Servlet中接收中文数据乱码解决
客户端提交数据给服务端,如果数据中带有中文的话,有可能会出现乱码的情况,那么可以参照 以下方法解决
如果是get方式
1,编码转换
get请求过来的数据,在url地址栏上就已经经过编码了,所以我们取到的就是乱码。
tomcat收到了这批数据,getParameter 默认使用了ISO-8859-1去解码
直接在tomcat里面做配置,以后get请求过来的数据永远都是用UTF-8编码
2,可以在tomcat里面做设置处理conf/server.xml加上URLEncoding="utf-8"
如果时POST 请求时
request.setCharacterEncoding("utf-8");
设置传进来的参数接收的编码方式
这个说的时设置请求体里面的文字编码。get方式,用这行有用吗?--->没用
HttpServletResponse
负责返回数据给客户端。
- 输出数据到页面上
以字符流的方式写数据
response.getWriter().write("<a href=\"#\">hello</a>");
以字节流的方式写数据
response.getOutputStream().write("hello..".getBytes());
//設置當前請求的狀態碼是
response.setStatus(sc);
//設置一個頭
response.setHeader(name, value);
//設置意昂應内容以及編碼
response.setContentType(type);
但是,经过实验证明,可能是tomcat 9.0.5的新特性原因,get方法浏览器传过来的数据在tomcate getParamete()中的编码是utf-8,所以当用get方法请求在控制台显示时,Servlet中不需要再改变中文字符的编码方式。
同时,在实际应用中绝大部分是使用的post方法来传入参数,因此,对于get 传入参数乱码的解决方法了解即可。(ps:强迫症,过于较真)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("aa--------------------------");
String name=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("name="+name+"password"+password);
//get请求过来的数据,在url地址栏上就已经经过编码了,所以我们取到的就是乱码。
//tomcat收到了这批数据,getParameter 默认使用了ISO-8859-1去解码
/* name=new String(name.getBytes("ISO-8859-1"),"UTF-8");
password=new String(password.getBytes("ISO-8859-1"),"UTF-8");*/
System.out.println("name="+name+"password"+"="+password);
String csd=Charset.defaultCharset().name();
System.out.println("get方法使用的码表是:"+csd);
}