1.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:
<!--initialize Dispatcherservlet, the framework looks for a file called [servlet-name]-servlet.xml in the Web application Web-inf directory, 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 processed Dispatcherservlet- < Url-pattern>/</url-pattern> </servlet-mapping>
2. Static resources do not intercept
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:)
<!--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-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 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:
<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:
<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 Interceptors
The 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,
<!--configuring interceptors, multiple interceptors, sequential execution -<mvc:interceptors> <mvc:interceptor> <!--matching URL paths, If not configured or/**, all controllers--- <mvc:mapping path= "/"/> <mvc:mapping path= "/user/** " will be blocked/> <mvc:mapping path= "/test/**"/> <bean class= "Com.alibaba.interceptor.CommonInterceptor" ></bean > </mvc:interceptor> <!--when setting up multiple interceptors, first call the Prehandle method sequentially, Then reverse-order the Posthandle and Aftercompletion methods for each interceptor- </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:
/** * */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 = Logger Factory.getlogger (commoninterceptor.class);p ublic static final String last_page = "Com.alibaba.lastPage";/* * Use the 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 () from the current interceptor to execute all interceptors, then exit the Interceptor chain * if return TR UE * Executes the next interceptor until all the interceptors are executed * and then executes the intercepted controller * and then goes into the interceptor chain, * back from the last interceptor to execute all Posthandle () *Then go back from the last interceptor to execute all aftercompletion ()/@Override public boolean prehandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {if ("GET". Equalsignorecase (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; /** * Actions performed before the view is generated when the business processor processes the request execution completion * Data can be added to Modelandview, such as current time */@Override public void Posthandle (HttpServletRequest request, Ht Tpservletresponse response, Object handler, Modelandview Modelandview) throws Exception {Log.info ( "============== Execution Order: 2, posthandle================"); if (Modelandview! = null) {//joins the current time Modelandview.addobject ("var", "Test Posthandle"); }}/** * is called after Dispatcherservlet fully processed 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 Aftercomple tion () */@Override public void aftercompletion (HttpServletRequest request, httpservletrespons E response, Object handler, Exception ex) throws Exception {log.info ("============== Execution Order: 3, Afterco mpletion================ "); } }
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
I have direct access to/test/hello and will be intercepted.
After successful login, we will jump to the corresponding page of/test/hello.
SPRINGMVC Interceptors (Resource and Rights Management)