主页 > 编程资料 > JSP(JAVA) >
发布时间:2016-01-01 作者:网络 阅读:266次

首先看是从什么地方开始出现的乱码,只要统一编码,就不会出现乱码,下面以uft-8(个人认为最好)为例,详细说明:

1、如果乱码是从jsp页面出现的,jsp头部页面加上:
<%@ page language="java" pageEncoding="UTF-8" %>
在head标签中加上标签。

2、如果乱码是在servlet中出现的,则有两种方法:
一种是在每个servlet中doget和doPost方法头部加上
request.setCharacterEncoding(“UTF-8″);
第二种最保险,一劳永逸,是专门写一个过滤器类,也称国际化,类名为SetCharacterEncodingFilter内容如下
复制代码 代码如下:
package com.sharep.filter;//包名
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;
public class SetCharacterEncodingFilter implements Filter
{
 protected String encoding = null;
 protected FilterConfig filterConfig = null;
 protected boolean ignore = true;
 public void init(FilterConfig filterConfig) throws ServletException
 {
  this.filterConfig = filterConfig;
  this.encoding = filterConfig.getInitParameter("encoding");
  String value = filterConfig.getInitParameter("ignore");
  if (value == null)
   this.ignore = true;
  else if (value.equalsIgnoreCase("true"))
   this.ignore = true;
  else
   this.ignore = false;
 }
 public void doFilter(ServletRequest request, ServletResponse response,
   FilterChain chain) throws IOException, ServletException
 {

  if (ignore || (request.getCharacterEncoding() == null))
  {
   String encoding = selectEncoding(request);
   if (encoding != null)
    request.setCharacterEncoding(encoding);
  }
  chain.doFilter(request, response);
 }
 public void destroy()
 {
  this.encoding = null;
  this.filterConfig = null;
 }
 protected String selectEncoding(ServletRequest request)
 {
  return (this.encoding);
 }
}

然后在web-inf的web.xml中加上如下代码:

复制代码 代码如下:

  SetCharacterEncoding
  com.young.filter.SetCharacterEncodingFilter//注意这里是类名,要有完整包名
  
   encoding
   UTF-8
  

 


 
  SetCharacterEncoding
  /*
 

这样就搞定了

3、如果还是有乱码,就是mysql数据库的问题了

1)保证建立数据库的时候数据库编码选择的是utf-8,最好在每个表中也指定编码格式,mysql默认是latin1
2)如果mysql版本是4.x以上,数据库中还是出现乱码,有以下两种解决方法:
一种是在连接数据库的代码中指定编码方式:
复制代码 代码如下:String url = “jdbc:mysql://localhost:3306/test2?autoReconnect=true&useUnicode=true&characterEncoding=gbk&mysqlEncoding=utf8″ ;

如果还是不行的话就是用
复制代码 代码如下:show variables like ‘collation_%';
这个命令来查看默认字符集,如果不是utf-8的话在my.ini(windows)或者是my.cnf(linux)将相应的编码修改成utf8之后重启mysql服务器就ok了

关键字词: