Spring MVC-9. Custom Interceptor, Exception Handling

Keywords: Spring Java

12. Custom Interceptor

1.helloworld

Spring MVC can also use interceptors to intercept requests. Users can customize interceptors to achieve specific functions. A customized interceptor must implement the Handler Interceptor interface:

preHandle(): This method is called before the business processor processes the request, in which the user request is processed. If the programmer decides that the interceptor will call another interceptor after intercepting the request, or the business processor will process the request, it will return true; if the programmer decides that no other component is needed to process the request, it will return false.

PosHandle (): This method is after the business processor has processed the request, but the Dispatcher Servlet Called before returning the response to the client, the user request is processed in this method.

afterCompletion(): This method is in Dispatcher Servlet is invoked after processing the request completely, and some resource cleaning operations can be performed in this method.

 

public classFirstInterceptor implements HandlerInterceptor{
   /**
    * This method is called before the target method.
    * If the return value is true, the subsequent interceptors and target methods will continue to be invoked.
    * If the return value is false, subsequent interceptors and target methods will not be invoked.
    *
    * Consider permissions, logs, transactions, etc.
    */
   @Override
   public voidafterCompletion(HttpServletRequest arg0,
         HttpServletResponsearg1, Object arg2, Exception arg3)
         throws Exception {
      System.out.println("FirstInterceptor:afterCompletion");
     
   }
 
   /**
    * After calling the target method, but before rendering the view.
    * Attributes or views in the request domain can be modified.
    */
   @Override
   public voidpostHandle(HttpServletRequest arg0, HttpServletResponse arg1,
         Objectarg2, ModelAndView arg3) throws Exception {
      System.out.println("FirstInterceptor:postHandle");
     
   }
 
   /**
    * Before the target method
    * If the return value is true, the subsequent interceptor and target method will continue to be invoked.
    * If the return value is false, no
    */
   @Override
   public booleanpreHandle(HttpServletRequest arg0, HttpServletResponse arg1,
         Objectarg2) throwsException {
      System.out.println("FirstInterceptor:preHandle");
      return true;
   }
 
}

2. Interceptor method execution sequence

3. Configuring custom interceptors

<mvc:interceptors>
     
      <!-- To configure LocaleChanceInterceptor -->
      <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
  
      <!-- Configuring custom interceptors -->
      <bean class="spring.interceptors.FirstInterceptor"></bean>
  
      <!-- Configuring Interceptors(No)Path of action -->
      <mvc:interceptor>
         <mvc:mapping path="/emps"/>
         <bean class="spring.interceptors.SecondInterceptor"></bean>
      </mvc:interceptor>
   </mvc:interceptors>
public classSecondInterceptor implements HandlerInterceptor{
 
   @Override
   public booleanpreHandle(HttpServletRequest request,
         HttpServletResponseresponse, Object handler) throws Exception {
      System.out.println("[SecondInterceptor] preHandle");
      return false;
   }
 
   @Override
   public void postHandle(HttpServletRequestrequest,
         HttpServletResponseresponse, Object handler,
         ModelAndViewmodelAndView) throwsException {
      System.out.println("[SecondInterceptor] postHandle");
   }
 
 
   @Override
   public voidafterCompletion(HttpServletRequest request,
         HttpServletResponseresponse, Object handler, Exception ex)
         throws Exception {
      System.out.println("[SecondInterceptor] afterCompletion");
   }
 
}

4. Interceptor sequence

 

 

13. Abnormal handling

1. exception handling

Spring MVC handles exceptions through the Handler Exception Resolver handler, including handler mapping, data binding, and exceptions that occur when the target method is executed.

Implementing class of Handler Exception Resolver provided by Spring MVC

 

2. HandlerExceptionResolver

Dispatcher Servlet default assembly of Handler Exception Resolver:

No < mvc: annotation-driven/> configuration was used:

Using the <mvc: annotation-driven/> configuration -:

Mainly deals with methods defined in Handler with the @ExceptionHandler annotation.

The first way is:

@RequestMapping("/testExceptionHandlerExceptionResolver")
   public StringtestExceptionHandlerExceptionResolver(@RequestParam("i")inti){
      System.out.println("result: "+ (10 / i));
      return "success";
   }
   /**
    * 1. The parameter of Exception type, which corresponds to the exception object, can be added to the parameter of @ExceptionHandler method.
    * 2. @ExceptionHandler Method input cannot be passed into Map. If you want to transmit exception information on the page, you need to use ModelAndView as the return value.
    * 3. @ExceptionHandler Exceptions marked by methods have priority problems.
    * 4. @ControllerAdvice: If the @ExceptionHandler method cannot be found in the current Handler to extract the exception from the current method,
    * The @ExceptionHandler tag will be looked up in the @Controller Advice tag class to handle exceptions.
    */
   @ExceptionHandler({ArithmeticException.class})
   public ModelAndViewhandleArithmeticException(Exception ex){
      System.out.println("Abnormal.: " + ex);
      ModelAndViewmv = newModelAndView("error");
      mv.addObject("exception",ex);
      return mv;
   }


@ Method priority issues defined by ExceptionHandler annotations:

For example, NullPointerException occurs, but the declared exceptions are RuntimeException and Exception, and then the @ExceptionHandler annotation method with the shallowest inheritance depth, that is, the method marked RuntimeException, is found based on the recent inheritance relationship of the exception.

If the @ExceptionHandler annotation is not found in ExceptionHandler Method Resolver, it will be found

@ ExceptionHandler in Controller Advice Annotation method

The second way (recommendation):

@ControllerAdvice
public classSpringMVCTestExceptionHandler {
 
   @ExceptionHandler({ArithmeticException.class})
   public ModelAndViewhandleArithmeticException(Exception ex){
      System.out.println("----> Abnormal.: " + ex);
      ModelAndViewmv = newModelAndView("error");
      mv.addObject("exception",ex);
      return mv;
   }
}

3. ResponseStatusExceptionResolver

Find the @ResponseStatus annotation in the exception and exception parent class, and then use the properties of the annotation to process it. Define an exception class modified by the @ResponseStatus annotation

@ResponseStatus(value=HttpStatus.FORBIDDEN, reason="User name password mismatch!")
public classUserNameNotMatchPasswordException extends RuntimeException{
 
   private static final long serialVersionUID= 1L;
 
}

If the above exception is thrown in the processor method:

If Exception Handler Exception Resolver does not resolve the exception. Because the triggered exception Unauthorized Exception has the @ResponseStatus annotation. Therefore, it will be parsed to ResponseStatusException Resolver. Finally, respond to the HttpStatus.UNAUTHORIZED code to the customer

End. HttpStatus.UNAUTHORIZED stands for response code 401 and has no privileges. Refer to the HttpStatus Enumeration Type Source for other response codes.

//@ ResponseStatus(reason = test, value=HttpStatus.NOT_FOUND)
   @RequestMapping("/testResponseStatusExceptionResolver")
   public StringtestResponseStatusExceptionResolver(@RequestParam("i")inti){
      if(i == 13){
         throw newUserNameNotMatchPasswordException();
      }
      System.out.println("testResponseStatusExceptionResolver...");
     
      return "success";
   }

4. DefaultHandlerExceptionResolver

Handling special exceptions, such as NoSuchRequest Handling Method Exception,

HttpRequest Method NotSupported Exception, HttpMediaTypeNotSupported Exception, HttpMediaTypeNotAcceptable Exception, etc.

@RequestMapping(value="/testDefaultHandlerExceptionResolver",method=RequestMethod.POST)
   public StringtestDefaultHandlerExceptionResolver(){
      System.out.println("testDefaultHandlerExceptionResolver...");
      return "success";
   }

5. SimpleMappingExceptionResolver

If you want to handle all exceptions uniformly, you can use

SimpleMapping Exception Resolver, which maps exception class names to view names, uses the corresponding view to report exceptions when an exception occurs

  

 <!-- Configuration and use SimpleMappingExceptionResolver To map exceptions -->
   <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
      <property name="exceptionAttribute" value="ex"></property>
      <property name="exceptionMappings">
         <props>
            <prop key="java.lang.ArrayIndexOutOfBoundsException">error</prop>
         </props>
      </property>
   </bean> 

@RequestMapping("/testSimpleMappingExceptionResolver")
   public StringtestSimpleMappingExceptionResolver(@RequestParam("i")inti){
      String[] vals = newString[10];
      System.out.println(vals[i]);
      return "success";
   }

<h4>error page</h4>
  
   ${requestScope.ex }


 

 

Source code file: http://download.csdn.net/detail/qq_26553781/9757893

Posted by Katanius on Mon, 01 Apr 2019 10:15:28 -0700