<> One , introduction

In the last article , Introduced Interceptor and Filter The difference and execution order of . We can know Filter Rely on Servlet, It is mainly aimed at URL
Address does a coding thing , Filter out useless parameters , Simple security verification ( Such as logging in or not logging in ), and Interceptor Rely on SpringMVC frame , It is in the
service Or before a method call , Call a method , Or after a method call , Call a method . Let's introduce it in detail Interceptor Usage and scenarios of .

<> Two , introduce
<>1,Interceptor use : (1), realization HandlerInterceptor Interface .
(2), The inheritance is implemented HandlerInterceptor The class of the interface . such as Spring Already provided HandlerInterceptor Interface
abstract class HandlerInterceptorAdapter ; <>2, about HandlerInterceptor Interface
Three methods are defined in the interface , We use these three methods to intercept the user's request .

(1),preHandle (HttpServletRequest request, HttpServletResponse response,
Object handle) method . seeing the name of a thing one thinks of its function , This method is called before the request is processed .
SpringMVC Medium Interceptor It's a chain call , There can be more than one application or one request at the same time Interceptor. each Interceptor The calls to are executed in the order in which they are declared , And the first thing to do is Interceptor Medium preHandle
method , Therefore, you can perform some pre initialization operations or preprocess the current request in this method , You can also make some judgments in this method to determine whether the request should continue .
The return value of this method is Boolean Type , When it returns as false Time , Indicates the end of the request , Subsequent Interceptor and Controller No more ; When the return value is true
Will continue to call the next Interceptor Of preHandle method , If it's already the last one Interceptor The current request will be called Controller
method .

(2),postHandle (HttpServletRequest request, HttpServletResponse response,
Object handle, ModelAndView modelAndView) method .
from preHandle We know that this method includes the following afterCompletion Methods can only belong to the Interceptor Of preHandle The return value of the method is true Can be called .**postHandle method , As the name suggests, after the current request is processed , that is Controller Method call , But it will be there DispatcherServlet Called before view return rendering , So we can do this in this way Controller After processing ModelAndView Object .**postHandle Method is called in the following direction preHandle It's the opposite , That is to say, it was stated first Interceptor Of postHandle The method will be implemented later .

(3),afterCompletion (HttpServletRequest request, HttpServletResponse response,
Object handle, Exception ex) method
, This method also needs the current corresponding Interceptor Of preHandle The return value of the method is true Only when the .
seeing the name of a thing one thinks of its function , This method will be after the end of the entire request , In other words DispatcherServlet Execute after rendering the corresponding view . The main function of this method is to clean up resources .

<> Three , code
<>1,Interceptor Usage scenarios of
Right up there Interceptor Three methods are introduced in detail , Let's take a look Interceptor Usage scenarios of .

<>(1), Landing interceptor
// Landing interceptor public class LoginInterceptor implements HandlerInterceptor { /** *
Complete business logic operations before controller execution * The return value of the method determines whether the logic continues to execute , true, Means to continue execution , false, Indicates that the execution is no longer continued . */ public
boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception { // Judge whether the current user has logged in HttpSession session = request
.getSession(); User loginUser = (User)session.getAttribute("loginUser"); if (
loginUser== null ) { String path = session.getServletContext().getContextPath();
response.sendRedirect(path + "/login"); return false; } else { return true; } }
/** * stay Controller Method call , But it will be there DispatcherServlet Called before view return rendering */ public void
postHandle(HttpServletRequest request, HttpServletResponse response, Object
handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated
method stub } /** * After rendering the view , Execute this method . */ public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception { } }
The landing interceptor is accessing each URL Whether to log in or not will be judged , If you don't land , Just jump to the landing page , It does not jump to the path to be accessed ( Data may not be available ).
In the login controller , User information needs to be placed in session in , And then in the landing interceptor , It is obtained in the following way HttpSession session =
request.getSession();
// Landing controller , to session User data code User dbUser = userService.queryForLogin(user); if (
dbUser!= null ) { session.setAttribute("loginUser", dbUser); }
<>(2), Logging Interceptor
/** * For logging , Before each request , Print the address and parameters of the request , Convenient debugging */ public class LogInterceptor implements
HandlerInterceptor { /** Log */ private static Logger logger = LogManager.
getLogger(LogManager.ROOT_LOGGER_NAME); @Override public boolean preHandle(
HttpServletRequest request,HttpServletResponse response, Object arg2) throws
Exception{ StringBuilder sb = new StringBuilder(); String uri = request.
getRequestURI(); sb.append("---------------> demo uri:").append(uri).append(" -
"); Enumeration<String> enums2 = request.getParameterNames(); while (enums2.
hasMoreElements()) { String key = enums2.nextElement(); sb.append("\"").append(
key).append("\":").append( request.getParameter(key)).append(", "); } logger.
info(sb.toString()); return true; } @Override public void postHandle(
HttpServletRequest request,HttpServletResponse response, Object arg2,
ModelAndView arg3)throws Exception { } @Override public void afterCompletion(
HttpServletRequest request,HttpServletResponse response, Object arg2, Exception
arg3) throws Exception { } } <>(3), Authorized access Url Interceptor

It needs to be explained here , Whether in the portal or management platform , If you log in to the system , You know some of them exist url, Even if you don't have access , But you type the correct one directly into the browser url, You can still visit the page , The purpose of this interceptor is to solve this problem .
// Here we adopt the way of inheriting abstract class , It's not implementation Interceptor mode public class AuthInterceptor extends
HandlerInterceptorAdapter { @Autowired private PermissionService
permissionService; @Override public boolean preHandle(HttpServletRequest request
, HttpServletResponse response, Object handler) throws Exception { // Get the user's request address
String uri= request.getRequestURI(); String path = request.getSession().
getServletContext().getContextPath(); // Determine whether the current path needs permission verification . // Query the collection of all paths that need to be verified List
<Permission> permissions = permissionService.queryAll(); Set<String> uriSet =
new HashSet<String>(); for ( Permission permission : permissions ) { if (
permission.getUrl() != null && !"".equals(permission.getUrl()) ) { uriSet.add(
path+ permission.getUrl()); } } if ( uriSet.contains(uri) ) { // Authority verification //
Determine whether the current user has the corresponding permissions Set<String> authUriSet = (Set<String>)request.getSession() .
getAttribute("authUriSet"); if ( authUriSet.contains(uri) ) { return true; }
else { response.sendRedirect(path + "/error"); return false; } } else { return
true; } } } <>(4), stay SpringMVC Register these interceptors in <mvc:interceptors> // Block all requests , Including static resources <
mvc:interceptor> <mvc:mapping path="/**"/> <bean class="
com.scorpios.atcrowdfunding.web.LogInterceptor"></bean> </mvc:interceptor> <mvc:
interceptor> <mvc:mapping path="/**" /> <mvc:exclude-mapping path="/login" /> <
mvc:exclude-mapping path="/doAJAXLogin" /> <mvc:exclude-mapping path="
/bootstrap/**" /> <mvc:exclude-mapping path="/css/**" /> <mvc:exclude-mapping
path="/fonts/**" /> <mvc:exclude-mapping path="/img/**" /> <mvc:exclude-mapping
path="/jquery/**" /> <mvc:exclude-mapping path="/layer/**" /> <mvc:
exclude-mapping path="/script/**" /> <mvc:exclude-mapping path="/ztree/**" />
// The interceptor does not intercept static resources <bean class="com.scorpios.atcrowdfunding.web.LoginInterceptor">
</bean> </mvc:interceptor> <mvc:interceptor> <mvc:mapping path="/**" /> <mvc:
exclude-mapping path="/login" /> <mvc:exclude-mapping path="/doAJAXLogin" /> <
mvc:exclude-mapping path="/bootstrap/**" /> <mvc:exclude-mapping path="/css/**"
/> <mvc:exclude-mapping path="/fonts/**" /> <mvc:exclude-mapping path="/img/**"
/> <mvc:exclude-mapping path="/jquery/**" /> <mvc:exclude-mapping path="
/layer/**" /> <mvc:exclude-mapping path="/script/**" /> <mvc:exclude-mapping
path="/ztree/**" /> // The interceptor does not intercept static resources <bean class="
com.scorpios.atcrowdfunding.web.AuthInterceptor"></bean> </mvc:interceptor> </
mvc:interceptors>
That's the interceptor Interceptor Use and scenarios of .

<> Four , summary

(1), stay SpringMVC In the use of mvc:interceptors label , To declare a series of interceptors , Then they can form a chain of interceptors , The execution order of interceptors is in the order of declaration , In the first declared interceptor preHandle Methods are executed first , But its postHandle Methods and afterCompletion The method will be implemented later .

(2), stay mvc:interceptors Statement under label interceptor There are two main ways :
a, Define a Interceptor Implementation class bean object . Declared in this way Interceptor The interceptor will block all requests section .
b, use mvc:interceptor Label . Declared in this way Interceptor It can be done through mvc:mapping Sub tag
Request path to be intercepted .
After these two steps , The interceptor defines the interceptor .

Technology
©2019-2020 Toolsou All rights reserved,
ElementUI In the select Of label value ( Essence )2020 year 6 month 29 day C# Class library Interface signature verification ( Essence )2020 year 8 month 15 day redis database StackExchange.Redis in Set type (C# edition ) be based on STM32 Design of infrared obstacle avoidance car ( There is a code )Golang Array bisection , Array split , Array grouping Linux File name validity detection git Pull the remote branch and switch to it Obviously post Why does the request display parameters in the address bar ?element-ui+vue-treeselect Verification of drop down box Hack Bar 2.1.2 Press F9 No response