[原]过滤器解决Servlet中文乱码

一、问题描述:Servlet接收来自JSP页面的中文参数时,在Servlet文件中编写输出语句,控制台输出中文乱码。

(乱码问题以前经常碰到,改编码格式相当麻烦)

利用过滤器解决方法可以一次性解决问题

1.过滤器在此方法的作用:每当程序要运行Servlet文件之前,都要去执行过滤器文件;在过滤器文件中编写要在Servlet文件之前运行的代码。

2.实现过程:分为两步(1.编写过滤器类。2.编写配置文件)

1.过滤器类

(1).在src文件下建个包 com.filter

(2).在此包下新建类  SetCharacterEncodingFilter

(3).代码:

 

package com.filter;

//1、新建一个SetCharacterEncodingFilter.java的类:(并在web.xml里配置好)即可以添加中文数据
import java.io.IOException;
import javax.servlet.*;

public class SetCharacterEncodingFilter  implements Filter{
 protected String encoding = null;

 protected FilterConfig filterConfig = null;

 protected boolean ignore = true;

 public void destroy()
 {
    this.encoding = null;
    this.filterConfig = null;

 }

 public void doFilter(ServletRequest request, ServletResponse response,
     FilterChain chain) throws IOException, ServletException
 {
    if (ignore || (request.getCharacterEncoding() == null))
    {
     String encoding = selectEncoding(request);
     if (encoding != null)
      request.setCharacterEncoding(encoding);
    }
    chain.doFilter(request, response);
 }

 public void init(FilterConfig filterConfig) throws ServletException
 {
    this.filterConfig = filterConfig;
    // 获取初始化参数
    this.encoding = filterConfig.getInitParameter("encoding");
    String value = filterConfig.getInitParameter("ignore");
    if (value == null)
    {
     this.ignore = true;
    } else if (value.equalsIgnoreCase("true"))
    {
     this.ignore = true;
    } else if (value.equalsIgnoreCase("yes"))
    {
     this.ignore = true;
    } else
     this.ignore = false;
 }

 protected String selectEncoding(ServletRequest request)
 {
    return (this.encoding);
 }


}

2.配置web.xml文件(/WebRoot/WEB-INF/web.xml)

 

<!--过滤器,将此代码放在</web-app>之上-->
  <filter>
   <filter-name>Set Character Encoding</filter-name>
   <filter-class>com.filter.SetCharacterEncodingFilter</filter-class>
   <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
   </init-param>
</filter>
<!--制定过滤器映射-->
<filter-mapping>
   <filter-name>Set Character Encoding</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

 

posted @ 2015-05-20 19:57  92浩荡天  阅读(641)  评论(0编辑  收藏  举报