The Springmvc Interceptor realizes the judgment to the user login state

Source: Internet
Author: User

Before the user login status has been used by filters filter implementation, today tried to use the SPRINGMVC Interceptor interceptor to achieve the user login status of the judge.

Add the following code to the 1.spring-mvc.xml configuration file:

<mvc:interceptors> <!--<mvc:interceptor> <mvc:mapping path= "/download/**"/>
        <mvc:mapping path= "/upload/**"/> <bean class= "Com.xxxx.interceptor.AuthInterceptor"/>
            </mvc:interceptor>--> <!--Check user permissions and exclude paths that do not require permissions--> <mvc:interceptor> <!--match all paths first, then exclude paths--> <mvc:mapping path= "/**"/> <!--Login-related requests--&G
            T <mvc:exclude-mapping path= "/user/login"/> <!--The following are static resources--> <mvc:exclude-mapping PA Th= "/img/**"/> <mvc:exclude-mapping path= "/css/**"/> <mvc:exclude-mapping path= "/boo" tstrap/** "/> <mvc:exclude-mapping path=/js/**"/> <mvc:exclude-mapping "path=" tepicker/** "/> <mvc:exclude-mapping path="/ueditorfile/** "/> <!--client file upload download, do not use this checksum-
   ->         <!--<mvc:exclude-mapping path= "/download/**"/> <mvc:exclude-mapping path= "/upload/**"/ >--> <!--whether the user has logged in check--> <bean id= "Logininterceptor" class= "Com.schooldevice.inte" Rceptor. Logininterceptor "></bean> </mvc:interceptor> </mvc:interceptors>


2. Write your own Logininterceptor interceptor class, and rewrite the three methods, the following code:

Package com.schooldevice.interceptor;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
Import Org.springframework.web.servlet.ModelAndView;

Import Org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

Import Com.schooldevice.domain.User; public class Logininterceptor extends Handlerinterceptoradapter {@Override public void aftercompletion (httpservletrequ EST request, httpservletresponse response, Object handler, Exception ex) throws Exception {super.aftercompletion (req
	Uest, response, Handler, ex); @Override public void Posthandle (HttpServletRequest request, httpservletresponse response, Object handler, Modelan
	Dview Modelandview) throws Exception {Super.posthandle (request, response, Handler, Modelandview); @Override public boolean prehandle (HttpServletRequest request, httpservletresponse response, Object handler) throw
        S Exception {request.setcharacterencoding ("UTF-8"); String URL = requEst.getservletpath ();
        System.out.println ("Post URL:" +url);
            if (!url.equals ("")) {//The Loginuser is logged in the user's = (user) request.getsession (). getattribute ("user"); if (Loginuser = null) {//No session is not logged in state System.out.println (">>> not logged in, please
                Re-login <<< "); Response.sendredirect ("..
                /loginandregist.jsp ");
            return false;
		} return true;
	return Super.prehandle (Request, response, handler); /*private boolean ispassurl (String URL) {if (!url.endswith ("/login/login") &&!url.ends With ("/login/chnagepassentry") &&!url.endswith ("/login/change_login") && !url.endswith ("/api/service") &&!url.endswith ("/api/service2") &&!url.en Dswith ("/province.txt") &&!url.endswith ("/city.txt") &Amp;&!url.endswith ("/area.txt") &&!url.endswith (". xml") &&!url.ends With (". js") &&!url.endswith (". css") &&!url.endswith (". png") && !url.endswith (". CSS ") &&!url.endswith (". CSS ") &&!url.endswith (". jpg ") &&!url.endswith (". gif ") &&!URL.E Ndswith (". JPG ") &&!url.endswith (".
        GIF ")) {return true;
    return false;
 }*/
	
}

Summarize: Defining the Interceptor implementation class

The interceptor interception request in SPRINGMVC is implemented through Handlerinterceptor. Defining a interceptor in SPRINGMVC is very simple, there are two main ways, the first way is to define the Interceptor class to implement the spring Handlerinterceptor interface, Or this class inherits the class that implements the Handlerinterceptor interface, such as the abstract class that spring has provided to implement the Handlerinterceptor interface Handlerinterceptoradapter The second way is to implement the Webrequestinterceptor interface of spring, or inherit the class that implements the Webrequestinterceptor. Implement Handlerinterceptor Interface

There are three methods defined in the Handlerinterceptor interface, which we use to intercept the user's request with these three methods.

    (1 ) prehandle  (httpservletrequest request, httpservletresponse response, Object Handle) method, as the name suggests, that the method will be invoked before the request is processed. The interceptor  in springmvc  is a chained call, and multiple interceptor  can exist in one application or in a single request. Each interceptor  call executes sequentially according to its declaration order, and the first execution is the prehandle  method in the interceptor , So you can do some forward initialization or a preprocessing of the current request in this method, or you can make some judgments in this method to decide whether the request should go on. The return value of the method is Boolean, and when it returns to false , the end of the request is expressed, and subsequent interceptor  and controller  are not executed; When the return value is true  will continue to invoke the next interceptor  prehandle  method, if it is the last interceptor , it will be the controller  method to invoke the current request.

    (2 ) posthandle  (httpservletrequest request, httpservletresponse response, Object Handle, Modelandview Modelandview) method, explained by the prehandle  method we know that this method includes the following aftercompletion  Method can only be invoked if the return value of the prehandle  method of the currently-owned interceptor  is true . The posthandle  method, as the name suggests, is executed after the current request is processed, that is, after the controller  method call, but it is invoked before the dispatcherservlet  makes the view return rendering. So we can manipulate the modelandview  object after controller  processing in this method. The posthandle  method is invoked in the opposite direction to the prehandle , which means that the interceptor  posthandle  method that is declared first will be executed later, and STRUTS2 The execution of the interceptor  in   is somewhat different. struts2  inside the implementation of the interceptor  process is also chained, but in the struts2  need to manually call actioninvocation  invoke  method to trigger a call to the next interceptor  or action , and then the contents of each interceptor  before the invoke  method invocation are executed in the order of Declaration, and the Invoke The content behind the   method is reversed.

(3) Aftercompletion (HttpServletRequest request, httpservletresponse response, Object handle, Exception ex) method, This method is also performed when the return value of the Prehandle method that requires the current corresponding interceptor is true. As the name suggests, the method executes after the entire request is finished, i.e. after the Dispatcherservlet renders the corresponding view. The main function of this method is to do the resource cleanup work.

Tip: In the use of mvc:exclude-mapping error, the solution: Change the configuration file http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd to HTTP ://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd can be.

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.