|
发表于 2020-12-29 13:55:34
|
显示全部楼层
本帖最后由 ecoolper 于 2020-12-29 14:03 编辑
1、编写ResponseWrapper类
- package com.muyu.servlet;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpServletResponseWrapper;
- import org.apache.catalina.ssi.ByteArrayServletOutputStream;
- public class ResponseWrapper extends HttpServletResponseWrapper {
- private ByteArrayServletOutputStream byteArrayServletOutputStream;
- private PrintWriter printWriter;
- public ResponseWrapper(HttpServletResponse response) {
- super(response);
- byteArrayServletOutputStream =new ByteArrayServletOutputStream();
- }
- @Override
- public ServletOutputStream getOutputStream() {
- return byteArrayServletOutputStream;
- }
- @Override
- public PrintWriter getWriter() throws IOException {
- if(printWriter == null){
- printWriter =new PrintWriter(new OutputStreamWriter(byteArrayServletOutputStream, this.getCharacterEncoding()));
- }
- return printWriter;
- }
-
- /**
- * 获取response内容
- * @return
- */
- public byte[] getContent() {
- return byteArrayServletOutputStream.toByteArray();
- }
- }
复制代码 2、编写filter类(标准web代码),添加到UIServer中,在filter中处理错误信息- package com.muyu.filter;
- import java.io.IOException;
- import javax.servlet.Filter;
- import javax.servlet.FilterChain;
- import javax.servlet.FilterConfig;
- import javax.servlet.ServletException;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.log4j.Logger;
- import com.muyu.servlet.ResponseWrapper;
- public class BizErrorFilter implements Filter {
- private static final Logger logger = Logger.getLogger(BizErrorFilter.class);
- @Override
- public void destroy() {
- logger.info("destroy-->");
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
- logger.info("doFilter-->执行前--" + request.toString());
- ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);
- filterChain.doFilter(request, responseWrapper);
-
- String content = new String(responseWrapper.getContent(), responseWrapper.getCharacterEncoding());
- logger.info("content内容-->" + content);
- //处理content内容,然后再给response
- response.getOutputStream().write(responseWrapper.getContent());
-
- logger.info("doFilter-->执行后--" + response.toString());
- }
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
- logger.info("init-->");
- }
- }
复制代码
|
|