Java编码过滤器:
package com.utils;
import javax.servlet.*;
import javax.servlet.http.*;
public class EncodingFilter extends HttpServlet implements Filter {
private FilterConfig config = null;
private String encoding = "";
public void init(FilterConfig config) throws ServletException {
this.config = config;
this.encoding = config.getInitParameter("encoding");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws java.io.IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
response.setCharacterEncoding(this.encoding);
java.io.PrintWriter out = res.getWriter();
out.print("过滤器设置编码为:" + this.encoding + "
");
chain.doFilter(req, res);
}
}
该类定义了一个变量encoding保存输入的参数,并通过init()函数取得该参数值。doFilter()函数是过滤器主要工作的地方。该类 首先去的当前页的request和response对象,调用response. setCharacterEncoding()函数来设置输入的编码参数。需要注意的是,最后有调用页面的输出对象out输出了编码的说明文字。从过滤器 的知识可知,这样每一个页面的最前面都会出现这一句话,因为chain.doFilter()函数在其后调用。在后续的效果图中将都会有这一句话。
分享到:
2010-06-23 23:08
浏览 1551
评论