1.Spring Web MVCreact
Spring MVC是基於Servlet API開發的原生web框架,其名字來源於在Spring項目的模塊名稱(spring-webmvc)。web
Spring還推出了基於reactive棧的web框架 Spring WebFlux。
Parallel to Spring Web MVC, Spring Framework 5.0 introduced a reactive-stack web framework whose name, 「Spring WebFlux,」 is also based on its source module (spring-webflux). This section covers Spring Web MVC. The next section covers Spring WebFlux.算法
1.1. DispatcherServletspring
Spring MVC圍繞一個Servlet(DispatcherServlet)設計,提供對於不一樣請求的分享算法,實際的工做由框架配置的組件完成。mvc
DispatcherServlet須要經過Java代碼或者web.xml進行配置,同時DispatcherServlet經過Sprong配置來發現業務組如請求路由匹配,視圖解析器,異常處理等等。app
如下代碼示範瞭如何經過代碼註冊並初始化一個DispatcherServlet,它會被Servlet容器自動檢測到:框架
public class MyWebApplicationInitializer implements WebApplicationInitializer {ide
@Override public void onStartup(ServletContext servletCxt) { // Load Spring web application configuration AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext(); // You need a Spring context configuration class name APPConfig.class 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配置DispatcherServlet:url
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <!-- you need a Spring context configuration file name app-context.xml --> <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>