This article mainly studies the introduction of interceptors in SpringMVC, example code, configuration and other contents, as follows.
Springmvc's processor interceptor is similar to the filter Filter in Servlet development, which is used to pre-process and post-process the processor. This article mainly summarizes how the interceptor is defined in springmvc, as well as the execution and usage of the interceptor.
In springmvc, define the interceptor to implement the HandlerInterceptor interface and implement the three methods provided in the interface, as follows:
//Test interceptor1public class HandlerInterceptor1 implements HandlerInterceptor{@Override public Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {System.out.println("HandlerInterceptor1....preHandle");//false means intercept, not downward execution; true means release return true;}@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println("HandlerInterceptor1..postHandle");}@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println("HandlerInterceptor1..afterCompletion");}}I'll do a simple analysis for these three methods:
In springmvc, the interceptor is configured for the specific HandlerMapping, that is, if an interceptor is configured in a HandlerMapping, the handler successfully mapped through the HandlerMapping will eventually use the interceptor. For example, suppose that the mapper we configured in the configuration file is org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping, then we can configure the interceptor as follows:
<bean> <property name="interceptors"> <list> <ref bean="handlerInterceptor1"/> <ref bean="handlerInterceptor2"/> </list> </property></bean><bean id="handlerInterceptor1"/><bean id="handlerInterceptor2"/>
So in springmvc, how to configure a global interceptor? As mentioned above, the interceptors in springmvc are targeted at specific mappers. To solve this problem, the springmvc framework injects configured globally similar interceptors into each HandlerMapping, so that they can become global interceptors. The configuration is as follows:
<!-- Configure interceptors--><mvc:interceptors> <!-- Multiple interceptors, executed in sequence--> <mvc:interceptor> <mvc:mapping path="/**"/> <!-- Indicates intercepting all urls including suburl paths--> <bean/> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**"/> <bean/> </mvc:interceptor>
Generally, we use this configuration, just specify the URL to be intercepted in <mvc:mapping>.
Write two interceptors, HandlerInterceptor2 and HandlerInterceptor3, according to the above configuration. Then we will test the execution of the three interceptors and make a related summary.
In other words, we change the return value of the preHandle method of the three interceptors to true to test the execution order of the interceptor. The test results are as follows:
HandlerInterceptor1….preHandle
HandlerInterceptor2….preHandle
HandlerInterceptor3….preHandleHandlerInterceptor3….postHandle
HandlerInterceptor2….postHandle
HandlerInterceptor1….postHandleHandlerInterceptor3….afterCompletion
HandlerInterceptor2….afterCompletion
HandlerInterceptor1….afterCompletion
A summary is made based on the printed results: when all interceptors are released, the preHandle method is executed in the order of configuration; while the other two methods are executed in the order of configuration.
We change the return value in the preHandle method of the third interceptor to false, and the first two are still true, to test the execution order of the interceptor. The test results are as follows:
HandlerInterceptor1….preHandle
HandlerInterceptor2….preHandle
HandlerInterceptor3….preHandleHandlerInterceptor2….afterCompletion
HandlerInterceptor1….afterCompletion
Make a summary based on the printed results:
1. Since interceptors 1 and 2 are released, the preHandle of interceptor 3 can be executed. In other words, the previous interceptor can be released, and the latter interceptor can execute preHandle.
2. Interceptor 3 does not release it, so its other two methods are not executed. That is, if an interceptor does not release it, then its other two methods will not be executed.
3. As long as there is an interceptor that does not release, the postHandle method of all interceptors will not be executed, but as long as preHandle is executed and released, the afterCompletion method will be executed.
In fact, you can refer to the above situation. It is a special case. Let’s take a look at the running results:
HandlerInterceptor1….preHandle
Obviously, only the preHandle method of the first interceptor was executed. Since none of them were released, none of them executed the postHandle method and the afterCompletion method.
From the second case, for example, if you want to write a unified exception processing logic, then the interceptor must be placed in the first position of the interceptor chain and must be released, because only afterCompletion will be executed, and if it is placed in the first position of the interceptor chain, the afterCompletion method will be executed last, so that the logic of unified exception processing can be executed in it.
For example, log in to the authentication interceptor and place it in the first position in the interceptor link (if there is unified exception handling, it should be placed behind the unified exception handling). The permission verification interceptor is placed after logging in to the authentication interceptor (because the permission is only verified after logging in).
Here is a login verification interceptor to explain how to use springmvc's interceptor.
First, let’s look at the requirements: what we want to intercept, what we want to do when we intercept. The idea is as follows:
1. User request url
2. Interceptor performs interception verification. If the requested url is a public address (url that can be accessed without logging in), let it be released.
If the user session does not exist, then jump to the login page.
If the user session exists, release it and continue the operation.
//Login in @RequestMapping("/login")public String login(HttpServletRequest request, String username, String password) throws Exception {//In fact, you need to match the database //...//Here, assume that the login is successful HttpSession session = request.getSession();session.setAttribute("username", username);return "redirect:queryItems.action";}//Login @RequestMapping("/logout")public String logout(HttpServletRequest request) throws Exception {HttpSession session = request.getSession();session.invalidate();return "redirect:queryItems.action";} //Test interceptor 1public class LoginInterceptor implements HandlerInterceptor {//Execute before entering the Handler method // Can be used for identity authentication and identity authorization. If the authentication does not pass, it means that the user is not logged in. This method needs to intercept it and no further execution. Otherwise, @Override public Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {//Get the requested urlString url = request.getRequestURI();//Direquire whether the url public address is public (configure the public address to the configuration file when actually used) // Here is a suppose that the public address is logged in to the submitted address if(url.indexOf("login.action") > 0) {//If the login submission is performed, release return true;}//Judge sessionHttpSession session = request.getSession();//Fetch the user identity information from the session String username = (String) session.getAttribute("username");if(username != null) {return true;}//Execute here to indicate that the user's identity needs to be verified, jump to the login page request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);return false;}//Save space, omit the other two methods and do not write them, and there is no need to deal with them}Then configure the interceptor:
<!-- Configure interceptors--><mvc:interceptors> <!-- Multiple interceptors, execute in sequence--> <mvc:interceptor> <mvc:mapping path="/**"/> <!-- Intercept all urls including suburl paths--> <bean/> </mvc:interceptor> <!-- Other interceptors--></mvc:interceptors>
In this way, when we request any URL, we will be captured by the interceptor we just defined, and then we will determine whether there is user information in the session. If not, we will jump to the login page and let us log in:
<form action="${pageContext.request.contextPath }/login.action" method="post"> Username: <input type="text" name="username" /><br> Password: <input type="password" name="password" /><br> <input type="submit" name="submit" /></form>This is basically the introduction to the use of interceptors.
The above is all the content of this article about the detailed explanation of the interceptor in SpringMVC and the code examples. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!