SpringMVC其实是SpringFramework下的一个基于Servlet API的一个子项目。为啥叫SpringMVC呢?是因为它的源码部分的module是spring-webmvc,那么DispatchServlet里面我们都能做啥呢?
和多说的Servlet一样,DispatchServlet需要通过web.xml来声明和配置文件映射特定的Servlet。与此对应,DispatchServlet通过Spring的configuration来去查找delegate对应的请求映射,view视图解析,异常处理等
下面的粒子是基于Java文件的configuration注册和初始化DispatchServlet
public class MyWebApplicationInitializer implements WebApplicationInitializer {
@Override public void onStartup(ServletContext servletCxt) {
// Load Spring web application configuration AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext(); ac.register(AppConfig.class); ac.refresh();
// Create and register the DispatcherServlet DispatcherServlet servlet = new DispatcherServlet(ac); ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet); registration.setLoadOnStartup(1); registration.addMapping("/app/*"); }}
而接下来的是通过web.xml 进行configuration注册和初始化实现的DispatchServlert
<web-app>
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/app-context.xml</param-value> </context-param>
<servlet> <servlet-name>app</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value></param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<servlet-mapping> <servlet-name>app</servlet-name> <url-pattern>/app/*</url-pattern> </servlet-mapping>
</web-app>
也就是说Spring要想启动一个web项目有两种方式:web.xml配置和使用Java原生文件进行配置(SpringBoot采用的方式)
<error-page> <location>/error</location></error-page>
然后自己实现一个响应的hanler
@RestControllerpublic class ErrorController {
@RequestMapping(path = "/error") public Map<String, Object> handle(HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); map.put("status", request.getAttribute("javax.servlet.error.status_code")); map.put("reason", request.getAttribute("javax.servlet.error.message")); return map; }}