1. Configuring in Web. xml
1 <!--Sessionfilter -2 3 <Filter>4 <Filter-name>Sessionfilter</Filter-name>5 <Filter-class>Com.juin.filter.SessionFilter</Filter-class>6 </Filter>7 8 <filter-mapping>9 <Filter-name>Sessionfilter</Filter-name>Ten <Url-pattern>/*</Url-pattern> One </filter-mapping> A - <!--above cutoff sessionfilter -
2. Create a Sessionfilter class
1 PackageCom.juin.filter;2 3 Importjava.io.IOException;4 ImportJavax.servlet.FilterChain;5 Importjavax.servlet.ServletException;6 Importjavax.servlet.http.HttpServletRequest;7 ImportJavax.servlet.http.HttpServletResponse;8 9 ImportOrg.springframework.http.HttpStatus;Ten ImportOrg.springframework.web.filter.OncePerRequestFilter; One A Public classSessionfilterextendsOnceperrequestfilter { - @Override - protected voiddofilterinternal (httpservletrequest request, httpservletresponse response, Filterchain Filterchain) the throwsservletexception, IOException { - - //non-filtered URI -string[] Notfilter =NewString[] {"/user/touser", "/login", "User/tomain" }; + - //URI of the request +String URI =Request.getrequesturi (); A //whether to filter at BooleanDoFilter =true; - for(String s:notfilter) { - if(Uri.indexof (s)! =-1) { - //If the URI contains a non-filtered URI, it is not filtered -DoFilter =false; - Break; in } - } to + if(doFilter) { - //Perform filtering the //get the login entity from the session *Object obj = Request.getsession (). getattribute ("Temp_user"); $ if(NULL==obj) {Panax Notoginseng BooleanIsajaxrequest =isajaxrequest (request); - if(isajaxrequest) { theResponse.setcharacterencoding ("UTF-8"); +Response.senderror (HttpStatus.UNAUTHORIZED.value (), "You have been too long to operate, please refresh the page"); A return; the } +Response.sendredirect (".. /user/touser "); - return; $}Else { $ //if the login entity exists in the session, continue - Filterchain.dofilter (request, response); - } the}Else { - //If filtering is not performed, continueWuyi Filterchain.dofilter (request, response); the } - } Wu - /** About * Determine if the AJAX request < feature description is detailed > $ * - * @paramRequest - * @returnis true, no false - * @see[Class, Class # method, Class # member] A */ + Public Static Booleanisajaxrequest (HttpServletRequest request) { theString Header = Request.getheader ("X-requested-with"); - if(Header! =NULL&& "XMLHttpRequest". Equals (header)) $ return true; the Else the return false; the } the}
View Code
SPRINGMVC Sessionfilter Login Filter