Springmvc Study Notes (20)-interceptor

Source: Internet
Author: User

Springmvc Study Notes (20)-interceptor
Springmvc Study Notes (20)-interceptor

This article mainly introduces the interceptor in springmvc, including the definition and configuration of the interceptor, then demonstrates a test example of chained interception, and finally demonstrates the application of the interceptor through a logon authentication example.

Interception Definition

Define interceptor and implementHandlerInterceptorInterface. The interface provides three methods.

Public class HandlerInterceptor1 implements HandlerInterceptor {// run before entering the Handler method // used for identity authentication, identity authorization // For example, identity authentication. If the authentication succeeds, it indicates that the current user has not logged in, this method is required to intercept public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// return false indicates intercept, if you do not run the "// return true" command, return false is allowed.} // after entering the Handler method, run the command before returning modelAndView. // The Application Scenario starts with modelAndView: upload public model data (such as menu navigation) to the view here. You can also specify public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) here) throws Exception {} // execute Handler to execute this method // Application Scenario: Unified Exception Handling and unified log processing public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}

You can see the order and function of each interface from the names and parameters:

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
The minimum number of parameters is required. Only three parameters are used for identity authentication and identity authorization before entering the Handler method. For example, if the identity authentication is successful, it indicates that the current user has not logged on. You need to use this method to intercept the request and do not perform the next step. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
After a modelAndView parameter is added to the Handler method, run the Application Scenario before returning modelAndView. Start from modelAndView: Upload the common model data (such as menu navigation) to the view, you can also specify a view here. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
An Exception type parameter is added and Handler is executed to complete this method. application scenarios: Unified Exception Handling and unified log processing interceptor configuration for HandlerMapping

Springmvc interceptor sets HandlerMapping interception. If HandlerMapping is configured in a HandlerMapping, handler that has been successfully mapped by the HandlerMapping will eventually use this interceptor.

<code class="language-xml hljs "><bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">    <property name="interceptors">        <list>            <ref bean="handlerInterceptor1">            <ref bean="handlerInterceptor2">        </ref></ref></list>    </property></bean>    <bean id="handlerInterceptor1" class="springmvc.intercapter.HandlerInterceptor1">    <bean id="handlerInterceptor2" class="springmvc.intercapter.HandlerInterceptor2"></bean></bean></code>

It is generally not recommended.

Similar to global interceptor

Springmvc is configured with a global Interceptor. The springmvc framework injects a globally configured interceptor into each HandlerMapping.

 
  
      
       
           
            
            
         
    
       
           
            
         
    
   
  
Interception Test

Test the execution time of each method of multiple interceptors

Access/items/queryItems.action

1. Both interceptors are allowed
DEBUG [http-apr-8080-exec-1] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]DEBUG [http-apr-8080-exec-1] - Looking up handler method for path /items/queryItems.actionDEBUG [http-apr-8080-exec-1] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]DEBUG [http-apr-8080-exec-1] - Returning cached instance of singleton bean 'itemsController'DEBUG [http-apr-8080-exec-1] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1HandlerInterceptor1...preHandleHandlerInterceptor2...preHandleDEBUG [http-apr-8080-exec-1] - Fetching JDBC Connection from DataSourceDEBUG [http-apr-8080-exec-1] - Registering transaction synchronization for JDBC ConnectionDEBUG [http-apr-8080-exec-1] - Returning JDBC Connection to DataSourceHandlerInterceptor2...postHandleHandlerInterceptor1...postHandleDEBUG [http-apr-8080-exec-1] - Rendering view [org.springframework.web.servlet.view.JstlView: name 'items/itemsList'; URL [/WEB-INF/jsp/items/itemsList.jsp]] in DispatcherServlet with name 'springmvc'DEBUG [http-apr-8080-exec-1] - Added model object 'itemtypes' of type [java.util.HashMap] to request in view with name 'items/itemsList'DEBUG [http-apr-8080-exec-1] - Added model object 'itemsQueryVo' of type [com.iot.learnssm.firstssm.po.ItemsQueryVo] to request in view with name 'items/itemsList'DEBUG [http-apr-8080-exec-1] - Added model object 'org.springframework.validation.BindingResult.itemsQueryVo' of type [org.springframework.validation.BeanPropertyBindingResult] to request in view with name 'items/itemsList'DEBUG [http-apr-8080-exec-1] - Added model object 'itemsList' of type [java.util.ArrayList] to request in view with name 'items/itemsList'DEBUG [http-apr-8080-exec-1] - Forwarding to resource [/WEB-INF/jsp/items/itemsList.jsp] in InternalResourceView 'items/itemsList'HandlerInterceptor2...afterCompletionHandlerInterceptor1...afterCompletionDEBUG [http-apr-8080-exec-1] - Successfully completed request

Conclusion: The preHandle method is executed in order, And the postHandle and afterCompletion are executed in reverse order according to the interceptor configuration.

2. interceptor 1 is allowed, and interceptor 2 is not allowed

DEBUG [http-apr-8080-exec-8] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]DEBUG [http-apr-8080-exec-8] - Looking up handler method for path /items/queryItems.actionDEBUG [http-apr-8080-exec-8] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]DEBUG [http-apr-8080-exec-8] - Returning cached instance of singleton bean 'itemsController'DEBUG [http-apr-8080-exec-8] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1HandlerInterceptor1...preHandleHandlerInterceptor2...preHandleHandlerInterceptor1...afterCompletionDEBUG [http-apr-8080-exec-8] - Successfully completed request

Summary:

Interceptor 1 is allowed, and interceptor 2 preHandle is executed. Interceptor 2 preHandle is not allowed. interceptor 2 postHandle and afterCompletion are not executed. PostHandle is not executed as long as an interceptor is not allowed.

3. Both interceptors are not allowed

DEBUG [http-apr-8080-exec-9] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]DEBUG [http-apr-8080-exec-9] - Looking up handler method for path /items/queryItems.actionDEBUG [http-apr-8080-exec-9] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]DEBUG [http-apr-8080-exec-9] - Returning cached instance of singleton bean 'itemsController'DEBUG [http-apr-8080-exec-9] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1HandlerInterceptor1...preHandleDEBUG [http-apr-8080-exec-9] - Successfully completed request

Summary:

Interceptor 1 preHandle is not allowed, and postHandle and afterCompletion are not executed. Interceptor 1 preHandle is not allowed, and interceptor 2 is not executed.

4. interceptor 1 does not allow, and interceptor 2 does.

DEBUG [http-apr-8080-exec-8] - DispatcherServlet with name 'springmvc' processing GET request for [/ssm1/items/queryItems.action]DEBUG [http-apr-8080-exec-8] - Looking up handler method for path /items/queryItems.actionDEBUG [http-apr-8080-exec-8] - Returning handler method [public org.springframework.web.servlet.ModelAndView com.iot.learnssm.firstssm.controller.ItemsController.queryItems(javax.servlet.http.HttpServletRequest,com.iot.learnssm.firstssm.po.ItemsQueryVo) throws java.lang.Exception]DEBUG [http-apr-8080-exec-8] - Returning cached instance of singleton bean 'itemsController'DEBUG [http-apr-8080-exec-8] - Last-Modified value for [/ssm1/items/queryItems.action] is: -1HandlerInterceptor1...preHandleDEBUG [http-apr-8080-exec-8] - Successfully completed request

The results are the same as those of the two interceptors. Because interceptor 1 is executed first, it is not allowed.

Summary

Based on the test results, the interceptor is applied.

For example, to unify the log processing interceptor, you must allow the interceptor preHandle and place it in the first position in the interceptor link.

For example, log on to the authentication interceptor and place it in the first position in the interceptor link. The permission verification interceptor is placed after the authenticate interceptor. (The permission is verified only after logon is passed. Of course, the logon authentication interceptor must be placed behind the unified log processing interceptor)

Interceptor application (login authentication) requirements 1. User request url 2. interceptor interception Verification
If the requested url is a public address (a url that can be accessed without logon), allow the user to go To the logon page if the user session does not exist. If the user session exists, continue the operation. Login controller Method
@ Controllerpublic class LoginController {// login @ RequestMapping ("/login") public String login (HttpSession session, String username, String password) throws Exception {// call the service for user authentication //... // Save the user identity information in the session. setAttribute ("username", username); // redirect to the product list page return "redirect:/items/queryItems. action ";} // exit @ RequestMapping ("/logout ") public String logout (HttpSession session) throws Exception {// clear session. invalidate (); // redirect to the product list page return "redirect:/items/queryItems. action ";}}
Code implementation for login authentication Interception
/*** Created by brian on 2016/3/8. * log on to the authentication interceptor */public class LoginInterceptor implements HandlerInterceptor {// run before entering the Handler method // used for identity authentication, identity authorization // For example, identity authentication, if the authentication succeeds, it indicates that the current user has not logged on. You need to use this method to stop executing public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// obtain the request url String url = request. getRequestURI (); // determine whether the url is a public address (the public address configuration file is used in actual use) // The public address here is the location submitted by login Address if (url. indexOf ("login. action ")> = 0) {// return true if submitted for login;} // judge session HttpSession session = request. getSession (); // retrieves the user identity information from the session String username = (String) session. getAttribute ("username"); if (username! = Null) {// identity exists, allow return true;} // execute this command to indicate that the user identity needs to be authenticated and redirect to the request on the login page. getRequestDispatcher ("/WEB-INF/jsp/login. jsp "). forward (request, response); // return false indicates interception. If you do not execute // return true, it indicates that return false is allowed;} // after entering the Handler method, run the following command before returning to modelAndView: Upload the common model data (such as menu navigation) to the view, you can also specify the public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System. out. println ("LoginInterceptor... postHandle ");} // execute Handler to execute this method // Application Scenario: Unified Exception Handling, unified log processing public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, exception ex) throws Exception {System. out. println ("LoginInterceptor... afterCompletion ");}}
Interceptor Configuration

  
      
       
       
           
            
         
    
   ... Omitted
  

 

Related Article

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.