package com.ruoyi.project.filter;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.project.system.domain.CrCustomer;
import com.ruoyi.project.system.service.CrCustomerService;
import com.ruoyi.project.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@Component
@WebFilter(urlPatterns = "/**", filterName = "LoginFilter")
@Order(1)
public class LoginFilter implements Filter {
@Autowired
private CrCustomerService crCustomerService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("======执行了用户id过滤器======");
HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
HttpServletResponse httpServletResponse=(HttpServletResponse)servletResponse;
//获取请求方式
if (httpServletRequest.getMethod().equals("GET")){
filterChain.doFilter(servletRequest,servletResponse);
}else {
//解析请求参数转换为json对象
BufferedReader streamReader = new BufferedReader(new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
if (jsonObject!=null){
String customerId = jsonObject.getString("customerId");
//判断用户id是否存在,存在是否是合法id
if (customerId==null){
filterChain.doFilter(servletRequest,servletResponse);
}else {
CrCustomer byId = crCustomerService.findById(Long.valueOf(customerId));
if (byId==null){
System.out.println("======错误的用户id="+customerId+"======");
//返回json格式401错误信息
httpServletResponse.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("application/json; charset=utf-8");
PrintWriter writer = httpServletResponse.getWriter();
Map<String, Object> map = new HashMap<>();
map.put("msg", "用户id错误,请重新登录");
map.put("code",HttpStatus.UNAUTHORIZED);
String s = JsonUtil.objectToJson(map);
writer.write(s);
}else {
filterChain.doFilter(servletRequest,servletResponse);
}
}
}else {
filterChain.doFilter(servletRequest,servletResponse);
}
}
}
@Override
public void destroy() {
}
}
自定义Filter过滤错误的用户id
最新推荐文章于 2023-11-25 01:12:21 发布