Filter and interceptor implement the login authentication function respectively.

        Filter (Filter) and interceptor (Interceptor) are two concepts commonly used in web development, used to process and control HTTP requests and responses. They are usually used to implement some common functions, such as authentication, logging, security checks, etc.

1. The differences between the two:

Filters are more suitable for Servlet-based applications, while interceptors are more suitable for projects using Spring MVC

  • Filter is a mechanism provided by the Servlet specification, mainly used for interception and processing during the processing of HTTP requests and responses. Filters can modify requests and responses, add or delete some attributes, header information, etc. They can be used in global processes, such as preprocessing a request before it enters the servlet, or postprocessing the response before it is returned to the client.
  • The interceptor is a mechanism provided by the Spring framework for intercepting and processing HTTP requests in the Spring MVC framework. Interceptors can control the request processing flow in a more fine-grained manner, such as performing some operations before or after entering the Controller.
2、Filter
Steps for usage:
1) Define Filter: Define a class, implement the Filter interface, and override all its methods.

Here is an example of implementing the login verification function:

@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//      将通用的 ServletRequest 转换为 HttpServletRequest
        HttpServletRequest req = (HttpServletRequest) servletRequest;
//      将通用的 ServletResponse 转换为 HttpServletResponse
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

//        1、获取请求url
        String url = req.getRequestURI().toString();

//        2、判断请求url中是否包含login,如果包含,说明是登录操作,放行。
        if (url.contains("login")){
            //放行操作
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

//        3、获取请求头中的令牌(token)。
        String jwt = req.getHeader("token");

//        4、判断令牌是否存在,如果不存在,返回错误结果(未登录)。
        if (!StringUtils.hasLength(jwt)){
            Result error = Result.error("NOT LOGIN");
            //手动转换,将对象转换为json格式 <-----阿里巴巴fastjson
            String notLogin = JSONObject.toJSONString(error);
            //将该字符串响应给前端
            resp.getWriter().write(notLogin);
            return;
        }
//        5、解析token,如果解析失败,返回错误结果(未登录)。
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){//解析失败
            e.printStackTrace();
            Result error = Result.error("NOT LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }
//        6、放行。
        filterChain.doFilter(servletRequest,servletResponse);

    }
}

        First of all, when implementing the method in a filter doFilter, you usually need to perform type conversion on the incoming request ( ServletRequest) and response ( ServletResponse) so that you can use more Servlet API features. So the first two lines of code here convert the generic ServletRequestand ServletResponseinto HttpServletRequestand HttpServletResponseso that you can access the richer functionality of HTTP requests and responses.

        Then follow the five steps of login authentication: 1. Get the request URL; 2. Determine whether the request URL contains login. If it does, it means that it is a login operation and let it pass; 3. Get the token in the request header (my specification here) The token is called token); 4. Determine whether the token exists. If it does not exist, return an error result (not logged in); 5. Parse the token. If the parsing fails, return an error result (not logged in).

        Among them, JwtUtils is a tool class used to realize jwt generation and decoding, which was written in the previous article.

2) Configure Filter:

        Add the @WebFilter annotation to the Filter class to configure the path to intercept resources. Add @ServletComponentScan to the boot class to enable Servlet component support.

        The @WebFilter annotation is used to configure the filter. The following (urlPatterns = "/*") specifies the URL pattern to be intercepted, and "/*" means intercepting all.

3、Interceptor
1) Define Interceptor: Define a class, implement the Interceptor interface, and override its preHandle method

Take the same example of implementing the login verification function:

@Component
public class LoginCheckinterceptor implements HandlerInterceptor {
    //快捷键ctrl+o 对方法进行重写
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        //目标资源方法执行前执行,返回true:放行,返回false:不放行

        //        1、获取请求url
        String url = req.getRequestURI().toString();

//        2、判断请求url中是否包含login,如果包含,说明是登录操作,放行。
        if (url.contains("login")){
            //放行操作
            return true;
        }

//        3、获取请求头中的令牌(token)。
        String jwt = req.getHeader("token");

//        4、判断令牌是否存在,如果不存在,返回错误结果(未登录)。
        if (!StringUtils.hasLength(jwt)){
            Result error = Result.error("NOT LOGIN");
            //手动转换,将对象转换为json格式 <-----阿里巴巴fastjson
            String notLogin = JSONObject.toJSONString(error);
            //将该字符串响应给前端
            resp.getWriter().write(notLogin);
            return false;
        }
//        5、解析token,如果解析失败,返回错误结果(未登录)。
        try {
            JwtUtils.parseJWT(jwt);
        }catch (Exception e){//解析失败
            e.printStackTrace();
            Result error = Result.error("NOT LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return false;
        }
//        6、放行。
        return true;
    }

    @Override//目标资源方法执行后执行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
4. Pay attention to method rewriting

In Java Web development, Filter and Interceptor are both middleware used to process requests and responses, but they have some differences in usage and implementation.

Filter
  • In the Java Servlet specification, Filter is a standard interface that provides a common way to handle requests and responses.
  • Filter needs to implement javax.servlet.Filterthe interface, which has three main methods: init, doFilterand destroy.
  • doFilterThe method must be implemented to write filtering logic. Requests and responses can be modified or processed.
  • The Filter method needs to be called explicitly chain.doFilter(request, response)to continue processing the request chain.

 

Interceptor
  • In Spring MVC, Interceptor is a mechanism provided by the Spring framework for processing requests and responses.
  • Interceptor needs to implement org.springframework.web.servlet.HandlerInterceptorthe interface, which has three methods: preHandle, postHandleand afterCompletion.
  • We need to override these methods as needed to implement preprocessing, postprocessing, and completion processing logic.
  • Interceptor methods do not need to explicitly call the next interceptor or processing chain.

 

Guess you like

Origin blog.csdn.net/LuoluoluoluoYan/article/details/132346093