SPRINGMVC's Interceptor Interceptor's login blocker

Source: Internet
Author: User
Tags prepare

SPRINGMVC interceptors are the primary function of intercepting requests from users to the background, which can be restricted to authorization and user login before entering the background.

1. Define interceptors; There are two main types of interceptors in SPRINGMVC: the first is to implement the Handleinterceptor interface, rewrite the method, and the second is to implement the Webrequestinterceptor interface, the same way of rewriting the method, Implement your own custom logic processing. 1. Implement Handleinterceptor interface; Three methods are defined in the interface: Prehandle (requsest,response.handle); Posthandle (Request,response,handle, Modleandview); aftercompletion (REQUEST,RESPONSE,HANDLE,EX); Let's talk about the function and function space of each method. 1.preHandle (Requsest,response.handle) : This method is called before the request is processed, that is, the method called before the request is passed from the foreground to the controller, the return value is Boolean, and if True is returned, the following two methods are resumed, and if False is returned, the request ends , my interceptor gets the session data from the request, verifies that the user is logged in, if flag is true, returns False;2.posthandle (Request,response,handle, Modleandview): Explained by the Prehandle method we know that this method, including the Aftercompletion method that is to be mentioned later, can only be called if the return value of the Prehandle method of the current owning interceptor is true. The Posthandle method, as the name implies, is executed after the current request is processed, that is, after the controller method call, but it is called before the view returns to render Dispatcherservlet. So we can manipulate the Modelandview object after controller processing in this method. The Posthandle method is called in the opposite direction to Prehandle, which means that the Posthandle method of the declared interceptor is executed later, which is somewhat different from the Struts2 execution in interceptor. Struts2 inside the Interceptor execution process is also chained, but in Struts2 need to manually invoke the Actioninvocation invoke method to trigger the next interceptor or action call, Then the contents of each interceptor before the Invoke method call are executed in the order of Declaration, and the content after the Invoke method is reversed. 3.aftercompletion (Request,response,handle,ex): This method is also required when the return value of the Prehandle method of the current corresponding interceptor is true to execute. As the name implies, the method executes after the entire request is finished, that is, after Dispatcherservlet renders the corresponding view. The main function of this method is to perform resource cleanup work.
Code description?
import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.springframework.web.servlet.handlerinterceptor;import Org.springframework.web.servlet.modelandview;public Class Springmvcinterceptor implements Handlerinterceptor {/** * Prehandle method is used for processor interception, as the name implies, the method will be called before the controller processing, The Interceptor interceptor in SPRINGMVC is chained, can exist simultaneously * multiple interceptor, then SPRINGMVC will execute one after the other according to the order of the Declaration, And all Prehandle methods in the interceptor are called before the Controller method call. This interceptor chain structure of the SPRINGMVC can also be interrupted, which means that the return value of Prehandle is false, and the entire request ends when the return value of Prehandle is false. */@Overridepublic Boolean prehandle (httpservletrequest request,httpservletresponse response, Object handler) throws Exception {
<span Style= "White-space:pre" ></span>httpsession session = Request.getsession (); Enumeration<string> e = Session.getattributenames (); hashmap< String, string> map = new hashmap<string, string> (), while (E.hasmoreelements ()) {Map.put ( E.nextelement (), "");} if (Map.containskey ("IsLogin")) {if (Session.getattribute ("IsLogin"). Equals (True)) {System.err.println ("in session Username is: "+session.getattribute (" username "); return true;} Else{system.err.println ("IsLogin is false! Response.senderror (501, "You're not logged in yet!") "); return false;}} Else{system.err.println ("There is not exist IsLogin flag!"); Response.senderror (502, "Here's a bit of a problem, please visit the login page! "); return false;} 
}/** * This method will only be executed if the current interceptor Prehandle method returns a value of true. Posthandle is used for processor interception, its execution time is after the processor to process the *, that is, after the controller's method call execution, but it will be executed before the rendering of the view Dispatcherservlet, That means you can do the Modelandview in this method. The chain structure of this method is the opposite of the normal access direction, that is, the first declaration of the Interceptor Interceptor the method will be called later, which is a bit like the execution process of the interceptor inside the STRUTS2, * Just Struts2 inside the Intercept method to manually invoke the Actioninvocation invoke method, the Invoke method called Actioninvocation in Struts2 is called the next interceptor * Either the action is called and the content to be called before Interceptor is written before invoking invoke, and the content to be called after Interceptor is written after the Invoke method is called. */@Overridepublic void Posthandle (httpservletrequest request,httpservletresponse response, Object handler, Modelandview Modelandview) throws Exception {}/** * This method is also required for the Interceptor method that currently corresponds to the return value of Prehandle to True when it is executed. This method will render the view execution after the entire request is completed, that is, the main function of this method is to clean up the resources, Dispatcherservlet Of course this method can only be executed if the return value of the current interceptor Prehandle method is true. */@Overridepublic void aftercompletion (httpservletrequest request,httpservletresponse response, Object handler, Exception ex) throws Exception {//TODO auto-generated method stub}}
2. Implement Webrequestinterceptor Interface: (This method I do not use, the first code, convenient later learning) Webrequestinterceptor also defined three methods, we also through the three methods to achieve interception. These three methods all pass the same parameter WebRequest, so what is this WebRequest? This WebRequest is an interface defined by spring, and its method definitions are basically the same as HttpServletRequest, in Webrequestinterceptor WebRequest All actions are synchronized to httpservletrequest and then passed in the current request.     (1) prehandle (WebRequest request) method. The method will be called before the request is processed, meaning it will be called before the Controller method call. This method is different from the Prehandle in Handlerinterceptor, the main difference is that the return value of the method is void, that is, there is no return value, so we generally use it to prepare resources, for example, we are using hibernate You can prepare a Hibernate session object in this method, and then use WebRequest's setattribute (name, value, scope) to place it in the WebRequest attribute. Here's the third parameter to the SetAttribute method, scope, which is an integer type. In WebRequest's parent interface Requestattributes, it defines three constants:   scope_request: Its value is 0, which means it can only be accessed in REQUEST.    scope_session: Its value is 1, if the environment allows it to represent a partial isolated session, otherwise it represents a normal session, and can be accessed within the session range.    scope_global_session: Its value is 2, if the environment allows, it represents a global shared session, otherwise it represents the normal session, and within the scope of the session can be accessed.     (2) posthandle (WebRequest requEST, Modelmap model) method. This method will be called after the request is processed, that is, after the controller method call, but will be called before the view returns are rendered, so you can change the presentation of the data by changing the data model Modelmap in this method. The method has two parameters, the WebRequest object is used to pass the entire request data, such as the data prepared in Prehandle can be passed through WebRequest and access; Modelmap is the model object returned by the controller after processing, We can change the returned model by changing its properties.     (3) aftercompletion (WebRequest request, Exception Ex) method. The method is executed after the entire request process is completed, that is, after the view is returned and rendered. Therefore, the method can be used to release the resources of the operation. The WebRequest parameter can then pass the resources we have prepared in Prehandle to be released here. The Exception parameter represents the currently requested exception object, which is null if the exception thrown in the controller has already been handled by spring's exception handler.
Import Org.springframework.ui.modelmap;import Org.springframework.web.context.request.webrequest;import Org.springframework.web.context.request.webrequestinterceptor;public class Allinterceptor Implements Webrequestinterceptor {/** * is executed before request processing, which is primarily used to prepare resource data, which can then be placed in WebRequest as a request attribute */@Overridepublic void Prehandle ( WebRequest request) throws Exception {//TODO auto-generated method StubSystem.out.println ("Allinterceptor .... Request.setattribute ("Request", "request", webrequest.scope_request);//................. This is placed within the request range, so you can only get the Request.setattribute ("session", "Session", "Webrequest.scope_session") in the request in the current requests;// This is placed in the session scope, if the environment allows it can only be accessed in a local isolated session, or in a normal current session can access Request.setattribute ("Globalsession", "Globalsession" , webrequest.scope_global_session);//If the environment allows it, it can be accessed in a globally shared session, otherwise it is accessed in a normal current session}/** * This method will be executed before the controller is executed and returned to the view. Modelmap represents the model object returned after the controller processing is requested, so you can modify the properties of the Modelmap in the * method to achieve the effect of changing the returned model. */@Overridepublic void Posthandle (WebRequest request, ModElmap map) throws Exception {//TODO auto-generated method Stubfor (String key:map.keySet ()) System.out.println (key + "---- ---------------------");; Map.put ("Name3", "Value3"); Map.put ("Name1", "name1");} /** * This method will be called after the entire request is completed, that is, after the view is rendered, primarily for the release of some resources */@Overridepublic void aftercompletion (WebRequest request, Exception Exception) throws Exception {//TODO auto-generated method StubSystem.out.println (Exception + "-=-=--=--=-=-=- =-=-=-=-=-==-=--=-=-=-=");}}
2. Place the well-written interceptor in the Spring container: first, you need to define the MVC component in Spring.xml:
<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-3.0.xsd     Http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd     http://www.springframework.org/ SCHEMA/MVC     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">

Then define your own interceptor:
<mvc:interceptors><!--use beans to define a interceptor, directly defined under the Mvc:interceptors root interceptor will intercept all requests-->< Bean class= "Com.host.app.web.interceptor.AllInterceptor"/>//not written, intercept all requests <MVC:INTERCEPTOR><MVC: interceptor>//intercepts the specified request        <mvc:mapping path= "/validate"/>        <!--defined in MVC: Interceptor the following representation is blocked for a specific request--        <bean class= "Com.sinoiov.interceptors.LoginInterceptor"/>    </mvc:interceptor></mvc:interceptors>

OK to restart your project, start your debugging!


SPRINGMVC's Interceptor Interceptor's login blocker

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.