日期:2014-05-16  浏览次数:20388 次

解决JSP中使用request乱码问题

经常在讨论区看到有人问我的JSP显示中文有乱码怎么办,我用request得到的用户输入的中文怎么是乱码,我把汉字写到数据库怎么是乱码,等等一些关于汉字乱码的问题。
其实这个问题很简单,管它汉字不汉字,还是日文,还是其他的什么双字节的语言,我们一律把它当作UTF-8看待。
(一)request中的双字节文字
好下面我们就来实现在整个应用程序中使用UTF-8编码工作,之所以选择UTF-8不仅仅之于上述原因,我们知道java的就是基于在UTF-8之上的,所以我们选择UTF-8应该没错^_^
我们首先把我们的.java, .jsp文件都用UTF-8编码来保存,如果以前的没有用UTF-8保存也无所谓,但是建议以后写的都用UTF-8来保存。
并在.jsp里面写:<%@page c%>而不是<%@page c%>
然后在web.xml添加下面一段:
<web-app>
...
  <filter>
    <filter-name>Set Character Encoding</filter-name>
    <filter-class>com.redv.projects.eduadmin.util.filters.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>
...
</web-app>



其中com.redv.projects.eduadmin.util.filters.SetCharacterEncodingFilter的代码如下:



package com.redv.projects.eduadmin.util.filters;



import java.io.IOException;
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.UnavailableException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




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 {



    // Conditionally select and set the character encoding to be used
    if (ignore || (request.getCharacterEncoding() == null)) {
      String encoding = selectEncoding(request);
      if (encoding != null) {
        request.setCharacterEncoding(encoding);           //就是这句话在工作的啦,哈哈,它:Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().
      }
    }



    // Pass control on to the next filter
    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) {
  &nb