关于jsp乱码问题

来源:互联网 发布:淘宝人工刷流量和收藏 编辑:程序博客网 时间:2024/05/17 23:38
关于jsp乱码问题,首先要看浏览器是否支持中文,得看浏览器的编码是否设置好.或者干脆在jsp页面头上加上<%@page language="java" contentType='text/html; charset=GBK"%>或者<%@page language="java" contentType='text/html; charset=gb2312"%>.
    其实对一些什么做也无法消除的中文乱码问题,就要考虑下提交方式是get还是post,用post比get安全的多,因为get常常会因为浏览器的比兼容性而出现意想不到的乱码,只要改成post,那么问题便解决啦.也即:doPost(HttpServletRequest request, HttpServletResponse response),如果非要用get的方法进行传递的话,那么可以这样解决:打开tomcat的server.xml文件,然后往其中加上URIEncoding=“GBK"  .重启tomcat就OK了.
    对于内容的提交我们还可以像下面这样设置,这样提交的任何信息都能正确地显示:
try
{
  byte[] tempByte = Str.getBytes("ISO-8859-1")
  Str = new String(tempByte,"GB2312");
//即new String(Str.getBytes("ISO-8859-1"),"GB2312")
}
catch ( Exception ex )
{
}
    还要提到的一点是数据库中的乱码.当写入时发生乱码.解决办法是配置一个filter. 代码如下:
jdbc: mysql: //localhost: 3306/db? useUnicode=true&characterEncoding = GBK
这样也便解决数据库中大部分的乱码问题.
    上面只是对数据库问题提到用filter,但鼓浪bbs上有人讲大都都可以用filter,他讲的是很有道理.
其实我们可以在tomcat的webapps/servlet-examples目录中找到SetCharacterEncodingFilter类的源代码.如下:
    package 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;
    public class SetCharacterEncodingFilter implements
Filter{
      protected String encoding=null;
      protected Filter Config filterConfig=null;
    protected boolean ignore=true;
    public void destroy(){
      this.encoding=null;
      this.filterConfig=null;
      }
      public void doFilter(ServletRequest request, Ser-
      vletResponseresponse,  FilterChainchain)
      throws IOException, ServletException{
      // Conditionally select and set the character a ncoding
        to be used
      if (ignore II (request.getCharacterEncoding()==
      null)){
 String encoding=selectEncoding(request);
      if (encoding !=null)
      request.setCharacterEncoding(encoding);
        }
      //Pass controlon to the nextfilter
      chain.doFilter(request, response);
      }
      public void init(FilterConfig filterConfig) throws
ServletException{
        this.filterConfig=filterConfig;
      this.encoding=filterConfig.getInitParameter("en-
coding" );
        String value=filterConfig.getInitParameter("ig-
nore");
        if (value == nu 11)
          this.ignore=true;
      elseif (value.equalsIgnoreCase("true"))
          this.ignore=true;
      else if (value.equalsIgnoreCase("yes"))
          this.ignore=true;
        else
        this.ignore = false;
      }
      protected String selectEncoding(ServletRequest re-
quest){
        return (this.encoding);
      }
但是毕竟filter是Servlet2.3版本才新增加的,多少有点限制啦