Detailed description and sample code of interceptor in SpringMVC, springmvc example

Source: Internet
Author: User

Detailed description and sample code of interceptor in SpringMVC, springmvc example

This article focuses on SpringMVC interceptor introduction, instance code, configuration, and other content, as follows.

Springmvc's processor interceptor is similar to the Filter in Servlet development and is used for preprocessing and post-processing of the processor. This article mainly summarizes how the interceptor is defined in springmvc, and how to test the execution and usage of the interceptor.

1. springmvc interceptor definition and configuration 1.1 springmvc interceptor Definition

In springmvc, define the Interceptor to implement the HandlerInterceptor interface and implement the three methods provided in this interface, as shown below:

// Test interceptor 1 public class HandlerInterceptor1 implements HandlerInterceptor {@ Override public Boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System. out. println ("HandlerInterceptor1 .... preHandle "); // false indicates interception, not to be executed; true indicates return true;} @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System. out. println ("HandlerInterceptor1 .... postHandle ") ;}@ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System. out. println ("HandlerInterceptor1 .... afterCompletion ");}}

For these three methods, I will perform a simple analysis:

  1. PreHandle method: run the preHandle method before entering the Handler method. It can be used for identity authentication and identity authorization. For example, if the authentication fails, it indicates that the user has not logged on. You need to use this method to intercept the request and stop executing (return false); otherwise, return true ).
  2. PostHandle method: after entering the Handler method, it is executed before ModelAndView is returned. You can see that this method has a modelAndView parameter. Application Scenario: Starting from modelAndView: Transfers common model data (such as menu navigation) to the view here, or you can specify a view here.
  3. AfterCompletion Method: After Handler is executed, it is executed. Application scenarios: Unified Exception Handling and log processing.
1.2 springmvc interceptor Configuration

In springmvc, the interceptor is configured for the specific HandlerMapping. That is to say, if an interception is configured in a HandlerMapping, the handler that has successfully mapped the HandlerMapping will eventually use the interceptor. For example, if the er we configured in the configuration file is org. springframework. web. servlet. handler. BeanNameUrlHandlerMapping, We can configure the interceptor as follows:

<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">  <property name="interceptors">    <list>      <ref bean="handlerInterceptor1"/>      <ref bean="handlerInterceptor2"/>    </list>  </property></bean><bean id="handlerInterceptor1" class="ssm.intercapter.HandlerInterceptor1"/><bean id="handlerInterceptor2" class="ssm.intercapter.HandlerInterceptor2"/>

In springmvc, how do I configure a global interceptor? As mentioned above, the interceptor in springmvc is for a specific er. To solve this problem, the springmvc framework injects a globally configured interceptor into each HandlerMapping, in this way, you can become a global interceptor. The configuration is as follows:

<! -- Configure interceptor --> <mvc: interceptors> <! -- Execute multiple interceptors in sequence --> <mvc: interceptor> <mvc: mapping path = "/**"/> <! -- Blocks all URLs, including sub-url paths --> <bean class = "ssm. interceptor. handlerInterceptor1 "/> </mvc: interceptor> <mvc: mapping path ="/** "/> <bean class =" ssm. interceptor. handlerInterceptor2 "/> </mvc: interceptor> <mvc: mapping path ="/** "/> <bean class =" ssm. interceptor. handlerInterceptor3 "/> </mvc: interceptor> </mvc: interceptors>

This configuration is generally used. <mvc: mapping> specifies the url to be blocked.

2. Test the springmvc interceptor.

Write two interceptors, HandlerInterceptor2 and HandlerInterceptor3, following the preceding steps. Then let's test the execution of the three interceptors and make a summary.

2.1 All three interceptors are allowed

In other words, we will change the return values of the three interceptor's preHandle method to true to test the sequence of the interceptor's execution. The test results are as follows:

HandlerInterceptor1 .... PreHandle
HandlerInterceptor2 .... PreHandle
HandlerInterceptor3 .... PreHandle

HandlerInterceptor3 .... PostHandle
HandlerInterceptor2 .... PostHandle
HandlerInterceptor1 .... PostHandle

HandlerInterceptor3 .... AfterCompletion
HandlerInterceptor2 .... AfterCompletion
HandlerInterceptor1 .... AfterCompletion

Make a summary based on the printed results: When all interceptors are released, the preHandle method is executed in the configuration order, and the other two methods are executed in reverse order according to the configuration order.

2.2 One interceptor is not allowed

Change the returned value in the preHandle method of the third Interceptor to false, and the first two are still true to test the execution sequence of the Interceptor. The test result is as follows:

HandlerInterceptor1 .... PreHandle
HandlerInterceptor2 .... PreHandle
HandlerInterceptor3 .... PreHandle

HandlerInterceptor2 .... AfterCompletion
HandlerInterceptor1 .... AfterCompletion

Make a summary based on the printed results:
1. Because interceptor 1 and 2 are allowed, the preHandle of interceptor 3 can be executed. That is to say, the previous interceptor is allowed, and the subsequent interceptor can execute preHandle.
2. interceptor 3 is not allowed, so the other two methods are not executed. That is, if an interceptor is not allowed, the other two methods will not be executed.
3. As long as one interceptor is not allowed, all the postHandle methods of the interceptor will not be executed, but as long as the preHandle is executed and the method is released, the afterCompletion method will be executed.

2.3 none of the three interceptors are allowed

In this case, you can refer to the above situation. It is a special case. Let's take a look at the running results:

HandlerInterceptor1 .... PreHandle

Obviously, only the preHandle method of the first interceptor is executed. Because neither of them is allowed, no postHandle method or afterCompletion method is executed.

3. Use of interceptor

In the second case, for example, to write a unified Exception Handling logic, you must place the interceptor in the first position of the interceptor chain, and make sure it is allowed, because it is only allowed, afterCompletion will be executed, and if the first one is placed in the interceptor chain, the afterCompletion method will be last executed to execute the unified Exception Handling logic in it.
For example, log on to the authentication interceptor and place it at the first position in the interceptor Link (if there is a unified Exception Handling, it should be placed behind the unified Exception Handling ). The permission verification interceptor is placed after logging on to the authentication Interceptor (because the permission is verified only after the login is passed ).
Here we will write an interceptor for login verification to illustrate how to use the springmvc interceptor.

3.1 requirements

First, let's take a look at the requirement: What should we intercept and what should we do. The idea is as follows:

1. User request url
2. the interceptor performs interception verification.
If the requested url is a public address (a url that can be accessed without logon), allow access.
If the user session does not exist, the logon page is displayed.
If a user session exists, the user is allowed to continue the operation.

3.2 Controller Method For Login
// Login @ RequestMapping ("/login") public String login (HttpServletRequest request, String username, String password) throws Exception {// What is going to match the database //.... // assume that HttpSession session = request is successfully logged in. getSession (); session. setAttribute ("username", username); return "redirect: queryItems. action ";} // exit @ RequestMapping ("/logout ") public String logout (HttpServletRequest request) throws Exception {HttpSession session = request. getSession (); session. invalidate (); return "redirect: queryItems. action ";}
3.3 implement login verification interceptor
// Test interceptor 1 public class LoginInterceptor implements HandlerInterceptor {// run before entering the Handler method // It can be used for identity authentication and identity authorization. If the authentication fails, it indicates that the user has not logged on. You need to use this method to intercept the requests. Otherwise, access @ Override public Boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// obtain the urlString url of the request = request. getRequestURI (); // determine whether the url is a public address (the public address is configured in the configuration file in actual use) // assume whether the public address is a submitted url if (url. indexOf ("login. action ")> 0) {// return true if submitted for login;} // judge sessionHttpSession session = request. getSession (); // retrieves user identity information from the session Str Ing username = (String) session. getAttribute ("username"); if (username! = Null) {return true;} // indicates that the user identity needs to be verified. The request is redirected to the login page. getRequestDispatcher ("/WEB-INF/jsp/login. jsp "). forward (request, response); return false;} // saves space. If you omit the other two methods, you do not need to process them}

Then configure the Interceptor:

<! -- Configure interceptor --> <mvc: interceptors> <! -- Execute multiple interceptors in sequence --> <mvc: interceptor> <mvc: mapping path = "/**"/> <! -- Intercept all URLs, including sub-url paths --> <bean class = "ssm. interceptor. LoginInterceptor"/> </mvc: interceptor> <! -- Other interceptors --> </mvc: interceptors>

In this way, when we request a url at will, it will be captured by the interceptor we just defined, and then we will determine whether the session contains user information, if not, we will jump to the login page to log on:

<Form action = "$ {pageContext. request. contextPath}/login. action "method =" post "> User name: <input type =" text "name =" username "/> <br> password: <input type = "password" name = "password"/> <br> <input type = "submit" name = "submit"/> </form>

This section describes how to use the interceptor.

Summary

The above is all the content about the interceptor in SpringMVC and the sample code. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.