SPRINGMVC3 interceptors, filtering Ajax requests, judging user logins, blocking rule settings

Source: Internet
Author: User

Web. XML settings: (/block all requests)

<servlet>    <Servlet-name>Dispatcher</Servlet-name>    <Servlet-class>Org.springframework.web.servlet.DispatcherServlet</Servlet-class>    <Init-param>        <Param-name>Contextconfiglocation</Param-name>        <Param-value>/web-inf/dispatcher.xml</Param-value>    </Init-param>    <Load-on-startup>1</Load-on-startup></servlet> <servlet-mapping>    <Servlet-name>Dispatcher</Servlet-name>    <!--All requests will be handled by Dispatcherservlet. -    <Url-pattern>/</Url-pattern></servlet-mapping> 

Spring MVC profile Interception rule settings (no matches will not be intercepted):

<!--Configure interceptors, multiple interceptors, sequential execution -      <mvc:interceptors>            <Mvc:interceptor>                <!--The URL path is matched, and if not configured or/**, all controllers will be blocked -              <mvc:mappingPath="/" />              <mvc:mappingPath= "/account/**" />  <!--Intercepting user Paths -            <mvc:mappingPath= "/image/**" />  <!--Chip Management Path -            <mvc:mappingPath= "/upload/**" />  <!--download path for blocking tablets -            <Beanclass= "Com.wzw.interceptor.LoginInterceptor"></Bean>    <!--Custom Interceptor Path -        </Mvc:interceptor>          <!--when multiple interceptors are set, the Prehandle method is called sequentially and then the Posthandle and Aftercompletion methods of each interceptor are called in reverse order -      </mvc:interceptors>  

Interceptor Code:

 PackageCom.wzw.interceptor;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportOrg.springframework.web.servlet.ModelAndView;ImportOrg.springframework.web.servlet.handler.HandlerInterceptorAdapter;ImportCom.wzw.entity.Account; Public classLogininterceptorextendshandlerinterceptoradapter{/*** Called before the business processor processes the request * if return false * Aftercompletion () from the current interceptor to execute all interceptors, then exit the Interceptor chain * if True       * Execute the next interceptor until all the interceptors have been executed * and then execute the intercepted controller * and then enter the Interceptor chain, * back from the last interceptor to perform all Posthandle () * Then go back from the last interceptor to execute all aftercompletion ()*/@Override Public BooleanPrehandle (httpservletrequest request, httpservletresponse response, Object handler)throwsException {String RequestUri= Request.getrequesturi ();//request full path, can be used to jump after loginString ContextPath = Request.getcontextpath ();//full path under ProjectString url = requesturi.substring (Contextpath.length ());//Request PageSystem.out.print ("Interception occurred ..."); System.out.println ("From:" +requesturi+ "Request"); Account User= (account) request.getsession (). getattribute (' account '); if(User = =NULL){//determine if the user exists, there is no return login interface, continue to intercept, exist through interception, release to the access page            /*** Intercept directory requests, whether for AJAX requests * Yes: no login required, direct access (because I am the Ajax login request for the home page) * No: Skip to login screen */            if(Request.getheader ("X-requested-with")! =NULL&& Request.getheader ("X-requested-with"). Equalsignorecase ("XMLHttpRequest"))){                 //if it is an AJAX request, the response header will have, X-requested-withSystem.out.print ("An AJAX request has occurred ..."); return true; //Response.setheader ("Sessionstatus", "timeout");//setting the session status in the response header}Else{System.out.print ("Back home ..."); Request.getrequestdispatcher ("/index.do"). Forward (request, response);//forward to login interface            }              return false; }Else              return true; }            /*** After the business processor processes the request execution, the actions performed before the view is generated * can include data in the Modelandview, such as the current time*/@Override Public voidPosthandle (httpservletrequest request, httpservletresponse response, Object handler, Mo Delandview Modelandview)throwsException {if(Modelandview! =NULL){//Join Current TimeModelandview.addobject ("var", "Test Posthandle"); }        }            /*** Called after dispatcherservlet complete processing of the request, can be used to clean up resources, etc. * * When an interceptor throws an exception, all interceptors are executed back from the current Interceptor Aftercompletion () */@Override Public voidaftercompletion (httpservletrequest request, httpservletresponse response, Object handler, Exception ex )                throwsException {}}

SPRINGMVC3 interceptors, filtering Ajax requests, judging user logins, blocking rule settings

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.