亲宝软件园·资讯

展开

JSP Post和Request中文乱码 通过过滤器(Filter)解决JSP的Post和Request中文乱码问题

人气:0
想了解通过过滤器(Filter)解决JSP的Post和Request中文乱码问题的相关内容吗,在本文为您仔细讲解JSP Post和Request中文乱码的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:JSP,Post,Request,中文乱码,下面大家一起来学习吧。

jsp代码:

import javax.servlet.*;
import javax.servlet.http.*;

public class CharsetFilter implements Filter
{
  public void destroy() 
  {
    
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
  {
    try
    {
      HttpServletRequest httpRequest = (HttpServletRequest)request;
      String method = httpRequest.getMethod().toLowerCase();
      if(method.equals("post"))
      {
        //如果是post,即表单方法,直接设置charset即可
        request.setCharacterEncoding("UTF-8");
      }
      else if(method.equals("get"))
      {
        //如果是get方法
        request.setCharacterEncoding("UTF-8");
        request = new HttpServletRequestWrapper((HttpServletRequest)request)
        {
          public String getParameter(String str)
          {
            try
            {
              return new String(super.getParameter(str).getBytes("iso-8859-1"),"GBK");
            }
            catch(Exception e)
            {
              return null;
            }
   
          }
        };
      }
      
      chain.doFilter(request, response);
    }
    catch(Exception e){}
  }
  
  public void init(FilterConfig filterConfig) 
  {
    
  }
}

过滤器配置:

<filter>
    <filter-name>CharFilter</filter-name>
    <filter-class>CharsetFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

加载全部内容

相关教程
猜你喜欢
用户评论