Spring MVC Interceptor Configuration

Source: Internet
Author: User

First configure the Spring MVC Portal in Web. xml:dispatcherservlet

SPRINGMVC 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:

<servlet><!--springmvc config-->    <servlet-name>springservlet< /servlet-name>    <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class>    <init-param >        <param-name>contextConfigLocation</param-name>         <!--Here is the new SPRING&NBSP;MVC configuration file-->         <param-value>classpath*:/spring/spring-mvc.xml</param-value>     </init-param>    <load-on-startup>1</load-on-startup></ Servlet><servlet-mapping>    <servlet-name>springservlet</servlet-name >    <!--  All requests will be processed by Dispatcherservlet  -->    < url-pattern>/</url-pattern></servlet-mapping><!--end springmvc config--> 

2, not interception of static resources

If 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,
The first is the use of <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, in the Web. XML, configure the following code:)

<!--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>

The second method:

With <mvc:resources/>, add the following code to the SPRINGMVC configuration file:

<mvc:resources mapping= "/js/**" location= "/global/js/"/><mvc:resources mapping= "/styles/**" location= "/ global/css/"/><mvc:resources mapping="/images/** "location="/global/images/"/>

3, the custom interceptor SPRINGMVC Interceptor Handlerinterceptoradapter corresponds provides 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,

<!--configuring SPRINGMVC interceptors, multiple interceptors, sequential execution--><mvc:interceptors> <!--using beans to define a interceptor, directly defined in MVC:        The interceptor below the interceptors root will intercept all requests-<!--<bean class= "" ></bean>--> <mvc:interceptor> <!--match URL path, if not configured or/**, will intercept all controllers--<mvc:mapping path= "/api/**"/> <bean cl ass= "Com.jason.system.CommonInterceptor"/> </mvc:interceptor> <!--when setting up multiple interceptors, first call the Prehandle method sequentially, The Posthandle and Aftercompletion methods of each interceptor are then called in reverse order--></mvc:interceptors>

4, the last realization class: Commoninterceptor

Package com.jason.system;import com.jason.utils.date.dateutils;import org.slf4j.logger;import  org.slf4j.LoggerFactory;import org.springframework.web.servlet.HandlerInterceptor;import  org.springframework.web.servlet.modelandview;import javax.servlet.http.httpservletrequest;import  javax.servlet.http.httpservletresponse;/** Public Interceptor  * created by liupu on 2015/10/ 26. */public class commoninterceptor implements handlerinterceptor {     private  static final logger logger= loggerfactory.getlogger ( Commoninterceptor.class);    /**     *  intercept before the request, Returns true to enter the request controller     *  @param  request     *   @param  response     *  @return      * @ throws exception     */     @Override     public boolean prehandle ( Httpservletrequest request, httpservletresponse response, object o)  throws  Exception {        logger.info ("============== Execution order:  1, prehandle================ ");         string requesturi =  request.getrequesturi ();        string method =  Request.getmethod ();        string url =  Request.getcontextpath ();         logger.info ("RequestUri:" +requestUri) ;         logger.info ("Method:" +method);         logger.info ("URL:" +url);//       string username  =   (String) request.getsession (). GetaTtribute ("user");//        if (Username == null) {//             request.getrequestdispatcher ("/tool/login/ Login.jsp "). Forward (Request, response);//             return false;//        }else{return true;}         return true;    }     /**     *  after the business processor handles the request execution, intercepts the,     *  before returning to the attempt Data can be added to the Modelandview, such as current time      *  @param  response      *  @param  request     *  @param  modelAndView      *  @throws  exception     */    @ override    public Void posthandle (Httpservletrequest request, httpservletresponse response, object  o, modelandview modelandview)  throws Exception {         logger.info ("============== Execution order:  2, posthandle================");         if  (Null!=modelandview) {             modelandview.addobject ("Servertime",  dateutils.getdate (DateUtils.YYYY_MM_DD_HH_mm _SS));         }    }    /**      *  is called after Dispatcherservlet completely finishes processing the request, and can be used to clean up resources such as      *   When an interceptor throws an exception, all interceptors are executed back from the current Interceptor Aftercompletion ()      *  @param  request      *  @param  response     *  @param  e      *  @throws  Exception     */     @Override      public void aftercompletion (httpservletrequest request, httpservletresponse  Response, object o, exception e)  throws Exception {         logger.info ("============== Execution order:  3, aftercompletion================");     }}


Spring MVC Interceptor Configuration

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.