In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the principle of Interceptor implementation of Java interceptor". In daily operation, I believe many people have doubts about the principle of Interceptor implementation of Java interceptor. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what is the principle of Interceptor implementation of Java interceptor?" Next, please follow the editor to study!
1, the concept of interceptor
Interceptors in java are objects that dynamically intercept Action calls. It provides a mechanism that enables developers to execute a piece of code before and after the execution of an Action, or to prevent the execution of an Action before it is executed. It also provides a way to extract reusable parts of the code from the Action. In AOP, interceptors are used to intercept a method or field before it is accessed and then add certain actions before or after. At present, what we need to master is mainly the interceptor of Spring, and the interceptor of Struts2 does not need to delve into it.
2, the principle of interceptor
Most of the time, interceptor methods are called through proxies. The interceptor implementation of Struts2 is relatively simple. When the request arrives at Struts2's ServletDispatcher, Struts2 looks for the configuration file, instantiates the relative interceptor object based on the configuration, then strands it into a list (List), and the last one invokes the interceptor in the list. Struts2's interceptor is pluggable, and interceptor is an implementation of AOP. The Struts2 interceptor stack connects interceptors into a chain in a certain order. When accessing intercepted methods or fields, interceptors in the Struts2 interceptor chain are called in the order previously defined.
3. Steps to customize the interceptor
Step 1: customize a class that implements the Interceptor interface, or inherit the abstract class AbstractInterceptor.
Step 2: register the defined interceptor in the configuration file.
Step 3: if you need to use the interceptor defined above in Action, you can also define the interceptor as the default interceptor for convenience, so that all Action are intercepted by this interceptor without special instructions.
4, the difference between filter and interceptor
The filter simply means "take what you want", the filter focuses on the web request, the interceptor simply means "reject what you want", and the interceptor focuses on method calls, such as intercepting sensitive words.
Interceptor is implemented based on java reflection mechanism, while filter is implemented based on function callback. (some people say that interceptors are based on dynamic agents.)
The interceptor does not rely on the servlet container and the filter depends on the servlet container.
The interceptor works only on Action, and the filter works on all requests.
Interceptors can access objects in the Action context and value stack, but filters cannot.
During the life cycle of Action, interceptors can be called multiple times, while filters can only be called once when the container is initialized.
5Perfect Spring interceptor abstract class HandlerInterceptorAdapter
If we use the Spring framework in our project, we can directly inherit the abstract class HandlerInterceptorAdapter.java to implement our own interceptor.
The Spring framework wraps the interceptor concept of java, which is very similar to Struts2. HandlerInterceptorAdapter inherits the abstract interface HandlerInterceptor.
Package org.springframework.web.servlet.handler;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;public abstract class HandlerInterceptorAdapter implements HandlerInterceptor {/ / public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {return true is called before the business processor processes the request } / / execute public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} / / after DispatcherServlet has fully processed the request after the business processor has finished processing the request, and before generating the view, it can be used to clean up the resource public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}
Next, let's take a look at UserRoleAuthorizationInterceptor,UserRoleAuthorizationInterceptor, a simple interceptor implemented by the Spring framework, which inherits the abstract class HandlerInterceptorAdapter and implements the function of intercepting user login authentication.
Package org.springframework.web.servlet.handler;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class UserRoleAuthorizationInterceptor extends HandlerInterceptorAdapter {/ / string array, used to store user role information private String [] authorizedRoles; public final void setAuthorizedRoles (String [] authorizedRoles) {this.authorizedRoles = authorizedRoles } public final boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {if (this.authorizedRoles! = null) {for (int I = 0; I < this.authorizedRoles.length; + + I) {if (request.isUserInRole (this.authorizedRoles [I])) {return true } handleNotAuthorized (request, response, handler); return false;} protected void handleNotAuthorized (HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {/ / 403 indicates that the resource is not available. The server understands the user's request but refuses to process it, usually due to permission problems response.sendError;}}
Next, we use the HandlerInterceptorAdapter abstraction class provided by the Spring framework to implement a custom interceptor. Our interceptor is called UserLoginInterceptorBySpring, which carries out login interception control.
The workflow goes like this: if the current user is not logged in, jump to the login page; after the login is successful, jump to the previously visited URL page.
Import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.handler.HandlerInterceptorAdapter / * * @ description uses the HandlerInterceptorAdapter provided by the spring framework to implement a custom interceptor * / public class UserLoginInterceptorBySpring extends HandlerInterceptorAdapter {/ / what is the difference between public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {/ / equalsIgnoreCase and equals before the business processor processes the request? If ("GET" .equals IgnoreCase (request.getMethod () {/ / RequestUtil.saveRequest ();} System.out.println ("preHandle..."); String requestUri = request.getRequestURI (); String contextPath = request.getContextPath (); String url = requestUri.substring (contextPath.length ()); System.out.println ("requestUri" + requestUri); System.out.println ("contextPath" + contextPath) System.out.println ("url" + url); String username = (String) request.getSession (). GetAttribute ("username"); if (null = = username) {/ / jump to the login page request.getRequestDispatcher ("/ WEB-INF/login.jsp") .forward (request, response); return false;} else {return true }} / / execute public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {System.out.println ("postHandle...") after the business processor processes the request and before generating the view; if (modelAndView! = null) {Map map = new HashMap (); modelAndView.addAllObjects (map) }} / / is called after the DispatcherServlet has fully processed the request and can be used to clean up the resource public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {System.out.println ("afterCompletion...");}}
The interceptor relies on the Java reflection mechanism to implement. The implementation of the interceptor uses the dynamic proxy implemented by JDK. As we all know, the dynamic proxy implemented by JDK depends on the interface.
Interceptors are used in aspect-oriented programming, which calls a method before your service or a method, or after a method. Interceptors are not configured in web.xml, for example, struts is configured in struts.xml.
Public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {Object result = null; System.out.println ("A piece of code can be executed before a method call" + method.getName ()); result = method.invoke (this.targetObj, args); System.out.println ("a piece of code can be executed after a method call" + method.getName ()); return result At this point, the study on "what is the principle of Interceptor implementation of Java interceptor" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.