This article mainly introduces the SpringMVC interceptor, as follows:
1.DispatcherServlet
SpringMVC has a unified entry DispatcherServlet, and all requests pass through DispatcherServlet.
DispatcherServlet is a pre-controller configured in the web.xml file. To intercept matching requests, the Servlet intercept matching rules must be defined by itself, and the intercepted requests shall be distributed to the target controller according to certain rules for processing. So we now add the following configuration to web.xml:
<!-- When initializing the DispatcherServlet, the framework looks for a file named [servlet-name]-servlet.xml in the web application WEB-INF directory, and defines the relevant beans there, overriding any beans defined globally --> <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 by DispatcherServlet--> <url-pattern>/</url-pattern> </servlet-mapping>
2. Static resources do not intercept
If you only configure the intercepting of urls similar to *.do format, there is no problem with accessing static resources. However, if the configuration intercepts all requests (such as "/" we configured above), it will cause static resources such as js files, css files, and picture files to be inaccessible.
Generally, the interceptor is mainly implemented for permission management, mainly intercepting some url requests, so static resources are not intercepted. There are generally two ways to filter out static resources.
The first one is to use <mvc:default-servlet-handler /> (Generally, the default servlet name of the 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 is provided for containers such as tomcat, jetty, etc., and changes the static resource mapping from / to /static/ directory. For example, when you visited http://localhost/foo.css, now http://localhost/static/foo.css --> <!-- Don't 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 The name of the default servlet---"resin-file"
WebLogic default Servlet name--"FileServlet"
WebSphere default Servlet name--"SimpleFileServlet"
If the default servlet name of all your web application servers is not "default", you need to display the specified via the default-servlet-name property:
<mvc:default-servlet-handler default-servlet-name="The Servlet name used by the web server by default" />
The second type 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/"/> <mvc:resources mapping="/images/**" location="/static_resources/images/"/>
3. Custom interceptor
SpringMVC's interceptor HandlerInterceptorAdapter provides three preHandle, postHandle, and afterCompletion methods. preHandle is called before the service processor processes the request,
postHandle is executed after the business processor completes the execution of the request and generates the view. AfterCompletion is called after the DispatcherServlet has completely processed the request and can be used to clean up resources, etc. Therefore, in order to implement your own permission management logic, you need to inherit HandlerInterceptorAdapter and rewrite its three methods.
First, add my own defined interceptor to springmvc.xml. My implementation logic CommonInterceptor.
<!--Configure interceptors, multiple interceptors, execute sequentially --> <mvc:interceptors> <mvc:interceptor> <!-- Matches the url path. If you do not configure or /**, all Controllers will be intercepted --> <mvc:mapping path="/user/**" /> <mvc:mapping path="/test/**" /> <bean></bean> </mvc:interceptor> <!-- When setting up multiple interceptors, first call the preHandle method in sequence, and then call the postHandle and afterCompletion methods of each interceptor in reverse order --> </mvc:interceptors>
My interception logic is "Before login, any access URL will jump to the login page; after login is successful, jump to the previous URL", the specific 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 = LoggerFactory.getLogger(CommonInterceptor.class); public static final String LAST_PAGE = "com.alibaba.lastPage"; /* * Use regular mapping to the path that needs to be intercepted private String mappingURL; public void setMappingURL(String mappingURL) { this.mappingURL = mappingURL; } */ /** * Called before the business processor handles the request* If false is returned * Execute all interceptors' afterCompletion() from the current interceptor, then exit the interceptor chain* If true * Execute the next interceptor until all interceptors have been executed* Execute the interceptor controller * Then enter the interceptor chain, * Execute all postHandle() from the last interceptor * Then execute all postCompletion() from the last interceptor */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if ("GET".equalsIgnoreCase(request.getMethod())) { RequestUtil.saveRequest(); } log.info("==============执行顺序: 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 the login page! "); request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response); return false; }else return true; } /** * After the business processor completes processing the request, the action executed before the view is generated* 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("=========================================================================================================== log.info("======================================================================================================================================================================================================================================================================================================================================================================================================== response, Object handler, Exception ex) throws Exception { log.info("==============执行顺序: 3、afterCompletion================"); } } Note: In the above code, I wrote a RequestUtil, which mainly implements functions such as obtaining the current Request, Session object, saving and encrypting pages, and taking out.
At this point, the interceptor has been implemented, and the effect is as shown in the figure:
I will be blocked by visiting /test/hello directly
After logging in successfully, it will jump to the page corresponding to /test/hello
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.