【Java开发技术】登陆过滤器,前端携带token向后端发起请求

package com.hzsr.hzsr_test.filter;

import com.hzsr.hzsr_test.utils.Result;
import org.jose4j.json.internal.json_simple.JSONObject;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author: DiCraft
 * @Date: 2022-07-17 11:02
 * @package: com.hzsr.hzsr_test.filter
 * @Version: 1.0
 * @Decsription:
 */

@WebFilter(urlPatterns = {"/user/*"})
public class LoginFilter implements Filter {
    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //校验用户登陆状态
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //Filter跨域处理
        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods","POST.GET,OPTIONS,PUT,PATCH,DELETE,COPY,HEAD,LINK.UNLINK,PURGE,LOCK.UNLOCK,PROPFIND,VIEW");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Origin","Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,JWT-TOKEN,Keep-Alive,Origin,User-Agent,UserName,UserToken,X-Access-Token,X-App-ID,X-CustomHeader,X-Data-Type,X-Device-ID,X-Device-Signature,X-Mx-ReqToken,X-OS,X-Requested-With,body,uber-trace-id,x-csrf-token,x-log-apiversion,x-log-bodyrawsize,x-log-requestid,x-token");
        response.setHeader("Access-Control-Allow-Credentials","true");

        //获取Headers中的参数
        String token = request.getHeader("token");
        token = token == null ? "" : token;

        //查询token在Redis中的剩余时间
        Long expire = redisTemplate.getExpire(token);
        //是登陆状态
        if (expire > 0) {
            //已登录,放行
            filterChain.doFilter(servletRequest,servletResponse);
        } else { //未登录,响应数据
            String string = JSONObject.toJSONString((Map) new Result(null, "未登录", 103));
            response.setContentType("json/text; charset=UTF-8");

            PrintWriter out = response.getWriter();

            out.write(string);
        }
    }

    @Override
    public void destroy() {
//        Filter.super.destroy();
    }

}

你可能感兴趣的:(Java后端随笔,servlet,java,Filter,过滤器,Springboot)