SpringMVC articles

Table of contents

1. Workflow of SpringMVC (focus)

2. The main components of SpringMVC

Six main components:

Front controller DispatcherServlet (does not require programmers to develop)

Processor mapper HandlerMapping (does not require programmer development)

Processor adapter HandlerAdapter (does not require programmer development)

Processor Handler (requires programmer development)

View resolver ViewResolver (does not require programmer development)

View View (requires programmers to develop jsp)

Hands:

(1)HandlerMapping:

(2)HandlerAdapter:

(3)HandlerExceptionResolver:

(4)ViewResolver

(5)RequestToViewNameTranslator

(6)LocaleResolver

(7)ThemResolver:

(8)MultipartResolver:

(9)FlashMapManger:

 3. What is Spring MVC? Briefly introduce your understanding of SpringMVC

4. Advantages of Spring MVC

5. Commonly used annotations of SpringMVC

@RequestMapping:

@RequestBody:

@ResponseBody:

@RequestParam:

@PathVariable:

@Controller:

@RestController:

6. How to set redirection and forwarding in SpringMVC

Forward:

Redirect:

7. What are the differences between SpringMVC and Struts2?

8. How to solve the Chinese garbled problem of POST request?

9. How to solve the GET request garbled code

10. How to write the interceptor in springMVC?

In fact, the simple point is:

11. Is the controller of SpringMvc a singleton mode? If so, what is the problem and how to solve it?

12. The difference between interceptors and filters

filter

interceptor


1. Workflow of SpringMVC (focus)

  • In fact, the working process of springmvc mainly revolves around DispatchServerlet (front controller)
  • Several important components are HandleMapping (processor mapper), HandleAdapter (processor adapter), ViewReslover (view resolver)

Simplified workflow:

  1. First (front controller) DispatchServerlet receives user requests and sends requests to (processor mapper) HandleMapping
  2. Then (processor mapper) HandleMapping finds the specific handle and interceptor according to the request url, and returns it to (front controller) DispatchServerlet
  3. Then (front controller) DispatchServerlet calls (processor adapter) HandleAdapter, (processor adapter) HandleAdapter executes the specific controller, and returns the (view and model) ModelAndView returned by the controller to (front controller) DispatchServler
  4. Finally (front controller) DispatchServerlet renders the view according to the view and returns it to the user

(1) The user sends a request to the front controller DispatcherServlet

(2) DispatcherServlet receives a request to call HandlerMapping processor mapper

(3) The processor mapper finds the specific processor (can be searched according to the xml configuration and annotation), generates the processor and the processor interceptor (generated if there is one), and returns it to the DispatcherServlet

(4) DispatcherServlet calls HandlerAdapter processor adapter

(5) HandlerAdapter calls the specific processor (Controller, also known as the back-end controller) through the adapter

(6) Controller executes and returns to ModelAndView

(7) HandlerAdapter returns the controller execution result ModelAndView to DispatcherServlet

(8) DispatcherServlet passes ModelAndView to ViewReslover view resolver

(9) ViewReslover returns a specific view after parsing

(10) DispatcherServlet renders the view according to the View (that is, fills the model data into the view)

(11) DispatcherServlet responds to users


2. The main components of SpringMVC

Six main components:

Only the processor Handle and the view view require programmer development, and the other four do not require programmer development!

Front controller DispatcherServlet (does not require programmers to develop)


effect:

  • The results of receiving requests and responses are actually equivalent to transponders.
  • With DispatcherServlet, the coupling between other components is reduced.

Processor mapper HandlerMapping (does not require programmer development)


effect:

  • Find the Handler based on the requested URL

Processor adapter HandlerAdapter (does not require programmer development)


Notice:

  • When writing Handler, it should be written according to the rules required by HandlerAdapter, so that the processor adapter HandlerAdapter can correctly execute Handler.

Processor Handler (requires programmer development)

View resolver ViewResolver (does not require programmer development)


effect:

  • Analyze the view according to the logical name of the view and resolve it into a real view (view)

View View (requires programmers to develop jsp)

  • View is an interface, and its implementation class supports different view types (jsp, freemarker, pdf, etc.)

===============================================================================================================

Here is the detailed version:

Hands:

  • It's also a processor. It directly corresponds to the C in MVC, which is the Controller layer.
  • There are many specific forms of it, which can be classes or methods.
  • All methods marked with @RequestMapping in the Controller layer can be regarded as a Handler, as long as it can actually process the request, it can be Handler

(1)HandlerMapping:

  • initHandlerMapping(context), the handler mapper. Find the Handler based on the resource url requested by the user.
  • There will be many requests in springmvc, and each request needs a Handler to process. Which Handler to use after receiving a request, this is what HandlerMapping needs to do.

(2)HandlerAdapter:

  • initHandlerAdapters(context), adapter. Because the handle in springmvc can be in any form, as long as it can handle the request, it is ok.
  • However, the structure of the processing method required by the servlet is fixed, and they all use request and response as parameters.
  • How to make the fixed servlet processing method call the flexible handler for processing, this is what HandlerAdapter has to do

  • Handle is a tool for doing work
  • HandlerMapping is used to find the corresponding specific
  • HandlerAdapter is a person who uses tools to work

(3)HandlerExceptionResolver:

  • initHandlerExceptionResolver (context), other components are used to work.

  • In the process of working, it is inevitable that there will be problems. What should I do after problems occur?
  • This requires a dedicated role to handle exceptions. In springmvc it is HandlerExceptionResolver.
  • Specifically, the function of this component is to set the ModelAndView according to the exception, and then hand it over to the render method for rendering

(4)ViewResolver

  • initViewResolver (context), ViewResolver is used to resolve the String type view name and Locale into a View type view.
  • View is used to render the page, that is, fill in the parameters returned by the program into the template to generate HTML (or other types) files.

There are two key questions here:

Which template to use? What technical rules are used to fill in the parameters?

  • This is actually the main work of ViewResolver. ViewResolver needs to find the template used for rendering and the technology used (that is, the type of view) to render. The specific rendering process is completed by different views themselves.

(5)RequestToViewNameTranslator

  • initRequestToViewNameTranslator (context), ViewResolver searches for View based on ViewName, but some Handlers do not set View or ViewName after processing. At this time, ViewName needs to be obtained from request.
  • How to get ViewName from requset is what RequestToViewNameTranslator has to do.
  • Only one RequestToViewTranslator can be configured in the spring mvc container, so all the conversion rules from request to viewname must be implemented in one Translator

(6)LocaleResolver

  • initLocaleResolver (context), the parsing view requires two parameters: one is the view name, and the other is Locale.
  • The view name is returned by the processor, where does the Locale come from? This is what the LocaleResolver does. LocaleResolver is used to parse out Locale from requset. Locale is like zh-cn, which means a region. With this, different results can be displayed for users in different regions.
  • SpringMVC mainly uses Locale in two places: one is when ViewResolver views are parsed, and the other is when international resources or themes are used

(7)ThemResolver:

  • initThemResolver(context), for resolving themes.
  • There is a theme in SpringMVC corresponding to a properties file, which stores all resources related to the current theme, such as pictures, css styles, etc. The theme-related classes in SpringMVC are ThemeResolver, ThemeSource and Theme.
  • A theme is embodied through a series of resources. To get a theme resource, you must first get the name of the resource. This is the job of ThemResolver.
  • Then find the corresponding theme (can be understood as a configuration) file through the theme name, which is the job of ThemeSource. Finally, get the resources from the theme.

(8)MultipartResolver:

  • initMultipartResolver(context), used to handle upload requests.
  • The processing method is to wrap the ordinary requset into MultipartHttpServletRequest, which can directly call the getFile method to obtain the File. If multiple files are uploaded, it can also call getFileMap to obtain the Map of the FileName-> structure.
  • There are three methods in this component, which are used to judge whether it is an upload request, package the requset into a MultipartHttpServletRequest, and clean up the temporary resources generated during the upload process after processing

(9)FlashMapManger:

  • initFlashMapManger (context), used to manage FlashMap, FlashMap is mainly used to pass parameters in redirect


 3. What is Spring MVC? Briefly introduce your understanding of SpringMVC

  • SpringMVC is a request-driven lightweight web framework that implements the MVC design pattern based on Java.
  • Separate business logic, view, and data (mvc mode) through MVC mode, and then organize code to reduce the coupling between view and business logic, simplify development, and make the process clearer.


4. Advantages of Spring MVC

  • Various view technologies can be supported: jsp
  • Can be integrated with the spring framework
  • Supports mapping strategies for various request resources


5. Commonly used annotations of SpringMVC

@RequestMapping:

  • It is an annotation for processing request url mapping and can be used on classes or methods.

@RequestBody:

  • It is to realize the json data receiving http request and convert json to java object.

@ResponseBody:

  • It converts the object returned by the controller method into a json response to the client.

@RequestParam:

  • It is to bind the request parameters to the parameters of the controller's method.

@PathVariable:

  • It is a placeholder for binding url.
  • Supported after spring 3.0;
  • Spring MVC supports important signs of rest-style URLs. /user/{id}

@Controller:

  • Its tags can be scanned by spring and registered as beans in the context

@RestController:

  • Equivalent to @ResponseBody + @Contoller


6. How to set redirection and forwarding in SpringMVC

Forward:

  • Add forward before the return value;
  • For example forward:/hello.jsp

Redirect:

  • Add redirect before the return value;
  • For example redirect:/hello.jsp can also be a request such as redirect:/hello.do


7. What are the differences between SpringMVC and Struts2?

  • The entrance of springmvc is a servlet, the front controller (DispatchServlet)
  • The entry of struts2 is a filter filter (StrutsPrepareAndExecuteFilter)

  • springmvc is developed based on the method (in fact, a url corresponds to a method), and the request parameter is passed to the formal parameter of the method, which can be designed as a single case or a multi-case mode (but it is recommended to be a single case);
  • Struts2 is developed based on classes, passing parameters is through the attributes of the class, and can only be designed as multiple instances.

  • springmvc parses the content of the request through the parameter parser, assigns values ​​to the method parameters, encapsulates the data and views into ModelAndView objects, and finally transfers the model data in ModelAndView to the page through the requests domain.
  • Struts uses the value stack to store request and response data, and accesses data through OGNL;


8. How to solve the Chinese garbled problem of POST request?

  • Configure a CharacterEncodingFilter filter in web.xml and set it to utf-8

<filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>utf-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>


9. How to solve the GET request garbled code

  • Modify the tomcat configuration file to add the encoding consistent with the engineering encoding.
  • Re-encode the parameters; ISO8859-1 is the default encoding of tomcat, and the content encoded by tomcat needs to be encoded in utf-8.


10. How to write the interceptor in springMVC?

In fact, the simple point is:

  1. First, the custom class implements the HandlerInterceptor interface,
  2. Then override the preHandle method before processing
  3. Override the postHandle method after processing,
  4. Use the afterCompletion method when performing cleanup operations.
  5. Then inherit the adapter class and implement the processing logic in the interface method,
  6. Finally configure the interceptor in the SpringMVC configuration file.

<!-- 配置SpringMvc的拦截器 -->
<mvc:interceptors>
	<!-- 配置一个拦截器的Bean就可以了 默认是对所有请求都拦截 -->
	<bean id="myInterceptor" class="com.et.action.MyHandlerInterceptor"></bean>
	<!-- 只针对部分请求拦截 -->
 	<mvc:interceptor>
		<mvc:mapping path="/modelMap.do" />
			<bean class="com.et.action.MyHandlerInterceptorAdapter" /> 
	</mvc:interceptor>
</mvc:interceptors>


11. Is the controller of SpringMvc a singleton mode? If so, what is the problem and how to solve it?

  • First it is a singleton pattern

Solution:

  • In fact, do not write variables in the controller. If you must write them, you need to solve the synchronization problem yourself.


12. The difference between interceptors and filters

filter

  • Filters are part of the servlet specification and can be used in any Javaweb project.
  • /* is configured in <url-pattern>, which can perform an interception operation on all resources to be accessed.

interceptor

  • The interceptor is the springMVC framework itself, and only projects that use the springMVC framework can use the interceptor. (Earlier in the struct framework)
  • The interceptor will only intercept the method of the accessed controller, if the access is html/css/js/jsp/image, it will not be intercepted.
  • Interceptor is a specific application of AOP thought.

Guess you like

Origin blog.csdn.net/qq_46423017/article/details/127573414