客户端提交数据给服务器端,如果数据中带有中文的话,有可能会出现乱码情况

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27449993/article/details/82316445

request:

如果是GET方式

代码转码

String username = request.getParameter("username");

String password = request.getParameter("password");

String username = request.getParameter("username"); String password = request.getParameter("password");
System.out.println("userName="+username+"==password="+password);

//get请求过来的数据,在url地址栏上就已经经过编码了,所以我们取到的就是乱码,
//tomcat收到了这批数据,getParameter 默认使用ISO-8859-1去解码

//先让文字回到ISO-8859-1对应的字节数组 , 然后再按utf-8组拼字符串
username = new String(username.getBytes("ISO-8859-1") , "UTF-8");
System.out.println("userName="+username+"==password="+password);

 

直接在tomcat里面做配置,以后get请求过来的数据永远都是用UTF-8编码。

可以在tomcat里面做设置处理 conf/server.xml 加上URIEncoding="utf-8" 

如果是POST方式

request.setCharacterEncoding("UTF-8");

这行设置一定要写在getParameter之前。

response

以字符流输出:

//1. 指定输出到客户端的时候,这些文字使用UTF-8编码
    response.setCharacterEncoding("UTF-8");

    //2. 直接规定浏览器看这份数据的时候,使用什么编码来看。
    response.setHeader("Content-Type", "text/html; charset=UTF-8");
    response.getWriter().write("我爱JAVA...");

以字节流输出:

//1. 指定浏览器看这份数据使用的码表
    response.setHeader("Content-Type", "text/html;charset=UTF-8");

    //2. 指定输出的中文用的码表
    response.getOutputStream().write("我爱JAVA..".getBytes("UTF-8"));

通用:不管是以字节流输出还是以字符流输出

response.setContentType("text/html;charset=UTF-8");
//写在响应的数据的前面

猜你喜欢

转载自blog.csdn.net/qq_27449993/article/details/82316445