龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > JAVA开发 >

tomcat中文问题--过滤器

时间:2009-12-23 15:42来源:未知 作者:admin 点击:
分享到:
转载请注明:http://www.csdn.net/develop/article/17/17204.shtm 作者:ggyy1977@hotmail.com 使用filter来改变request的编码 在前面的文章里面,我们讨论了在tomcat下的jsp和servlet的字符编码问题! 知道当没

 

  转载请注明:http://www.csdn.net/develop/article/17/17204.shtm

  作者:ggyy1977@hotmail.com   

                                     使用filter来改变request的编码

  在前面的文章里面,我们讨论了在tomcat下的jsp和servlet的字符编码问题!

  知道当没有指定request的编码的时候,从客户端得到的数据是iso-8859-1编码的(request.getParameter()得到传递的参数值);

  但是我们怎么来改变request的编码呢?

  方法有很多种!

   比如:在getRequestDispatcher("/jsp/jsptoserv/hello.jsp").forward(request, response);之前修改

  request的编码,那么在jsp/jsptoserv/hello.jsp中得到的参数值就是制定的编码的字符。

  本文我们使用Filter来修改request的编码!

   

  1)首先编写filter类:

  package myFilter;

  
  import Java.io.IOException;
  import javax.servlet.*;
  

  public class ChangeCharsetFilter implements Filter {

  
      protected String encoding = null;/////要制定的编码,在web.XML中配置
  
      protected FilterConfig filterConfig = null;

          public void destroy() {

          this.encoding = null;
          this.filterConfig = null;

      }

      public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
   throws IOException, ServletException {

              if (request.getCharacterEncoding() == null){
              String encoding = getEncoding();////得到指定的编码名字
              if (encoding != null)
                  request.setCharacterEncoding(encoding);////设置request的编码
          }

           chain.doFilter(request, response);///有机会执行下一个filter

      }

      public void init(FilterConfig filterConfig) throws ServletException {

            this.filterConfig = filterConfig;
          this.encoding = filterConfig.getInitParameter("encoding");///得到在web.xml中配置的编码
        }

  
      protected String getEncoding() {

          return (this.encoding);///得到指定的编码

      }

  
  }

  
  2。编辑web.xml文件

  <?xml version="1.0" encoding="ISO-8859-1"?>

  <!DOCTYPE web-app
  
  

精彩图集

赞助商链接