SPRINGMVC Interceptors (Resource and Rights Management)

Source: Internet
Author: User
Tags current time tomcat

1.DispatcherServletSPRINGMVC has a unified portal Dispatcherservlet, all requests are through Dispatcherservlet.
The Dispatcherservlet is the predecessor controller, which is configured in the Web. xml file.  Interception of matching requests, servlet intercept matching rules to be self-defined, the interception of requests, according to certain rules distributed to the target controller to deal with. So we now add the following configuration to Web. xml:
[HTML] View Plain copy print? <!--  Initialize  dispatcherservlet, the framework looks for a file called [servlet-name]-servlet.xml in the  web application Web-inf directory,              where to define the relevant beans, overriding any beans -->  defined in the global      <servlet>        <servlet-name> springmybatis</servlet-name>        <servlet-class> org.springframework.web.servlet.dispatcherservlet</servlet-class>         <load-on-startup>1</load-on-startup>      </servlet>       <servlet-mapping>        <servlet-name> springmybatis</servlet-name>        <!--  All the requests, will be handled by Dispatcherservlet  -->        <url-pattern>/</ url-pattern>   &NBsp;  </servlet-mapping>  

2. Static resources do not interceptIf you only configure the interception of URLs similar to *.do format, then access to the static resources is not a problem, but if the configuration intercepts all requests (such as the "/" configured above), it will cause the JS files, CSS files, picture files and other static resources can not be accessed.
The general implementation of the interceptor is mainly for the rights management, mainly to intercept some URL requests, so do not intercept static resources. There are generally two ways to filter out static resources,
First Kindis using <mvc:default-servlet-handler/> (the default servlet name for the Web application server is "default", so here we activate Tomcat's defaultservlet to handle the static file , configure the following code in Web. XML:)
[HTML]View Plain copy print? <!--the servlet is provided for containers such as Tomcat,jetty, and the static resource mappings from/to/static/directories, such as the original Access Http://localhost/foo.css, are now http://localhost/ STATIC/FOO.CSS-<!--do not intercept static files--<servlet-mapping> <servlet-name>default</servlet-nam e> <url-pattern>/js/*</url-pattern> <url-pattern>/css/*</url-pattern> <url -pattern>/images/*</url-pattern> <url-pattern>/fonts/*</url-pattern> </servlet-mapping >
Tomcat, Jetty, JBoss, and GlassFish the default servlet name-"Default"
Resin default servlet name-"Resin-file"
WebLogic default servlet name-"Fileservlet"
The name of the WebSphere default servlet-"Simplefileservlet"

If your default servlet name for all Web application servers is not "default", you need to display the specified through the Default-servlet-name property:
[HTML]View Plain copy print? <mvc:default-servlet-handler default-servlet-name= "The Web server used by default is used by the servlet name"/>
The second is to use <mvc:resources/>, add the following code to the SPRINGMVC configuration file:
[HTML]View Plain copy print? <mvc:resources mapping= "/js/**" location= "/static_resources/javascript/"/> <mvc:resources mapping= "/ styles/** "location="/static_resources/css/"/> <mvc:resources mapping="/images/** "location="/static_ Resources/images/"/>


3. Custom InterceptorsThe Springmvc Interceptor Handlerinterceptoradapter corresponds with three prehandle,posthandle,aftercompletion methods. Prehandle is called before the business processor processes the request,
Posthandle executes the view before the business processor processes the request execution, Aftercompletion is called after the Dispatcherservlet has completely processed the request, can be used to clean up resources, and so on. So to implement your own authority management logic, you need to inherit handlerinterceptoradapter and rewrite three of its methods.
First add your own defined interceptor to the springmvc.xml my implementation logic Commoninterceptor,
[HTML] View Plain copy print? <!--configuring interceptors,  multiple interceptors, sequential execution  -->   <mvc:interceptors>          <mvc:interceptor>              <!--  matches the URL path,  if not configured or/**, all controller -->   will be intercepted          <mvc:mapping path= "/"  />            <mvc:mapping path= "/user/**"  />            <mvc:mapping path= "/test/**"  />            <bean class= "Com.alibaba.interceptor.CommonInterceptor" ></bean>          </mvc:interceptor>       <!--  When setting up multiple interceptors, call the Prehandle method sequentially, then call each interceptor's Posthandle and Aftercompletion methods in reverse order  -->   </mvc:interceptors>  

My interception logic is "before the login, any access URL to jump to the login page, the successful login to jump to the previous URL", the code is as follows:
[Java] View Plain copy print? /**   *    */   package com.alibaba.interceptor;      import javax.servlet.http.httpservletrequest;   import  javax.servlet.http.httpservletresponse;      import org.slf4j.logger;   Import  org.slf4j.LoggerFactory;   import org.springframework.web.servlet.modelandview;    import org.springframework.web.servlet.handler.handlerinterceptoradapter;      import com.alibaba.util.requestutil;        /**   *  @author  tfj   * 2014-8-1   */   public class commoninterceptor  extends handlerinterceptoradapter{       private final logger  log = loggerfactory.getlogger (commoninterceptor.class);        Public static final string last_page =  "Com.alibaba.lastPage";       /*        *  use regular mapping to paths that need to be intercepted                   private String mappingURL;             public void setmappingurl (String mappingurl)  {                       this.mappingurl = mappingurl;          }        */       /**        *   called before the business processor processes the request         *  if return false         *      aftercompletion () of all interceptors from the current interceptor, and then exit the interceptor chain         *&nbSP; If you return to true        *     execute the next interceptor until all interceptors are executed          *     re-execute intercepted controller         *     then into the interceptor chain,        *      Back from the last interceptor execute All posthandle ()         *     Then go back from the last interceptor. All Aftercompletion ()         */           @Override          public boolean prehandle ( httpservletrequest request,                  httpservletresponse response, object handler)  throws Exception  {             if  ("GET". Equalsignorecase (Request.getmethod ())) &nbSp {               requestutil.saverequest () ;           }            log.info ("============== Execution order:  1, prehandle================");              string requesturi = request.getrequesturi ();            String contextPath =  Request.getcontextpath ();           string url =  requesturi.substring (Contextpath.length ());                    log.info ("RequestUri:" +requesturi);             log.info ("ContextPath:" +contextpath);          &Nbsp;  log.info ("URL:" +url);                         String username =   (String) Request.getsession (). getattribute ("user");            if (Username == null) {               log.info (" Interceptor: Jump to the login page. ");                Request.getrequestdispatcher ("/web-inf/jsp/login.jsp"). Forward (Request, response);                return false;            }else                return true;          }   & nbSp          /**       *  After the business processor finishes processing the request execution, Actions that are performed before the view is generated           *  can include data in Modelandview, such as current time         */        @Override           public void posthandle (httpservletrequest request,                  HttpServletResponse response,  object handler,                  modelandview modelandview)  throws Exception {               log.info ("============== Execution order:  2, posthandle================");              if (modelandview != null) {   //Join Current time                   Modelandview.addobject ("var",  "Test Posthandle");              }         }               /**        *  Called after the Dispatcherservlet has fully processed the request and can be used to clean up resources          *         *  when an interceptor throws an exception, all interceptors are executed back from the current Interceptor Aftercompletion ()          */          @Override           public void aftercompletion (httpservletrequest request,                  HttpServletResponse  RESPONSE,&NBSP;OBJECT&NBSP;HANDLER,&NBSP;EXCEPTION&NBSP;EX) &Nbsp;                throws  exception {             log.info ("============ = = Execution Order:  3, aftercompletion================ ");         }        }    

Note: In the above code I wrote a requestutil, mainly to achieve the current request, session object, save and encrypt the page, take out and other functions.

At this point, the interceptor has been implemented, the effect is as follows:

I have direct access to/test/hello and will be intercepted.


After successful login, we will jump to the corresponding page of/test/hello.




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.