SPRINGMV Interceptors & Exception handling

Source: Internet
Author: User
Tags stub

Interceptor Interceptor Concept

The main function of the interceptor is to intercept the user's request and execute it before the matching target method. In general, used as authorization to determine whether the user login, there is no login in the mall does not allow the purchase can also be used to verify the interceptor.

We can customize interceptors to implement specific functions, and custom interceptors must implement the Handlerinterceptor interface .
and implement the following methods:
prehandle (): This method is called before the business processor processes the request, in which the user requests the request to be processed. It is important to note that the return value of this method returns true if we call other interceptors after the interceptor has intercepted the request, or if the business processor is going to process it, or false if we no longer need to invoke other components to process the request.
posthandle ():* when the business processor finishes executing the target method, but is called before the Dispatcherservlet returns a response to the client, the request is processed in the method.
aftercompletion (): This method is called after the Dispatcherservlet has completely processed the request, and some cleanup of resources can be done in the method.

Configuring the Custom Interceptor

Two Step walk:
First step: Writing a custom Interceptor
Step Two: Register a custom Interceptor

        <!--Configure a custom Interceptor implementation Handlerinterceptor-->public class Firstintercept implements handlerinterceptor{/* This method precedes the target method     Previous Intercept Call * If the method returns True, the subsequent interceptor and target method will continue to be invoked * If the method returns false, the execution of the subsequent interceptor and the target method will be terminated. * prehandle--"target Method-" posthandle--"aftercompletion * * Rights LOG Transaction */public boolean prehandle (httpservletreq Uest request, HttpServletResponse response, Object handler) throws Exception {System.out.println ("first        Intercept Prehandle ");        return false;    return true; */* Before rendering the view after invoking the target method * You can make changes to the properties or views in the request domain * * * * public void Posthandle (HttpServletRequest request, HTTPSERVLETR Esponse response, Object handler, Modelandview Modelandview) throws Exception {//TODO auto-generated m    Ethod stub System.out.println ("Firstintercept posthandle"); }/* After rendering the view * FREE resources * */public void aftercompletion (HttpServletRequest request, HttpS Ervletresponse response, Object handler, EXception ex) throws Exception {//TODO auto-generated Method Stub System.out.println ("Firstinter    Cept aftercompletion "); }   }<!--registering custom interceptors--<Mvc:interceptors><Beanclass="Com.wf.springmvc.crud.intercept.FirstIntercept" ></Bean><Beanclass="Com.wf.springmvc.crud.intercept.SecondIntercept" ></Bean></Mvc:interceptors><!--Configuring a custom Interceptor method two--<mvc:interceptors> <!-- The Configuration Interceptor (not) Action path is requestmapping path--<mvc:interceptor> Span class= "hljs-comment" ><!--<mvc:exclude-mapping path= "/list"/>--<mvc:mapping path= "/list"/> <bean class= "Com.wf.springmvc.crud.intercept.SecondIntercept" ></bean > </mvc:interceptor> </MVC:INTERCEPTORS>           
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

Note:
When configuring an interceptor, we can use the "Mvc:interceptor" sub-node to make a specified interceptor function on those requests, such as the above configuration custom Interceptor method Two, in fact, this can greatly optimize our performance, because then, We can specify interception on certain target methods that require interceptors, and no interception for target methods that do not require interception.

Interceptor Execution Order

for a single interceptor, the Order of interception is performed in the following order, but it is important to note that the return value of Prehandle at this time is true, and if the return value is false, the render view is rendered directly after the target method of Handleradapter is executed. And no other processing is done.
Firstintercept prehandle--"Handleradapter target Method-" Firstintercept posthandle--"dispatcherservlet rendering View-" Firstintercept's Aftercompletion

For multiple interceptors, the order of execution is as layered as the onion peel. are executed according to the order in which the custom interceptors are registered. Note that the stop in is a direct stop and the target method is not executed.

Exception handling

Springmvc the exception that is handled by the Handlerexceptionresolver interface handler, including handler mappings, data binding, and exceptions that occur when the target method executes.

There are several implementation classes for the Handlerexceptionresolver interface, but we commonly use four:

When we configure "Mvc:annotation-driven", Dispatcherservlet will assemble the following three default exception implementation classes, add breakpoints, see "Dispatcherservlet" in the This variable " Handlerexceptionresolver "

Exceptionhandlerexceptionresolver

1. Exceptionhandlerexceptionresolver mainly deals with the method defined by @exceptionhandler annotations in handler.
2, for @exceptionhandler annotation method, if it occurs nullpointexception, but in our declaration exception has runtimeexception and exception, then this time will be based on the most recent inheritance of the exception, Find the one with the deepest depth of succession (nearest principle).
3,exceptionhandlermethodresolver internal if cannot find @exceptionhandler annotation, will find @controlleradvice in the @exceptionhandler annotation method.

In general, in our operation in the event of an exception, will be directly on the page error display, if we take advantage of our exception handling, we can avoid this.

<!--前台链接 --><a href="TestExceptionHandlerExceptionResolver?i=2">Test ExceptionHandlerExceptionResolver </a> <br><!-- 后台处理--> @RequestMapping("TestExceptionHandlerExceptionResolver") public String TestExceptionHandlerExceptionResolver(@RequestParam("i") int i){ System.out.println("result : "+10/i); return "success"; }
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

When we run the above code, if we do not do exception handling, the jump page is as follows : (we can pass the parameter set to 0, so that it is forced to error)

But if we add an exception-handling method under this method, that is, the method that is modified by the @exceptionhandler annotation. The following results are run:
The added code:

    @ExceptionHandler (value={arithmeticexception.Class,ioexception.Class})Public Modelandview Testexceptionhandlerexceptionresolver (Exception ex) {System.out.println ( "----Abnormal:" +ex); Modelandview model = new Modelandview ( "error"); Model.addobject ( "exception", ex); return model;}  @ExceptionHandler ({classnotfoundexception. Class,classcastexception. class}) public modelandview TestExceptionHandlerExceptionResolver02 (Exception ex) {System.out.println ( "----Abnormal:" +ex); Modelandview model = new Modelandview ( "error"); Model.addobject ( "exception", ex); return model;}            
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

Attention:
1, the above we define the method of two @exceptionhandler modification, but it is important to note that two methods of the exception type can not be the same, the purpose is to test, when we throw the exception is not in this predefined exception, will be the nearest choice to deal with.

2.@ExceptionHandler Annotations can specify exceptions and can be used for multiple

3,@ExceptionHandler modification method, can not use map as a data store to interact with the foreground, if you want to pass the wrong Metro to the foreground, we need to use Modelandview as the view return value in the model for the interaction and display of the exception

4,@ExceptionHandler method has the exception of the priority, is generally matched with a higher degree of similarity

5, If an exception occurs in this class can not find @exceptionhandler decorated methods for exception handling, it will go into the class with @controlleradvice adornment to find @exceptionhandler decorated method to match

6. Note that @exceptionhandler can match multiple exceptions, but the same exception cannot be handled in different ways, because you will not know which method to use for processing and return 500 exceptions

Run as follows:

Or we can write a separate class to store exception handling, as follows:

@ControllerAdvicepublic class HandlerExceptionController {    @ExceptionHandler({ArithmeticException.class,IOException.class})    public ModelAndView TestExceptionHandlerExceptionResolver(Exception ex){        System.out.println("03----ControllerAdvice出异常了:"+ex); ModelAndView model = new ModelAndView("error"); model.addObject("exception", ex); return model; }}
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

Note Use class annotations @controlleradvice and exception annotations @exceptionhandler.
In this case, when an exception occurs, the exception is not found in this class @exceptionhandler-modified method for exception handling, it will go into the @controlleradvice decorated class to find @exceptionhandler decorated method to match.

Responsestatusexceptionresolver

Responsestatusexceptionresolver is generally used to develop specific response status and error message information displayed above . In general, we can throw our own defined exception classes when we are dealing with exceptions thrown out.
The above exception is thrown in the processor method, and if "Exceptionhandlerexceptionresolver" does not parse our exception class, this is because the custom exception that is triggered has a "@ResponseStatus annotation", so will be parsed by Responsestatusexceptionresolver. Finally responds to the "@ResponseStatus annotation" property value to the client.

<!--front link--><a href="testresponsestatusexceptionresolver?i=10" >test responsestatusexceptionresolver </a> <br><!-- Background Processing--Test Responsestatusexceptionresolver Note The custom exception class Namenotinpasswordexception @RequestMapping ("Testresponsestatusexceptionresolver")Public String Testresponsestatusexceptionresolver (@RequestParam ("I")int i) {if (i==13) {ThrowNew Namenotinpasswordexception ();Changing the browser parameter i is 13throw new runtimeerrorexception (null); } System.out.println (return  "success";} <!--custom Exception class-- //reason specify display information value HTTP status Code screen This annotation contrast to the external browser to display //do not mark on the method @responsestatus (Value=httpstatus.forbidden,reason=public class namenotinpasswordexception extends runtimeexception {private static Span class= "Hljs-keyword" >final long serialversionuid = 1L;}   
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27

Note:Responsestatusexceptionresolver only handles exceptions with @responsestatus annotations and maps them to status codes.
For the first time we throw runtimeerrorexception, because there is no annotation @responsestatus, so the return is 500
The second time we modify our thrown exception to a custom exception, and we use annotations @responsestatus, we return our specific status code and information.

Defaulthandlerexceptionresolver

Defaulthandlerexceptionresolver This primarily deals with some of the spring-specific exceptions and translates them into status codes. we can see it in the source code.

Test the above httprequestmethodnotsupportedexception. He meant not to support the way we submitted the method.
Our hyperlinks are get methods, and when we do it in the background, we specify the method to process the post request, so we'll give it to our defaulthandlerexceptionresolver for processing.

<!-- 前台链接  get 方式 --><a href="TestHttpRequestMethodNotSupportedException">Test HttpRequestMethodNotSupportedException </a> <br><!--后台处理 post方式 --> @RequestMapping(value="/TestHttpRequestMethodNotSupportedException",method=RequestMethod.POST) public String TestHttpRequestMethodNotSupportedException(){ System.out.println("TestHttpRequestMethodNotSupportedException..."); return "success"; } 
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

Note: Obviously, from here we can see that the previous error page has been processed by the framework.

Simplemappingexceptionresolver

This exception handling, is mainly to resolve when we specify the exception situation, jump to the page we specify. This exception is registered in the Springmvc.xml file.

<!--front desk links-<Ahref="Testsimplemappingexceptionresolver?i=10" >test simplemappingexceptionresolver</A><Br><!--background-@RequestMapping ("/testsimplemappingexceptionresolver") public String Testsimplemappingexceptionresolver (@RequestParam ("i") Integer i) {int [] Vals = new INT[20]; System.out.println (Vals[i]); Pass parameter 21 to make it happen java.lang.ArrayIndexOutOfBoundsException return "success"; }<!--file Configuration--<!--configuration exception Simplemappingexceptionresolver in this page, the exception information is stored in the exception attribute in the Requestscope domain, and we can get it directly from the page Or we can configure this Exceptionattribute property to specify a specific attribute in the Requestscope domain--<Beanclass="Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" ><PropertyName="Exceptionmappings" ><!--name fixed--<Props><Propkey="Java.lang.ArrayIndexOutOfBoundsException" >error</Prop><!--Configure the specified exception to the specified location-</Props></Property><property name= " Exceptionattribute "value=" ex "> </property> <!--Configure a specific domain on the page should be ${ex}--> </bean><!--error page--><body>error page <br > Default storage domain: ${exception} <br>haha  <br> configuration Modify Storage domain: ${ex}<br>< Span class= "Hljs-tag" ></BODY>        
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

Note: Configuring the specified exception to the specified location is still configured by our view parser, so write the error page at the specified location.

SPRINGMV Interceptors & Exception handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.