Writing in the front

Life is like a sea, only the strong will of the people can reach the other shore. I haven’t sent an article for a long time, I think everyone misses me, haha.

Let’s review the spring MVC today.

Introduction to Spring MVC and how it works

Spring’s model-View-Controller (MVC) framework is designed around a DispatcherServlet that dispatches requests to individual processors and supports configurable processor mapping, view rendering, localization, time zone and theme rendering, and even file uploading.

  • (1) Http request: the client request is submitted to DispatcherServlet.
  • (2) Find the handler: The DispatcherServlet Controller queries one or more HandlerMapping to find the Controller handling the request.
  • (3) Invoke handler: DispatcherServlet submits request to Controller.
  • Call business processing and return result: After the Controller calls business logic processing, return ModelAndView.
  • Handle view mapping and return model: DispatcherServlet queries one or more ViewResoler view parsers to find the view specified by ModelAndView.
  • (8) Http response: The view is responsible for displaying the results to the client.

Main annotations

ContextLoaderListener

Before talking about ContextLoaderListener, let’s look at what web.xml does.

  • A Web can be without a web. XML file, that is, a web. XML file is not required for a Web project. The web. XML file is used to initialize configuration information such as the Welcome page, servlet, servlet-mapping, filter, listener, launch load level, etc. When your Web project doesn’t use this, you can configure your Application without using the web.xml file.

  • When you want to start a Web project, the server software or container such as (tomcat) will first load the web. XML file in the project and start the project through various configurations in it. Only when all the configurations are correct, the project can be started correctly. Web.xml has multiple tags, which are loaded in the following order: context-param >> Listener >> fileter >> Servlet. (Multiple nodes of the same kind are loaded in the order of appearance)

The spring MVC startup process is roughly divided into two processes:

  • ContextLoaderListener initializes, instantiates the IoC container, and registers the container instance with the ServletContext.
  • The DispatcherServlet is initialized.

The ContextLoaderListener, which implements the ServletContextListener interface, is implemented by default when the web.xml is configured to start the container. The ContextLoader class is associated with the ContextLoaderListener, so the entire loading and configuration process is done by the ContextLoader.

  • Configuration of ContextLoaderListener in web.xml
<! <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <! -- ContextLoaderListerner --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>Copy the code

ServletContextListener interface has two methods: contextInitialized, contextDestroyed

DispatcherServlet

The Spring MVC framework, like many other Web MVC frameworks, is request-driven; The design revolves around a central Servlet that distributes all requests to the controller; It also provides other functions required by Web application development. But Spring’s central processing unit, DispatcherServlet, can do more than that.

The following figure shows the workflow of Spring Web MVC’s DispatcherServlet handling requests. Those familiar with design patterns will notice that DispatcherServlet applies a “front controller” design pattern (and many other good Web frameworks use this design pattern).

  • The flow chart

  • Configuration in web.xml
<! <servlet> <servlet-name> </servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>Copy the code

Among them

  • Load-on-startup: initializes the Servlet when the container is started.
  • Url-pattern: Indicates which requests are sent to Spring Web MVC for processing. The “/” is used to define the default servlet mapping. You can also block all requests with an HTML extension, as in *.html.

In Spring MVC, each DispatcherServlet holds its own context object, WebApplicationContext, which in turn inherits all beans already defined in the root WebApplicationContext object. These inherited beans can be overridden in specific Servlet instances, and within each Servlet instance you can define new beans within its scope.

WebApplicationContext inherits from ApplicationContext and provides some features that web applications often need. It differs from normal ApplicationContext in that it supports topic resolution and knows which servlet it is associated with (it holds a reference to that ServletContext)

Spring MVC also provides a number of special annotations for handling requests, rendering views, etc. These special beans are configured by default during DispatcherServlet initialization. If you want to specify which specific beans to use, you can simply configure them in the Web application context, WebApplicationContext.

Where, the ViewResolver configuration is commonly used. Take a JSP as a view

<! - on the interpretation of the name of the model view, that is, in the name of the model view before adding the suffix - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>Copy the code

Configure upload file limit MultipartResolver

<! - upload restrictions - > < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.Com monsMultipartResolver" > <! <property name="maxUploadSize" value="32505856"/> </bean>Copy the code

Tags in applicationContext.xml

File upload

The DispatcherServlet has a special Bean called MultipartResolver that can be used to limit file upload sizes, etc. When the parser MultipartResolver completes processing, the request is processed by normal flow just like any other request.

  • The form
<form method="post" action="/form" enctype="multipart/form-data">
     <input type="text" name="name"/>
     <input type="file" name="file"/>
     <input type="submit"/>
</form>
Copy the code
  • The controller
@RequestMapping(path = "/form", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { if (! file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return "redirect:uploadSuccess"; } return "redirect:uploadFailure"; }Copy the code

Exception handling

First, there are several ways to handle common exceptions, as shown in the following figure:

The implementation of Spring’s processor exception parser, the HandlerExceptionResolver interface, handles exceptions that occur during the execution of various controllers. Also mentioned above, are special beans in the DispatcherServlet that can be customized for configuration processing.

In some ways, HandlerExceptionResolver is similar to exception Mapping that you can define in your Web application descriptor web.xml file, but it provides a more flexible approach. For example, it can provide information about which processor was executing when the exception was thrown.

  • HandlerExceptionResolver provides the resolveException interface
public interface HandlerExceptionResolver {  
    ModelAndView resolveException(  
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);  
}
Copy the code
  • Handle exceptions in BaseController using the @ExceptionHandler annotation
@ExceptionHandler(Exception.class) public Object exceptionHandler(Exception ex, HttpServletResponse response, HttpServletRequest request) throws IOException { String url = ""; String msg = ex.getMessage(); Object resultModel = null; try { if (ex.getClass() == HttpRequestMethodNotSupportedException.class) { url = "admin/common/500"; System.out.println("-------- have found the corresponding method ---------"); } else if (ex. GetClass () = = ParameterException. Class) {/ / custom exception} else if (ex. GetClass () = = UnauthorizedException. Class)  { url = "admin/common/unauth"; System.out.println("-------- have permission ---------"); } String header = req.getHeader("X-Requested-With"); boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header); String method = req.getMethod(); boolean isPost = "POST".equalsIgnoreCase(method); if (isAjax || isPost) { return Message.error(msg); } else { ModelAndView view = new ModelAndView(url); view.addObject("error", msg); view.addObject("class", ex.getClass()); view.addObject("method", request.getRequestURI()); return view; } } catch (Exception exception) { logger.error(exception.getMessage(), exception); return resultModel; } finally { logger.error(msg, ex); ex.printStackTrace(); }}Copy the code
  • Handle exceptions in web.xml
<! -- Default error handling page --> <error-page> <error-code>403</error-code> <location>/403. HTML </location> </error-page> <error-page> <error-code>404</error-code> <location>/404.html</location> </error-page> <! Watch it only during debugging, do not comment it during deployment. If 500 errors occur, go to the 500.jsp page. --> <error-page> <error-code>500</error-code> <location>/500.html</location> </error-page> <! -- This configuration means that if a JSP page or servlet encounters an Exception of type java.lang.Exception (including subclasses, of course), it will be referred to a 500.jsp page. --> <error-page> <exception-type>java.lang.Exception</exception-type> <location>/500.jsp</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/500.jsp</location> </error-page> <! Error code: 500.jsp--> error code: 500.jsp--> error code: 500.jsp--> error code: 500.jspCopy the code
  • Here’s a question: Do HandlerExceptionResolver and the error-page configuration in web.xml conflict?

Solution: If resolveException returns a ModelAndView, the page in the returned value will be displayed first. However, resolveException can return null, in which case the 500 status code configuration page for error-Page in web.xml is displayed. When there is an error-page configuration in web.xml, null can be returned when the resolveException method is implemented. Return a corresponding ModelAndView to forward to, or NULL for default processing

Write in the last

The next article will write about Spring AOP, again in mind mapping style. Visual learning, so that Java is no longer difficult.

Finally, welcome to pay attention to my wechat public account Java mind Map, download map source files, as well as more Java mind map and project materials for you to learn, take you into the world of memory brain map.

Read the previous article

  • Spring Mind Map, make Spring not difficult (IOC)
  • Spring Mind Map, make Spring not difficult (1)