天天看點

servlet中如何解決中文亂碼的問題!...

一般中文亂碼都是因為你字元集的設定不當而緻的。一般servlet的中文亂碼問題針對各種不同的情況有四種解決的方案:

1,首先你是通過post方式送出表單的,這樣的話,那你隻需要設定request,response的字元集為utf-8或gbk即可(request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");).

2,針對送出方式為get和url重寫。如果是這兩種方式,那麼就需要封裝一個方法,

public String tocn(String str)

 {

  String rs=null;

  byte[] temp;

  try {

   temp=str.getBytes();

   rs=new String(temp,"utf-8");

  } catch (Exception e) {

   e.printStackTrace();

  }

  return rs;

 }

隻需調用即可.

3.在tomcat中的server.xml中修改

 <Connector port="9000" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" URIEncoding='utf-8'/>

其中[URIEncoding='utf-8']為新增的。

4.寫一個過濾器(記得在web.xml中配置filter節點).