2 qq 30084891 qq_30084891 于 2016.05.07 23:59 提问

filter过滤输出的问题

import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class HttpCharacterResponseWrapper extends HttpServletResponseWrapper {

private CharArrayWriter charArrayWriter = new CharArrayWriter();

public HttpCharacterResponseWrapper(HttpServletResponse response) {
super(response);
}

[color=#FF0000]@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(charArrayWriter);
}为什么要重写getwriter(),哪里会用到这个方法[/color]

public CharArrayWriter getCharArrayWriter() {
return charArrayWriter;
}
}

public class OutputReplaceFilter implements Filter {

private Properties pp = new Properties();

public void init(FilterConfig config) throws ServletException {
String file = config.getInitParameter("file");
String realPath = config.getServletContext().getRealPath(file);
try {
pp.load(new FileInputStream(realPath));
} catch (IOException e) {
}
}

public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {

// 自定义的 response
HttpCharacterResponseWrapper response = new HttpCharacterResponseWrapper(
(HttpServletResponse) res);

// 提交给 Servlet 或者下一个 Filter
chain.doFilter(req, response);

// 得到缓存在自定义 response 中的输出内容
String output = response.getCharArrayWriter().toString();

// 修改,替换
for (Object obj : pp.keySet()) {
String key = (String) obj;
output = output.replace(key, pp.getProperty(key));
}
// 输出
PrintWriter out = res.getWriter();为什么用原来的response,不用自定义的response
out.write(output);
out.println("<!-- Generated at " + new java.util.Date() + " -->");
}

public void destroy() {
}

以上2个问题困扰小弟许久了,还请各位大虾不吝赐教,小弟感激不尽

2个回答

CSDNXIAON
CSDNXIAON   2016.05.08 00:12

Filter过滤不了Action的问题
一个Filter编码过滤的白痴问题
miniUI tree 过滤(filter)的问题
----------------------同志你好,我是CSDN问答机器人小N,奉组织之命为你提供参考答案,编程尚未成功,同志仍需努力!

jhfsdfs
jhfsdfs   2016.05.08 08:04

我觉得你吧chain.dofilter放到最后

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!