A, spring mvc features
1. Review of servlet and jsp execution process
Flow Description:
- Servlet request
- Business logic
- Set Business Model
- forward jsp Servlet
- jsp Servlet returns parsed html package
2, spring mvc features
in the spring or essentially the Servlet mvc process, package and simplify the development process, improve ease of use, and using the program logic structure becomes more clearly on the basis thereof
- Annotation-based URL Xie Ying
- Form parameter mapping
- Caching
- Global unified exception handling
- Implement Interceptor
3, the request processing flow
4, spring mvc example
For ease of understanding, this gives a simple, minimal spring mvc configuration example:
web.xml servlet configuration:
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/spring-mvc.xml
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
复制代码
Written Controller Methods:
public class SimpleController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView modelAndView = new ModelAndView("/WEB-INF/page/userView.jsp");
modelAndView.addObject("name","cyan");
return modelAndView;
}
}
复制代码
Configuring spring-mvc.xml file
<bean name="/hello.do" class="com.cyan.controller.SimpleController"></bean>
复制代码
The whole process is how to achieve?
- How dispatchServlet find the corresponding Control?
- How to perform a business method invocations among Control?
In the interview to answer the above questions is good, we have to figure out spring mvc system components.
Two, mvc architecture Detailed
1, spring mvc framework to solve the problem
From a technical point of view to think, for any reason an existing framework for their existence, and that reason is to solve practical problems. Or provide a better solution to the problem solution. spring mvc it solves the problem?
- URL mapping
- Form parameter mapping
- Call the target Control
- Data model mapping
- View resolution
- Exception Handling
Solving the above problems are reflected in the spring mvc among the following components:
- Handler Mapping
- Xie mapping controller url
- Handler Adapter
- The controller executes adapter
- ViewResolver
- View warehouse
- view
- Specific analytical view
- HandlerExceptionResolver
- Abnormal catcher
- HandlerInterceptor
- Interceptor
Which corresponds to a specific uml follows:
mvc various components of the implementation process:
2, HandlerMapping Comments
Mvc url path to solve the problem of mapping and Controller image, DispatcherServlet is based on this component to find the corresponding Controller, if not found will be reported No mapping found for HTTP request with URI exception.
HandlerMapping interface structure analysis:
HandlerMapping action is to find the corresponding URL through Handler, but HandlerMapping.getHandler () method does not return directly to the image Handler, but returns to HandlerExecutionChain image, by HandlerExecutionChain.getHandler () returns the final handler
Common implementation class:
The three mainstream mapping as follows:
- SimpleUrlHandlerMapping: url based on manual configuration and control mapping Xie
- BeanNameUrlHandlerMapping: ioc name has been based on "/" at the beginning of the line when Bean registration to reflect Xie.
- RequestMappingHandlerMapping: configuring a corresponding enantiomeric Xie based annotation @RequestMapping
SimpleUrlHandlerMapping :
Written Controller Methods:
public class SimpleHandler implements HttpRequestHandler {
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("name","tangtang");
request.getRequestDispatcher("/WEB-INF/page/userView.jsp").forward(request,response);
}
}
复制代码
Write spring-mvc.xml profile:
<bean id="simpleHandler" class="com.cyan.handler.SimpleHandler"></bean>
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="order" value="100"></property>
<property name="mappings">
<props>
<prop key="hello2.do">simpleHandler</prop>
</props>
</property>
</bean>
复制代码
SimpleUrlHandlerMapping architecture:
SimpleUrlHandlerMapping key source initialization process:
> org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#setMappings()
> org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#initApplicationContext()
> org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#registerHandlers()
> org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#registerHandler()
复制代码
The main processes are: to map the path handler objects (if lazy loading, compared with the bean name) into LinkedHashMap
Get Handler Process Key Source:
> org.springframework.web.servlet.DispatcherServlet#getHandler()
> org.springframework.web.servlet.handler.AbstractHandlerMapping#getHandler()
> org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#getHandlerInternal()
> org.springframework.web.util.UrlPathHelper#getLookupPathForRequest()
> org.springframework.web.util.UrlPathHelper#getPathWithinApplication()
> org.springframework.web.servlet.handler.AbstractUrlHandlerMapping#lookupHandler()
> org.springframework.web.servlet.handler.AbstractHandlerMapping#getHandlerExecutionChain
复制代码
Main process: obtaining url path, find Handler, packaging execution chain
BeanNameUrlHandlerMapping :
BeanNameUrlHandlerMapping on a SimpleUrlHandlerMapping to realize, the only difference is inherited from AbstractDetectingUrlHandlerMapping, the handler can be found url mapping configuration in the absence of a case by a corresponding detectHandlers.
Schematic:
RequestMappingHandlerMapping:
Annotation-based implementation, in the following sections explain Xie Ying comment in detail when speaking.
Handler type :
In AbstractUrlHandlerMapping, we can see the storage handler of Map value type is Object, it means that all classes can do to Handler to use?
Handler corresponding type as follows:
- Controller Interface:
- HttpRequestHandler Interface:
- HttpServlet Interface:
- @RequestMapping method Notes
Handler can be seen that there is no unified interface, when dispatchServlet get the current corresponding Handler how to call it? Call it what method? There are two solutions: one is to use instanceof to determine Handler type and then calls related methods. Is achieved by introducing two adapters, each adapter implementation calls the specified Handler (spring latter)
3, HandlerAdapter Detailed
Here spring mvc mode by using an adapter adapted to call the specified Handler, different Adapter Handler depending on the type of which the Handler HandlerAdapter correspondence is as follows:
Handler Class | The corresponding adapter | description |
---|---|---|
Controller | SimpleControllerHandlerAdapter | Standard controller, return ModelAndView |
HttpRequestHandler | HttpRequestHandlerAdapter | Self-service processing request, does not need to view by modelAndView |
Servlet | SimpleServletHandlerAdapter | Standards-based servlet processing |
Handler Method | RequestMappingHandlerAdapter | The method of processing based on the corresponding @requestMapping |
HandlerAdapter interface methods :
FIG HandlerAdapter interface structure :
- The demonstration is based Servlet processing SimpleServletHandlerAdapter
Written Controller Methods:
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("hello lingqi");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
复制代码
Write spring-mvc.xml profile:
<bean id="/helloServlet" class="com.cyan.servlet.HelloServlet"></bean>
<bean class="org.springframework.web.servlet.handler.SimpleServletHandlerAdapter"></bean>
复制代码
After the above example, when the IOC instantiate classes, corresponding to the DispatcherServlet handler will look through the adapter org.springframework.web.servlet.DispatcherServlet # getHandlerAdapter () method, if no abnormality will be reported as follows: javax.servlet. ServletException: No adapter for handler ......
Gets Adapter Process Key Source:
> org.springframework.web.servlet.DispatcherServlet#getHandlerAdapter()
>
复制代码
4, ViewResolver with View Comments
After finding the corresponding Adapter adapter calls it will be based on business processing, after processing the business side will return a ModelAndView, to find the corresponding view for processing. In () in org.springframework.web.servlet.DispatcherServlet # resolveViewName traverse viewResolvers list to find, if not found it will report a Could not resolve view with name abnormalities.
BeanNameViewResolver example:
Writing a custom view:
public class MyView implements View {
@Override
public void render(Map<String, ?> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.getWriter().println("hello "+map.get("name"));
}
@Override
public String getContentType() {
return null;
}
}
复制代码
Write spring-mvc.xml profile:
<bean name="/myController" class="com.cyan.controller.MyController"></bean>
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"></bean>
<bean name="myView" class="com.cyan.view.MyView"></bean>
复制代码
Written Controller Methods:
public class MyController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
ModelAndView modelAndView = new ModelAndView("myView");
modelAndView.addObject("name","qingzi");
return modelAndView;
}
}
复制代码
InternalResourceViewResolver example:
Write spring-mvc.xml profile:
<bean name="/hello1.do" class="com.cyan.controller.SimpleController"></bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"/>
<property name="suffix" value=".jsp"/>
<property name="viewClass" value="org.springframework.web.servlet.view.InternalResourceView"/>
</bean>
复制代码
Written Controller Methods:
public class SimpleController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView("userView");
modelAndView.addObject("name","cyan");
return modelAndView;
}
}
复制代码
In the next step is based ViewResolver.resolveViewName () obtains the corresponding View returns to parse and generate Html. VIEW corresponding to the following structure: