美文网首页
Spring boot 使用Filter

Spring boot 使用Filter

作者: 后山野鹤 | 来源:发表于2019-06-28 09:55 被阅读0次

    Filter 过滤器,可以对web请求进行相应的过滤,通过filter技术,对web服务器管理的所有web资源进行管理
    实现原理
    Filter接口中doFilter方法,配置服务器每次在调用web资源的service方法之前都会先调用filter的doFilter方法,可以在doFilter方法中编写代码,做相应的过滤,
    可以控制的行为包括:
    1、判断是否允许请求
    2、是否允许访问目标资源
    3、修改报文

    举例 修改response报文内容

    自定义过滤器 LoginFilter Response代理类 WrapperResponse
    LoginFilter 类

           @WebFilter(urlPatterns = "/login", filterName = "loginFilter")
    public class LoginFilter implements Filter {
        private final Logger log = LoggerFactory.getLogger(getClass());
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
                ResponseWrapper wrapperResponse = new ResponseWrapper((HttpServletResponse) response);
    
        System.out.println("do filter");
        HttpServletRequest req = (HttpServletRequest) request;
        System.out.println(req.getRequestURI());
        Map<String, String[]> map = req.getParameterMap();
        System.out.println(req.getParameter("name"));
        if (map.containsKey("name") && map.get("name")[0].equals("1")) {
            chain.doFilter(request, wrapperResponse);
    
        } else {
            req.getRequestDispatcher("/failed").forward(request, wrapperResponse);
        }
    
        byte[] content = wrapperResponse.getResponseData();
        String str = new String(content)+"test";
        System.out.println("filter:" + str);
        HttpServletResponse res = (HttpServletResponse) response;
        writeResponse(res, 200, str);
    
        log.info("filter complete");
    
    }
    
    private void writeResponse(HttpServletResponse response, int status, String json) {
        try {
            response.reset();// 重置输入流
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "*");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(status);
            response.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    }
    

    }

    WrapperResponse 类

    public class ResponseWrapper extends HttpServletResponseWrapper {
    private ByteArrayOutputStream buffer = null;
    private ServletOutputStream out = null;
    private PrintWriter writer = null;
    
    public ResponseWrapper(HttpServletResponse resp) throws IOException {
        super(resp);
        buffer = new ByteArrayOutputStream();// 数据流
        out = new WapperedOutputStream(buffer);
        writer = new PrintWriter(new OutputStreamWriter(buffer));
    }
    
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return out;
    }
    
    @Override
    public PrintWriter getWriter() throws UnsupportedEncodingException {
        return writer;
    }
    
    @Override
    public void flushBuffer() throws IOException {
        if (out != null) {
            out.flush();
        }
        if (writer != null) {
            writer.flush();
        }
    }
    
    
    
    public byte[] getResponseData() throws IOException {
        flushBuffer();
        return buffer.toByteArray();
    }
    
    public String getContent() throws IOException {
        flushBuffer();
        return buffer.toString();
    }
    
    
    private class WapperedOutputStream extends ServletOutputStream {
        private ByteArrayOutputStream bos = null;
    
        public WapperedOutputStream(ByteArrayOutputStream stream) throws IOException {
            bos = stream;
        }
    
        @Override
        public void write(int b) throws IOException {
            bos.write(b);
        }
    
        @Override
        public void write(byte[] b) throws IOException {
            bos.write(b, 0, b.length);
        }
    
        @Override
        public void write(byte[] b, int off, int len) throws IOException {
            bos.write(b, off, len);
        }
    
        @Override
        public boolean isReady() {
            return false;
        }
    
        @Override
        public void setWriteListener(WriteListener writeListener) {
    
        }
      }
    }
    

    欢迎一块学习交流,需要源码的留言

    相关文章

      网友评论

          本文标题:Spring boot 使用Filter

          本文链接:https://www.haomeiwen.com/subject/iykrcctx.html