论坛首页 入门技术论坛

一个不错处理encoding的过滤器

浏览 1766 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (3)
作者 正文
   发表时间:2008-11-12   最后修改:2008-11-12

package com.yida.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class CharacterFilter implements Filter
{

    private String encoding;

    /**
     * 自定义一个类,完成get请求的中文乱码解决
     *
     * @author yohn
     */
    class MyRequest extends HttpServletRequestWrapper
    {

        public MyRequest(HttpServletRequest request)
        {
            super(request);
        }

        /**
         * 重写父类的方法
         *
         * @param name
         *            元素名
         */
        public String getParameter(String name)
        {
            String str = super.getParameter(name);

            try
            {
                str = new String(str.getBytes("iso8859-1"),encoding);
            }
            catch (Exception e)
            {
            }
            return str;
        }
    }

    public void destroy()
    {

    }

    @SuppressWarnings("unchecked")
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
    {
        try
        {
            HttpServletRequest hsr = (HttpServletRequest) request;
            if ("get".equalsIgnoreCase(hsr.getMethod()))
            {
                MyRequest mr = new MyRequest(hsr);
                response.setCharacterEncoding(encoding);

                chain.doFilter(mr,response);

            }
            else
            {
                hsr.setCharacterEncoding(encoding);
                response.setCharacterEncoding(encoding);
                chain.doFilter(request,response);
            }
        }
        catch (Exception e)
        {
        }
    }

    public void init(FilterConfig cfg) throws ServletException
    {
        String ie = cfg.getInitParameter("encoding");
        if (null != ie && "" != ie)
        {
            this.encoding = ie;
        }
        else
        {
            this.encoding = "UTF-8";
        }
    }
    public String getEncoding()
    {
        return encoding;
    }

    public void setEncoding(String encoding)
    {
        this.encoding = encoding;
    }

}

 

****************web.xml****************

<filter>

 <filter-name>ChineseFilter</filter-name>

 <filter-class>com.yida.filter.CharacterFilter</filter-class>
  <init-param>
     <param-name>encoding</param-name>
     <param-value>UTF-8</param-value>
  </init-param>

</filter>

 

<filter-mapping>

  <filter-name>ChineseFilter</filter-name>

  <url-pattern>/*</url-pattern>

</filter-mapping>

 

</filter>

   发表时间:2008-11-12   最后修改:2008-11-12
一切不透明, 手动处理办法都是愚蠢的!
0 请登录后投票
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics