SpringMVC请求处理流程
1 添加相关依赖
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.17.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
2 使用Java方式搭建SpringMVC
1)配置DispatcherServlet
package com.musi;
import com.musi.config.RootConfig;
import com.musi.config.WebConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* @Author:musi
* @Date:2019/8/18
* @Description:
*/
public class SpittrWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
AbstractAnnotationConfigDispatcherServletInitializer剖析
在Servlet3.0环境中,容器会在类路径下查找实现javax.servlet.ServletContainerInitializer接口的类,如果能发现的话,就会用它来配置Servlert容器.Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这个类反过来又会查找实现WebApplicationInitializer的类并将配置的任务交给它们来完成。Spring3.2引入了一个便利的WebApplicationInitializer基础实现,也就是AbstractAnnotationConfigDispatcherServletInitializer。程序中SpittrWebAppInitializer 扩展了AbstractAnnotationConfigDispatcherServletInitializer,因此当部署到Servlet3.0容器中的时候,容器会自动发现它,并用它类配置Servlet上下文
三个方法的解析:
getServletMappings();将一个或多个路径映射到DispatcherServlet上,本例中映射的是"/",这表示它会是应用的默认Servlet,它会处理应用的所有请求
当DispatcherServlet启动的时候,它会创建Spring应用上下文,并加载配置文件或配置类中所声明的bean。在上面程序的getServletConfigClasses()方法中,我们要求DispatcherServlet加载应用上下文时,使用定义在WebConfig配置类(使用Java配置)中的bean。但是在SpringWeb应用中,通常还会有另外一个应用上下文。另外的这个应用上下文是由ContextLoaderListener创建的。我们希望DispatcherServlet加载包含Web组件的bean,如控制器、视图解析器以及处理器映射,而ContextLoaderListener要加载应用中的其他bean。这些bean通常是驱动应用后端的中间层和数据层组件。实际上,AbstractAnnotationConfigDispatcherServletInitializer会同时创建DispatcherServlet和ContextLoaderListener。GetServletConfigClasses()方法返回的带有@Configuration注解的类将会用来定义DispatcherServlet应用上下文中的bean。getRootConfigClasses()方法返回的带有@Configuration注解的类将会用来配置ContextLoaderListener创建的应用上下文中的bean。
注意:通过AbstractAnnotationConfigDispatcherServlet-Initializer来配置DispatcherServlet是传统web.xml方式的替代方案。如果你愿意的话,可以同时包含web.xml和AbstractAnnotationConfigDispatcher-ServletInitializer,但这其实并没有必要。如果按照这种方式配置DispatcherServlet,问题在于它只能部署到支持Servlet3.0的服务器中才能正常工作,如Tomcat7或更高版本。
2)配置WebConfig
/**
* @Author:musi
* @Date:2019/8/18
* @Description:
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.musi")
public class WebConfig extends WebMvcConfigurerAdapter{
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
}
3)配置rootconfig
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/**
* @Author:musi
* @Date:2019/8/18
* @Description:
*/
@Configuration
@ComponentScan(basePackages = {"com.musi"},excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = EnableWebMvc.class)})
public class RootConfig {
}
- 编辑controller
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @Author:musi
* @Date:2019/8/25
* @Description:
*/
@Controller
public class HomeController {
@RequestMapping(value="/",method = RequestMethod.GET)
public String home(){
return "home";
}
}
5)编辑home页
6)测试控制器
/**
* @Author:musi
* @Date:2019/8/25
* @Description:
*/
public class HomeControllerTest {
@Test
public void testHomePage(){
HomeController controller = new HomeController();
Assert.assertEquals("home",controller.home());
}
@Test
public void testHome() throws Exception {
HomeController controller = new HomeController();
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get("/")).andExpect(view().name("home"));
}
}
7)自定义DispatcherServlet配置
配置springMVC时,除了实现AbstractAnnotationConfigDispatcherServletInitializer必须的三个抽象方法外,还可以有更多的方法可以重载.其中之一便是customizeRegistration().通过重载customizeRegistration()方法,我们可以对DispatcherServlet进行额外的配置.
如下所示:
@Override
protected void customizeRegistration(Dynamic registration){
registration.setMultipartConfig(new MultipartConfigElement("/tmp/spittr/uploads")); //设置对multipart的支持,将上传文件的临时目录设置为"tmp/spittr/uploads"
}
8)添加其他servlet和filter
import com.musi.filter.MyFilter;
import com.musi.servlet.MyServlet;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.WebApplicationInitializer;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
/**
* @Author:musi
* @Date:2019/8/25
* @Description:
*/
public class MyServletInitializer implements WebApplicationInitializer {
/***
* 注册servlet
* @param servletContext
* @throws ServletException
*/
/*@Override
public void onStartup(ServletContext servletContext) throws ServletException {
ServletRegistration.Dynamic myservlet = servletContext.addServlet("myServlet", MyServlet.class);
myservlet.addMapping("/custom*//**");
}*/
/**
* 注册过滤器
* @param servletContext
* @throws ServletException
*/
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// 注册过滤器
FilterRegistration.Dynamic filter = servletContext.addFilter("myFilter", MyFilter.class);
filter.addMappingForUrlPatterns(null,false,"custom/**");
// 注册servlet
ServletRegistration.Dynamic myservlet = servletContext.addServlet("myServlet", MyServlet.class);
myservlet.addMapping("/custom/**");
}
备注:如果只是注册Filter,并且该Filter只会映射到DispatcherServlet上,那么还有一种快捷的方式,如下: