首页 > 其他分享 >springboot中Filter的使用

springboot中Filter的使用

时间:2022-08-25 09:47:24浏览次数:141  
标签:writer springboot 使用 request public Filter registration 过滤器 response

1.bean注入过滤器

 @Bean
    public FilterRegistrationBean companyUrlFilterRegister() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        //注入过滤器
        registration.setFilter( new PrintLogFilter());
        //拦截规则
        registration.addUrlPatterns("/*");
        //过滤器名称
        registration.setName("printRequestFilter");
        //过滤器顺序
        registration.setOrder(FilterRegistrationBean.LOWEST_PRECEDENCE);
        return registration;
    }

2.过滤器使用

public class PrintLogFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public void init(FilterConfig filterConfig) throws ServletException {}


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        String Sequence = "0" ;
        if(request instanceof HttpServletRequest){
            Sequence = ((HttpServletRequest )request).getHeader("Sequence");
        }
        logger.info("request 请求参数:" + request.getRemoteAddr()+ ":"+request.getRemotePort() + "  " +((HttpServletRequest) request).getRequestURI() + "  Sequence:"+Sequence+"  contentLenth:" +request.getContentLength());
         if( new Random().nextInt(10) < 5){
            chain.doFilter(request, response); //责任链模式
        }else {
            returnJson(response,"过滤器拦截返回!");
        }
    }

    public void destroy() {}
    
    /**
     * response回复str res
     *
     * @param response
     * @param res
     * @throws Exception
     */

    private void returnJson(ServletResponse response, String res)   {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(res);
        } catch (IOException e) {
            System.out.println("response error" + e.toString());
        } finally {
            if (writer != null)
                writer.close();
        }
    }


}

  

标签:writer,springboot,使用,request,public,Filter,registration,过滤器,response
From: https://www.cnblogs.com/heshana/p/16623166.html

相关文章