Spring MVC interceptor 01 and spring MVC blocker 01
Spring MVC Interception
Role: identity verification and permission check to prevent unauthorized access.
Scenario: In a bbs system, users cannot post or delete comments without logon;
A blog system cannot post a blog without logon, add a category, or delete a blog.
Spring MVC interception implementation is divided into two steps
(1) Compile the interceptor classMust inherit from org. springframework. web. servlet. HandlerInterceptor
Core methods:
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
In this method, perform permission verification. To put it bluntly, check whether the logon is successful. The core code is as follows:
@ Override public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {response. setCharacterEncoding ("UTF-8"); HttpSession session = request. getSession (true); String loginFlag = (String) session. getAttribute (Constant2.SESSION _ KEY_LOGINED_FLAG); if (loginFlag = null | (! LoginFlag. equalsIgnoreCase (Constant2.FLAG _ LOGIN_SUCCESS) {String path = request. getRequestURI (); // "/demo_channel_terminal/news/list" System. out. println ("You are not authorized to access:" + path); String contextPath = request. getContextPath (); request. setCharacterEncoding ("UTF-8"); response. setStatus (401); response. sendRedirect (contextPath); return false;} return true ;}
(2) configure the spring MVC configuration file
My spring MVC configuration file named spring2-servlet.xml
Interceptor Configuration:
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/bbs/json_add_bbs"></mvc:mapping> <mvc:mapping path="/news/json_add_tips"></mvc:mapping> <bean class="com.web.controller.intercept.MemberInterceptor"> </bean> </mvc:interceptor> </mvc:interceptors>
Explanation: when accessing/bbs/json_add_bbs and/news/json_add_tips, the interceptor class com. web. controller. intercept. MemberInterceptor (custom) will be applied)
This interceptor will not be applied when accessing other paths !!!
(3) project structure
The project is built using maven
Note:
If false is returned in the preHandle method, the request process is terminated, that is, no action is executed;