Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle of springmvc?

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What is the principle of springmvc? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

1. Spring mvc design idea and architecture composition

Knowledge point

Review of jsp implementation process

Spring mvc execution process parsing

Mvc architecture

1. Review the implementation process of servlet and jsp

Process description:

Request Servlet

Deal with business logic

Set up the business Model

Forward jsp Servlet

Jsp Servlet parsing encapsulates html return

Question: is this a MVC application scenario?

Spring mvc essentially uses Servlet processing, and encapsulates on it to simplify the development process, improve ease of use, and use the logical structure of the program to become clearer.

URL Mapping thanks based on Annotation

Http form parameter conversion

Global unified exception handling

Implementation of interceptor

2. Spring mvc execution process:

How is the whole process realized?

How does dispatchServlet find the corresponding Control?

How do I call a business method in Control?

Before we answer these questions, let's take a look at the spring mvc architecture.

3. Spring mvc architecture

HandlerMapping'h æ ndl / m æ p provinces

Mapping thanks of url and Controller

HandlerAdapter'h æ ndl é'd æ pt'

Controller execution adapter

ViewResolver vju'ri'z'lv'

View warehouse

View

Concrete parsing view

HandlerExceptionResolver'h æ ndl "k'sep" (") n ri" z "lv"

Anomaly trap

HandlerInterceptor'h æ ndl "nt"sept"

Interceptor

Configure a spring mvc example to demonstrate and verify the above process

Create a Controller class

Configure DispatchServlet

Create a spring-mvc.xml file

Configure SimpleUrlHandlerMapping

Configure InternalResourceViewResolver

Architecture UML

II. Analysis of mvc execution process

Knowledge points:

Specific implementation process of mvc

HandlerMapping detailed explanation

HandlerAdapter detailed explanation

Detailed explanation of ViewResolver and View

HandlerExceptionResolver detailed explanation

HandlerInterceptor detailed explanation

Execution flow of each component of mvc

2. Detailed explanation of HandlerMapping

It is the mapping between the url path and the Control object in mvc. DispatcherServlet is based on this component to find the corresponding Control. If it cannot be found, it will report the exception of Not Found mapping.

HandlerMapping interface method

HandlerMapping interface structure

The three mainstream mapping types are as follows:

BeanNameUrlHandlerMapping: based on the Bean that begins with "/" in ioc name, the line registers to Yingxie.

SimpleUrlHandlerMapping: based on manual configuration of url and control mapping

RequestMappingHandlerMapping: configure corresponding mapping thanks based on @ RequestMapping annotation

The demo is based on BeanNameUrlHandlerMapping configuration.

Write mvc files

/ / beanname control controller

Public class BeanNameControl implements HttpRequestHandler {

@ Override

Public void handleRequest (HttpServletRequest request, HttpServletResponse response)

Throws IOException, ServletException {

Request.getRequestDispatcher ("/ WEB-INF/page/userView.jsp") .forward (request, response)

}

}

When these classes are instantiated in IOC, DispatcherServlet finds the corresponding Handler based on request through the org.springframework.web.servlet.DispatcherServlet#getHandler () method. But when we find the corresponding Handler, we find that it is an Object type and does not implement a specific interface. How do I call Handler?

3. Detailed explanation of HandlerAdapter

Here, spring mvc uses the adapter pattern to adapt to the specified Handler, and different Adapter is used according to the type of Handler. The corresponding relationship between Handler and HandlerAdapter is as follows:

Handler category

Corresponding adapter

Description

Controller

SimpleControllerHandlerAdapter

Standard controller, returns ModelAndView

HttpRequestHandler

HttpRequestHandlerAdapter

The business processes the request on its own and does not need to go to the view through modelAndView

Servlet

SimpleServletHandlerAdapter

Standards-based servlet processing

HandlerMethod

RequestMappingHandlerAdapter

Processing based on @ requestMapping correspondence method

HandlerAdapter interface method

HandlerAdapter interface structure diagram

Demonstrate dealing with SimpleServletHandlerAdapter based on Servlet

/ / Standard Servlet

Public class HelloServlet extends HttpServlet {

@ Override

Protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Resp.getWriter () .println (hello luban)

}

}

In the above example, when these classes are instantiated in IOC, DispatcherServlet passes the

The org.springframework.web.servlet.DispatcherServlet#getHandlerAdapter () method looks up the adapter for the corresponding handler, and if it can't find it, it reports No adapter for handler.

4. Detailed explanation of ViewResolver and View

After finding the appropriate Adapter, the business process is called based on the adapter. After processing, the business party will return a ModelAndView and look up the corresponding view for processing. It traverses the viewResolvers list lookup in org.springframework.web.servlet.DispatcherServlet#resolveViewName () and reports a Could not resolve view with name exception if it cannot be found.

The next step is to get the corresponding View based on ViewResolver.resolveViewName () to parse the generated Html and return it. The corresponding VIEW structure is as follows:

At this point, the whole forward process is over, what if the program handles exception MVC at this time?

5. Detailed explanation of HandlerExceptionResolver

This component is used to indicate what to do with mvc when an exception occurs. DispatcherServlet calls the org.springframework.web.servlet.DispatcherServlet#processHandlerException () method, traverses the handlerExceptionResolvers to handle the exception, and returns errorView to jump to the exception view when the processing is complete.

Demonstrate custom exception capture

Public class SimpleExceptionHandle implements HandlerExceptionResolver {

@ Override

Public ModelAndView resolveException (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

Return new ModelAndView ("error")

}

}

HandlerExceptionResolver structure

In addition to the above components, my Interceptor interceptor mechanism is also introduced in spring, similar to Filter.

6. Detailed explanation of HandlerInterceptor

Demo HandlerInterceptor

Public class SimpleHandlerInterceptor implements HandlerInterceptor {

@ Override

Public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

System.out.println ("preHandle")

Return true

}

@ Override

Public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

System.out.println ("postHandle")

}

@ Override

Public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

System.out.println ("afterCompletion")

}

}

The implementation mechanism is based on HandlerExecutionChain to execute the following methods in the doDispatch method:

PreHandle: execution before business processing

PostHandle: after business processing (exception is not executed)

AfterCompletion: after view processing

Specific logic source code can be found in: org.springframework.web.servlet.DispatcherServlet#doDispatch method.

III. Annotation configuration

Demonstrate configuring mvc mapping based on annotations

/ / Annotation method

@ RequestMapping ("/ hello.do")

Public ModelAndView hello () {

ModelAndView mv = new ModelAndView ("userView")

Mv.addObject ("name", "luban")

Return mv

}

Ask why the entire configuration of mvc can be implemented based on configuration, and the previously mentioned handlerMapping and handlerAdapter components are no longer applicable.

Just look at the source of the class to see why:

Recognize the NamespaceHandler interface

View MvcNamespaceHandler

View AnnotationDrivenBeanDefinitionParser

Conclusion:

In the corresponding parser, two BeanDefinition are automatically registered with ioc. Are: RequestMappingHandlerMapping and BeanNameUrlHandlerMapping

The answer to the question about the principle of springmvc is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report