Spring boot 自定义过滤器,通过过滤器修改request中的body参数

实战:代码实战;

实现过滤器 。重新封装request

@Configuration
public class FilterConfig  {

    @Bean
    public FilterRegistrationBean registFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(userInfoFilterBean());
        registration.addUrlPatterns("/**/v1/*");
        registration.setName("UserinfoFilter");
        registration.setOrder(2);
        return registration;
    }

    @Bean
    public Filter userInfoFilterBean() {
     return new UserInfoFilter();
    }

public class UserInfoFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(UserInfoFilter.class);

    private SellerMapper sellerMapper;

    private String[] notexcludedUrlArray = { "/url/***/",
            "/url/***/"};

    /**
     * @return
     *
     */
    @Autowired
    public void setUserInfoFilter(SellerMapper sellerMapper) {
        this.sellerMapper = sellerMapper;
    }

    private final int ADMIN = 1;

    /**
     * 判断是否 是 子账号 操作。是的 话,设置成管理员账户
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        boolean notExcluded = false;
        String url = ((HttpServletRequest) request).getServletPath();
        System.out.println(url+"-----------");
        for (String page : notexcludedUrlArray) {//判断是否在过滤url之外
        if(url.equals(page)){
            notExcluded = true;
            System.out.println("______是不过滤的路径");
            break;
        }
        }
        if (!notExcluded) {
            logger.info("判断是否业务系统子账号操作:---");
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            logger.info(httpRequest.getRequestURI());
            JxddUserInfo userInfo = CheckUserInfoUtil.getUserInfo(httpRequest);
            if (Objects.nonNull(userInfo)) {
                SellerCriteria sellerCriteria = new SellerCriteria();
                SellerCriteria.Criteria criteria = sellerCriteria.createCriteria();
                if (Objects.nonNull(userInfo.getMemberId()) && Objects.nonNull(userInfo.getStoreId())) {
                    criteria.andMemberIdEqualTo(userInfo.getMemberId());
                    List members = sellerMapper.selectByCriteria(sellerCriteria);
                    if (CollectionUtils.isNotEmpty(members)) {
                        if (members.get(0).getIsAdmin() == ADMIN) {
                            logger.info("主账号在操作:------");
                        } else {
                            logger.info("子账号在操作:切换------" + userInfo.getMemberId());
                            sellerCriteria.clear();
                            criteria = sellerCriteria.createCriteria();
                            criteria.andStoreIdEqualTo(userInfo.getStoreId());
                            List list = sellerMapper.selectByCriteria(sellerCriteria);
                            if (CollectionUtils.isNotEmpty(list)) {
                                List admins = list.stream().filter(s -> s.getIsAdmin() == ADMIN).collect(Collectors.toList());
                                if (CollectionUtils.isNotEmpty(admins)) {
                                    userInfo.setMemberId(admins.get(0).getMemberId());
                                }

                              //重新封装参数
                                HashMap m = new HashMap(request.getParameterMap());
                                m.put(JxddRequestConstants.USER_INFO, new String[] { JsonUtil.serialize(userInfo) });
                                HttpServletRequest req = (HttpServletRequest) request;
                                ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(req, m);
                                request = wrapRequest;
                                userInfo = CheckUserInfoUtil.getUserInfo((HttpServletRequest)request);
                                logger.info("切换到主账号-------------" + userInfo.getMemberId());
                            }
                        }
                    }
            }
              chain.doFilter(request, response);
            }
        }else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

 

@SuppressWarnings("unchecked")
public class ParameterRequestWrapper extends HttpServletRequestWrapper {

    private Map params;

    public ParameterRequestWrapper(HttpServletRequest request, Map newParams) {
        super(request);
        this.params = newParams;
    }

    @Override
    public Map getParameterMap() {
        return params;
    }

    @Override
    public Enumeration getParameterNames() {
        Vector l = new Vector(params.keySet());
        return l.elements();
    }

    @Override
    public String[] getParameterValues(String name) {
        Object v = params.get(name);
        if (v == null) {
            return null;
        } else if (v instanceof String[]) {
            return (String[]) v;
        } else if (v instanceof String) {
            return new String[] { (String) v };
        } else {
            return new String[] { v.toString() };
        }
    }

    @Override
    public String getParameter(String name) {
        Object v = params.get(name);
        if (v == null) {
            return null;
        } else if (v instanceof String[]) {
            String[] strArr = (String[]) v;
            if (strArr.length > 0) {
                return strArr[0];
            } else {
                return null;
            }
        } else if (v instanceof String) {
            return (String) v;
        } else {
            return v.toString();
        }
    }

}

 

参考文章:https://blog.csdn.net/ldw_2012210765/article/details/79653827

你可能感兴趣的:(filter,Java基础)