maven+spring mvc环境搭建注解版(无web.xml,maven jetty插件运行)

环境:

Spring Framework 4.3.7.RELEASE

Servlet 3.1.0

JDK 1.8


创建maven webapp项目:maven-spring-webmvc  项目结构如下:

maven+spring mvc环境搭建注解版(无web.xml,maven jetty插件运行)_第1张图片


各文件代码如下:

pom.xml


	4.0.0
	com.pp
	maven-spring-webmvc
	war
	1.0.0

	maven-spring-webmvc
	http://maven.apache.org

	
		UTF-8
		1.8
		1.8
	

	
		
			javax.servlet
			javax.servlet-api
			3.1.0
			provided
		
		
			org.springframework
			spring-webmvc
			4.3.7.RELEASE
		
	

	
		
			
			
				org.eclipse.jetty
				jetty-maven-plugin
				9.4.2.v20170220
				
					foo
					9999
					
						
						9090
					
					
						/
					
				
			
			
				org.apache.maven.plugins
				maven-war-plugin
				3.0.0
				
					
					false
				
			
		
	



package com.pp.web;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * 启用mvc
 */
@EnableWebMvc
/**
 * 设置componen的扫描包路径 
 */
@ComponentScan("com.pp.web")
public class AppConfig {

}

package com.pp.web;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

/**
 * 系统初始化入口
 */
public class AppDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

	/**
	 * 设置spring容器启动的入口
	 */
	@Override
	protected Class[] getRootConfigClasses() {
		return new Class[]{AppConfig.class};
	}

	@Override
	protected Class[] getServletConfigClasses() {
		return null;
	}

	/**
	 * 设置DispatcherServlet的拦截路径
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[]{"/"};
	}
}

package com.pp.web;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 *  定制mvc
 */
@Configuration
public class AppWebMvcConfigurer extends WebMvcConfigurerAdapter {

	/**
	 * 配置静态资源的映射
	 */
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
	    registry.addResourceHandler("/static/**").addResourceLocations("/static/");
	}
}

package com.pp.web.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

	@GetMapping("/index")
	public String index(){
		return "hello index";
	}
}

最后,在项目的跟目录执行mvn clean jetty:run 运行项目

访问

http://127.0.0.1:9090/index  访问controller

http://127.0.0.1:9090/static/list.html  访问静态资源





你可能感兴趣的:(Spring,maven,spring,mvc)