servlet中文乱码处理

在Servlet项目中发生中文乱码的几种情况
(1)表单form
  • post:在接收的servlet,写上
   request.setCharacterEncoding("utf-8");

       原因是:浏览器设置为了utf-8,但是传到web服务器变为了iso-8859-1,所以传到对于的servlet去的时候会产生乱码。

  • get: 我的没问题
       原因是它是通过请求行传递参数过去的,不是在请求体中
(2)超链接<a href="/encoding/GetInfoServlet?username=你好吗">测试</a>
         超链接默认是get,也没问题
(3)html页面乱码(常见):
    
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

(4)sendRedict()发生乱码:

   //这个方法用于转编码,防止乱码。有时候需要把utf-8改为gb2312

   public static String getNewString(String str){

       String newString="";

       try {

        newString=new String(str.getBytes("iso-8859-1"),"utf-8");

    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();

    }

       return newString;

   }
 (5)想要下载时,文件名不要乱码
 String temp=java.net.URLEncoder.encode("传奇.mp3","utf-8")

 response.setHeader("Content-Disposition","attachment;filename="+temp)
原文地址:https://www.cnblogs.com/sunnyCx/p/7544004.html