日期:2014-05-17 浏览次数:20818 次
public class SetCharacterEncoding implements Filter
{
// 定义编码类型属性
protected String encoding = null;
// 定义接受过滤器参数的对象
protected FilterConfig filterConfig = null;
// 过滤器初始化方法
public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
//System.out.println("初始化字符编码过滤器");
}
// 过滤器主方法
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
// 若过滤器编码格式不为空则进入设置
if (this.encoding != null)
{
request.setCharacterEncoding(this.encoding);
}
// System.out.println("字符编码过滤器执行前");
// 继续传递请求,执行程序
chain.doFilter(request, response);
// System.out.println("字符编码过滤器执行后");
}
// 过滤器销毁的方法
public void destroy()
{
try
{
Thread.sleep(1000);// 休眠1s
} catch (Exception e)
{
e.printStackTrace();
} finally
{
// System.out.println("字符编码过滤器销毁的方法");
}
}
}
String keywords = request.getParameter("keywords");
keywords = new String(keywords.getBytes(),"utf-8");
------解决方案--------------------
可以在配置文件中配置filter,然后把filter的都配置好,编码格式一致,应该没问题。