This is the 16th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021 “.

👨🎓 author: Java Academic Conference

🏦 Storage: Github, Gitee

✏️ blogs: CSDN, Nuggets, InfoQ, Cloud + Community

💌 public account: Java Academic Party

🚫 special statement: the original is not easy, shall not be reproduced or copied without authorization, if you need to reproduce can contact xiaobian authorization.

🙏 Copyright notice: part of the text or pictures in the article come from the Internet and Baidu Encyclopedia, if there is infringement, please contact xiaobian as soon as possible. Wechat search public Java academic party contact xiaobian.

☠️ Daily toxic chicken soup: smile embrace every day, be like sunflower warm woman.

👋 Hello! I’m your old friend Java Academic Party. Recently xiaobian in the whole Spring family bucket notes, notes will be issued regularly every day, like the big guys welcome to collect points like attention yo. Xiaobian will share it every day. Today we bring you a new framework technology, SpringMVC.

Spring MVC is a successor to the Spring Framework and has been integrated into Spring Web Flow. The Spring framework provides a full-featured MVC module for building Web applications. Use Spring’s pluggable MVC architecture so that you can choose to use Spring’s Spring MVC framework or integrate with other MVC development frameworks when using Spring for WEB development.

Chapter 4 SpringMVC core technology

4.1 Request Redirection and Forwarding

  • After processing a request, a processor can jump to another resource in two ways: request forwarding and redirection. Depending on the type of resource to jump to, there are two types: jump to page and jump to other processors.
  • Note that for a page requesting a forward, it can be a web-INF page; The redirected page cannot be a web-INF page. Because a redirect is equivalent to the user making another request, the user cannot directly access the WEB-INF Chinese source

The SpringMVC framework encapsulates the request forwarding and redirection operations in the original Servlet. Forwarding and redirection can now be implemented in a simple manner.

  • Forward: forward, to achieve the request. GetRequestDispatcher (” xx. JSP “). The forward ()
  • Redirect: Response.sendredirect (“xxx.jsp”)

4.4.1 Requesting forwarding

  • When the handler method returns ModelAndView, add forward: to the view specified by setViewName(), and the view no longer works with the view parser, so that views at different locations can be specified when the parser is configured. The view page must write out the path relative to the project root. The forward operation does not require a view parser.
  • Processor method Mandatory String, adding forward to the view path: full view path.
@RequestMapping(value = "/some.do") public ModelAndView doSome(String name,int age){ ModelAndView mv = new ModelAndView(); mv.addObject("myName",name); mv.addObject("myAge",age); */ mv.setviewName ("forward:/ web-INF /view/show.jsp"); return mv; }Copy the code

4.1.2 Requesting Redirection

  • You can redirect by adding redirect: to the view string returned by the processor method.
@RequestMapping(value = "/some2.do") public ModelAndView doSome2(String name,int age){ ModelAndView mv = new ModelAndView(); /* The data is placed in the request scope */ mv.addobject ("myName",name); mv.addObject("myAge",age); /* Use the redirect to redirect the request */ /* Use the redirect to redirect the request */ / use the mv.setviewName ("redirect:/show.jsp"); // http://localhost:8080/myWeb/show.jsp? myName=lisi&myAge=20 return mv; }Copy the code

4.2 Exception Handling

  • A common way the SpringMVC framework handles exceptions is by using the @ExceptionHandler annotation.

2 @ ExceptionHandler annotation

  • The @ExceptionHandler annotation is used to specify a method as an exception handling method. The annotation has only one optional attribute, value, which is a Class array that specifies the exception Class to be handled by the annotation’s method, that is, the exception to be matched.
  • The return value of an annotated method can be ModelAndView, String, or void, and the method name can be arbitrary. The method parameters can be Exception and its subclasses, HttpServletRequest, HttpServletResponse, and so on. The system automatically assigns values to these method parameters.
  • For the use of exception handling annotations, it is also possible to annotate exception handling methods directly into the Controller.

(1) Custom exception class

Define three exception classes: NameException, AgeException, and MyUserException. MyUserException is the parent of the other two exceptions.

Public class MyUserException extends Exception{/* Public MyUserException() {super(); } public MyUserException(String message) { super(message); }}Copy the code
Public class AgeException extends MyUserException{public AgeException() {super(); } public AgeException(String message) { super(message); }}Copy the code
/* * An exception is thrown when an exception exists in the user name. Throws NameException * */ public Class NameException extends MyUserException{public NameException() {super(); } public NameException(String message) { super(message); }}Copy the code

(2) Modify Controller to throw an exception

/* * This class uses Java code to handle exceptions (i.e. try... * */ @controller public class MyController {@requestMapping (value = "/exception.do") public ModelAndView exception(String name,int age) throws MyUserException { ModelAndView mv = new ModelAndView(); // Throw an exception according to the request parameters /* * the order of processing: If the first if condition is met, the program enters the exception class. Instead of continuing to execute the handler method, it jumps to the class that handled the exception, which is flagged by the @ControllerAdvice annotation. Here is the GlobalExceptionHandel class. * * In the exception class, according to the type of exception thrown, the exception class will look for the value of the value attribute in the annotation on the method marked by @ExceptionHandler(value = nameException.class) * and handle the exception. * */ if (!" Equals (name)){throw new NameException(" Input name incorrect!" ); } the if (age = = 0 | | age > 80) {/ * specified here throws an exception information equivalent to system exceptions thrown, NullPointException throws new AgeException(" age invalid! ") ); } mv.addObject("myName",name); mv.addObject("myAge",age); mv.setViewName("show"); return mv; }}Copy the code

(3) Define the abnormal response page

Define three exception response pages.

  • However, this is not generally used. Instead, the exception handling methods are specifically defined in a class and handled as global exceptions.
  • You need to use the @controllerAdvice annotation, which literally means’ controller enhancement ‘, to enhance controller objects. A class decorated with @ControllerAdvice can use @ExceptionHandler
  • When an exception is thrown by a method decorated with the @RequestMapping annotation, the exception handling method in the @ControllerAdvice modified class is executed.
  • @ControllerAdvice is decorated with the @Component annotation to scan the classpath (package name) of @ControllerAdvice and create an object.

(4) Define global exception handling classes

/* * @controllerAdvice: Control class enhancements * Location: on top of the class * Features: The framework must know the name of the package in which this annotation is located. A component scanner needs to be added to the SpringMVC configuration file. This uses AOP techniques in Spring to add non-business methods to the existing business code. * Such as logs, error messages, etc. * */ @controllerAdvice Public class GlobalExceptionHandel {// Define the method to handle the exception that occurs /* * The method to handle the exception is the same as the method to handle the controller. Common data types, Object Object types, lists, and Map collections can be used. * There are multiple return value types ModelAndView, String, void object, list object collection. * * parameter: Exception. Represents the exception object thrown in the Controller. * Parameters can be used to obtain information about the exception that occurred. * * @ExceptionHandel(value = exception class. Class) : Indicates the type of exception. When this type of exception occurs, the current method handles it. * */ /* * The way SpringMVC handles exceptions, it receives an exception in the Controller class and then looks for a method to handle the exception in the Controller class, matching it with the value of the @ExceptionHandler annotation. If the Controller class throws an exception that does not match the @ExceptionHandler value, the method for the @ExceptionHandler annotation that did not end with a value is executed. * * Note: only one @ExceptionHandler annotation can exist without the value attribute. The equivalent of the if... Else of else. * */ @ExceptionHandler(value = NameException.class) public ModelAndView doNameException(Exception exception){ // Handle NameException exceptions. * 1. The exception needs to be recorded in a log file or database. * Record the log time, which method occurred, and the content of the exception information. * 2. Send notification, send abnormal information to relevant personnel by email, SMS, or MAINTENANCE. * * 3. Give the user a nice complexity. * */ ModelAndView mv = new ModelAndView(); AddObject (" MSG "," name must be Chenyunbo, other users can not access! "); ); // Exception object, this is equivalent to the object that the system throws the exception. For example, the NullPointException object. // Or our custom AgeException, NameException. mv.addObject("ex",exception); mv.setViewName("nameError"); return mv; } @ExceptionHandler(value = AgeException.class) public ModelAndView doAgeException(Exception exception){ // Handle exceptions for AgeException. * 1. The exception needs to be recorded in a log file or database. * Record the log time, which method occurred, and the content of the exception information. * 2. Send notification, send abnormal information to relevant personnel by email, SMS, or MAINTENANCE. * * 3. Give the user a nice complexity. * */ ModelAndView mv = new ModelAndView(); Mv.addobject (" MSG "," Your age does not meet the requirements!" ); // Exception object mv.addobject ("ex",exception); mv.setViewName("ageError"); return mv; } // Handle other exceptions, exceptions other than NameException, AgeException, unknown exception types // When the error message is not NameException, AgeException, Leave it to this method to handle the Exception @ExceptionHandler public ModelAndView doOtherException(Exception Exception){// Handle other exceptions. * 1. The exception needs to be recorded in a log file or database. * Record the log time, which method occurred, and the content of the exception information. * 2. Send notification, send abnormal information to relevant personnel by email, SMS, or MAINTENANCE. * * 3. Give the user a nice complexity. * */ ModelAndView mv = new ModelAndView(); Mv.addobject (" MSG "," Your age does not meet the requirements!" ); // Exception object mv.addobject ("ex",exception); mv.setViewName("defaultError"); return mv; }}Copy the code

(5) Define the Spring configuration file

<? The XML version = "1.0" encoding = "utf-8"? > <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <! --SpringMVC configuration file that declares controllers and other Web-related objects --> <! - announcement component scanner, using dynamic proxy way to create the dynamic proxy Servlet object - > < context: component - scan base - package = "com. Yunbocheng. Controller" / > <! - the parser configuration view - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > <! -- Here we use the value attribute, <property name="prefix" value="/WEB-INF/view/" /> <property name="suffix" value=". <! < MVC :annotation-driven/> <! MVC :annotation-driven/> <! <context:component-scan base-package="com.yunbocheng.handel"/> </beans>Copy the code

4.3 the interceptor

  • The Interceptor Interceptor in SpringMVC is very important and quite useful. Its main function is to intercept the specified user request, and carry out the corresponding pre-processing and post-processing. The interception occurs when “the processor mapper maps the processor class to be executed based on the request submitted by the user and also finds the processor adapter to execute the processor class before the processor adapter executes the processor.” Of course, when the processor mapper maps the processor class to be executed, the interceptor and processor are already combined into a processor execution chain that is returned to the central scheduler.

4.3.1 Execution of interceptors

Custom interceptors

/* * This is an interceptor class that inherits the HandlerInterceptor interface and implements three of its classes. * * This class is used to intercept user requests. * */ public class MyInterceptor implements HandlerInterceptor {// Implements HandlerInterceptor. View the source code can see that the three methods are using the Default declaration method // so we do not need to implement all three methods // we implement these three methods here. /* * preHandle() : This method is called the preHandle method. Return value: Boolean * true: Indicates that the request has been authenticated by the interceptor and can be processed by the handler method. False: indicates that the request has not been authenticated by the interceptor and cannot be processed by a processor method. 1. Methods are executed before controller methods (MyController's doSome). * The user's request first arrives in this method * 2. In this method, the requested information can be retrieved. Verify that the request meets the requirements. * Can verify that the user can log in and that the user has permission to access a connection address (URL) * If authentication fails, the request can be truncated and the request cannot be processed. * If the validation succeeds, the request can be released and the controller method can be executed. * */ private long bTime; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { bTime = System.currentTimeMillis(); System.out.println(" MyInterceptor's perHandler()"); // Business logic checks in this method, returns true or false, and controls whether the request can be passed to the handler method for processing. / * when the request is stopped interceptor, the browser to a return page results. * / / * request getRequestDispatcher ("/tips. JSP "). The forward (request, response); */ return true; } /* * postHandle: post-processing method. Object Handler: Intercepts the handler Object MyController. ModelAndView: The return value of the processor method. * 1. The method is executed after the method (myController.dosome ()) * 2. Can get the return value of the processor method ModelAndView, can modify the * data and view in ModelAndView, can affect the final execution result. * 3. Perform secondary modifications to the original execution result. * */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView ModelAndView) throws Exception {/* This method is executed only if the preprocessing method returns true*/ Println (" MyInterceptor postHandle()"); system.out.println (" MyInterceptor postHandle()"); // Process the return value of the original processor method. if (modelAndView ! = null){// Add data from the return value modelAndView.addobject ("myDate",new Date()); // Modify the returned value of the data modelAndView.addobject ("myAge",40); // Modify the returned view modelAndView.setViewName("other"); }} /* * afterCompletion: The last method to be executed * parameters: * Object Handler: the processor Object to be intercepted. * Exception ex: An Exception that occurs in a program. * Features: * 1. Is executed after the request processing is complete. The stipulation in the framework is that when your view is finished processing, you perform a forward on the view. The request processing is considered complete. * 2. Generally do resource recovery work, program request process to create some objects, here can be deleted, the occupied memory recovery. * */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {system.out.println (" afterCompletion of MyInterceptor "); long eTime = System.currentTimeMillis(); System.out.println(" calculate the time between preHandler and request completion: "+ (etime-btime)); }}Copy the code

Custom interceptor, need to implement the HandlerInterceptor interface. This interface contains three methods:

Preparation of request, Response, Object handler: This method is executed before the handler method is executed. The return value is Boolean, and if true, the processor method is followed and the afterCompletion() method is placed on a special method stack to wait for execution.

Preparation, preparation, preparation, preparation, preparation, preparation, preparation, preparation. A processor method does not execute if it is not eventually executed. Since the method is executed after the processor method is executed and the method parameter contains ModelAndView, the method can modify the processing result data of the processor method and change the jump direction.

Completion(Request, Response, Object handler, Exception ex) : When the preHandle() method returns true, it is placed on a special stack of methods and is not executed until all work has been done to respond to the request. That is, the method is executed after the central scheduler has rendered (filled with data) the response page, at which point the ModelAndView operation does nothing for the response.

The last method performed by afterCompletion clears resources, such as adding data to the Controller method

The sequence of methods and handler methods in the interceptor is shown below:

To put it another way, it can also be understood as follows:

(1) Register interceptors

  • Used to specify the request path that the currently registered interceptor can intercept, with /** indicating that all requests are intercepted.

(2) Modify index page

(3) Modify the processor

(4) Modify the Show page

(5) Console output results

For the source code of the above project, click planet for free accessplanet(Github address) If you don’t have a Github partner. You can follow my wechat official account:Java academic lie prone, send SpringMVC, free to send everyone the project source code, the code is personally tested by the small editor, absolutely reliable. It’s free to use.