SpringMVC整合Servlet3.0
工程目录结构
MyWebApplicationInitializer.class
/**
* web容器启动的时候创建对象,调用方法来初始化容器的前端控制器
*/
public class MyWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 获取根容器的配置类(Spring的配置文件)父容器
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{RootConfig.class};
}
/**
* 获取web容器的配置类(SpringMVC的配置文件)子容器
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{AppConfig.class};
}
/**
* 获取DispatcherServlet的映射信息
* 拦截所有请求,包括静态资源xx.js,xx.jpg...,但是不包括*.jsp
* /*拦截所有请求,连*.jsp都会拦截,jsp页面是tomcat的引擎解析的
* 写成/就行
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
AppConfig.class
/**
* springmvc只扫描Controller,子容器
* useDefaultFilters = false,禁用默认的过滤规则
*/
@ComponentScan(value = "com.lun", includeFilters = {
@Filter(type = FilterType.ANNOTATION, value = {Controller.class})
}, useDefaultFilters = false)
@Configuration
public class AppConfig {
}
RootConfig
@ComponentScan(value = "com.lun", excludeFilters = @Filter(type = FilterType.ANNOTATION, value = {Controller.class}))
@Configuration
public class RootConfig {
}
HelloController.class
@Controller
public class HelloController {
@Autowired
private HelloService helloService;
@ResponseBody
@RequestMapping("hello")
public String hello() {
helloService.sayHello("world");
return "success";
}
}
HelloService.class
@Servicepublic class HelloService {
public void sayHello(String name) {
System.out.println("hello," + name);
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.lun</groupId>
<artifactId>springmvc-annotation</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.23.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
以上是 SpringMVC整合Servlet3.0 的全部内容, 来源链接: utcz.com/z/517098.html