Detailed SPRINGMVC interceptors (resources and Rights Management) _java

Source: Internet
Author: User
Tags current time tomcat

This article mainly introduces the SPRINGMVC interceptor, specifically as follows:

1.DispatcherServlet

SPRINGMVC has a unified entrance Dispatcherservlet, all requests are through Dispatcherservlet.

Dispatcherservlet is the predecessor controller, configured in the Web.xml file.  To intercept a matching request, the servlet interception matching rule has to be defined, and the intercepted request is distributed to the target controller according to certain rules. So we now add the following configuration to the Web.xml:

<!--initializing Dispatcherservlet, the framework looks for a file in the Web application Web-inf directory named [servlet-name]-servlet.xml, where the 
     associated beans is defined, Override 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 requests will be dispatcherservlet processed--> 
   < Url-pattern>/</url-pattern> 
  

2. Static resources do not intercept

If you configure only blocking URLs similar to the *.do format, access to static resources is fine, but if the configuration blocks all requests (such as the "/" configured above), it can cause static resources such as JS files, CSS files, picture files, and so on, to be inaccessible.

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,

The first is to use <mvc:default-servlet-handler/>, (the default servlet name for the general Web application server is "default"). So here we activate Tomcat's defaultservlet to process static files, and configure the following code in Web.xml:

<!--the servlet provides for containers such as tomcat,jetty, mapping static resources from/to/static/directories, such as the original Access Http://localhost/foo.css, now http://localhost/ Static/foo.css--> 
<!--do not intercept static files--> 
<servlet-mapping> 
  <servlet-name>default</ servlet-name> 
  <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 name of the default servlet--"Default"

Resin default servlet name-"Resin-file"

WebLogic default servlet name-"Fileservlet"

The name of the WebSphere default servlet-"Simplefileservlet"

If the default servlet name for all your Web application servers is not "default", you need to display the specified through the Default-servlet-name property:

<mvc:default-servlet-handler default-servlet-name= "The default servlet name used by the Web server used"/> 

The second is to use <mvc:resources/>, and add the following code to the SPRINGMVC configuration file:

<mvc:resources mapping= "/js/**" location= "/static_resources/javascript/"/> <mvc:resources mapping=  
" styles/** "location="/static_resources/css/"/>  

3. Custom Interceptor

The SPRINGMVC Interceptor Handlerinterceptoradapter corresponds to three prehandle,posthandle,aftercompletion methods. Prehandle is invoked before the business processor processes the request.

Posthandle executes before the view is generated after the execution of the Business processor processing request, Aftercompletion is invoked after the Dispatcherservlet has fully processed the request, and can be used to clean up resources. So to implement your own rights management logic, you need to inherit handlerinterceptoradapter and rewrite its three methods.

First of all, add your own definition of interceptors in springmvc.xml my implementation logic Commoninterceptor,

  <!--Configure interceptors, multiple interceptors, sequential execution--> 
<mvc:interceptors>  
  <mvc:interceptor>  
    <!--match the URL path, If not configured or/**, all controller--> 
    <mvc:mapping path= "/"/> <mvc:mapping path= 
    " 
    /user/**" will be intercepted/> <mvc:mapping path= "/test/**"/> <bean class= "Com.alibaba.interceptor.CommonInterceptor 
    " ></bean >  
  </mvc:interceptor> 
  <!--When multiple interceptors are set, the Prehandle method is called sequentially. Then the Posthandle and Aftercompletion methods of each interceptor are called in reverse order--> 

My interception logic is "to jump to the login page for any access URL before you log on, to jump to the previous URL after a successful login," as follows:

  /** * * * * * * 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 a regular map to the path that needs to be intercepted private String mappingurl;   
  public void Setmappingurl (String mappingurl) {this.mappingurl = Mappingurl; 
   * * */** * is 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 * if return True * Execute the next interceptor until all interceptors are executed * then execute the intercepted controller * and enter the Interceptor chain, * from the Last stopThe cutter goes back and executes all the Posthandle () * and then executes all aftercompletion ()/@Override public boolean prehandle from the Last Interceptor (Httpser Vletrequest request, HttpServletResponse response, Object handler) throws Exception {if ("get". Equalsignore 
    Case (Request.getmethod ())) {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);  
     
    Log.info ("URL:" +url);  
    String username = (string) request.getsession (). getattribute ("user"); if (username = null) {Log.info ("Interceptor: Jump to login page!) 
      "); 
      Request.getrequestdispatcher ("/web-inf/jsp/login.jsp"). Forward (request, response); 
    return false;   
  }else return true; /** * After the Business processor processing request is completed, generateActions performed before a view * You can add data to the Modelandview, such as the 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"); }/** * is invoked after Dispatcherservlet has fully processed the request, which can be used to clean up resources, etc. * * When a interceptor throws an exception, all interceptors are executed back from the current interceptor aftercompletion () */@Override public void aftercompletion (HttpServletRequest request, httpservletresponse response, Object handler, Exception ex) throws Exception {log.info ("============== Execution Order: 3, aftercompletion============  
  ====");  
 }  
 
}

Note: The above code I wrote a requestutil, the main implementation to obtain the current request, session object, save and encrypt the page, remove and other functions.

Now that the interceptor has been implemented, the effect is as follows:

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

Successful login will jump to the/test/hello corresponding page

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.