Get方式获取
使用如下页面表单内容:
<form action="http://127.0.0.1:8080/day07/params" method="get">
用户名:<input name="username" type="text" /><br/>
密 码:<input name="password" type="password" /><br/>
<input type="submit" />
</form>
获取表单内容代码:
控制台打印乱码内容:
乱码的根本原因是什么呢?
(打开tomcat下doc工程/index.html文件——Configuration—-HTTP 搜索 URIEncoding)
解决乱码的核心思路,就是把得到的乱码按照原来乱码的步骤逆序操作。
1、先以iso-8895-1进行解码
2、然后再以utf-8进行编码
1) 第一种方式 使用URLEncoder 和 URLDecoder 两个类 编解码
如:
//获取客户端传递过来的用户名参数值
String username = request.getParameter("username");
System.out.println("用户名:" + username);
// 先对用户名进行解码得到%E7%8E%8B%E6%8C%AF%E5%9B%BD 这样的形式
username = URLEncoder.encode(username, "ISO-8859-1");
// 再进行utf-8编码 一次得到页面上输入的文本内容
username = URLDecoder.decode(username, "UTF-8");
System.out.println("乱码解决后用户名:" + username);
2) 第二种方式 使用 String类的方法进行编解码
username = new String(username.getBytes("ISO-8859-1"), "UTF-8");
System.out.println("乱码解决后用户名:" + username);
Post请求
post请求方式乱码的原因是:
因为post是以二进制流的形式发送到的服务器。服务器收到数据后。
默认以iso-8859-1进行编码。
POST请求乱码解决,只需要在获取请求参数之前调用
request.setCharacterEncoding(“UTF-8”); 方法设置字符集 即可。
输出中文到客户端
1) 往客户端输出。分两个步骤:
第一步:先获取输出流(二进制返回用获取字节流,字符出获取字符流)
第二步:调用输出流对象,写出数据第客户端
如:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 通过response响应对象获取到字符输出流
Writer writer = response.getWriter();
// 往 客户 端 输出数据。
writer.write("this is response content!");
}
但是:输出中文到客户端的乱码解决方法
1) 如果拿到writer字符输出流。直接输出中文内容返回到客户端。会得到乱码。
比如:
程序如下,客户端收到会有乱码情况:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 通过response响应对象获取到字符输出流
Writer writer = response.getWriter();
// 往 客户 端 输出数据。
// writer.write("this is response content!");
// 输出中文数据到客户端
writer.write("这是中文的输出");
}
通过浏览器访问后显示的结果:
遇到这种情况是什么原因呢?
主要是因为服务器输出的字符串的编码和客户端显示字符串的编码不一致。导致乱码问题。
所以我们只需要设置服务器和客户端的编码相同就可以解决这个问题。
2) 乱码的解决。
设置服务器的字符串编码
//设置服务器输出的编码为UTF-8
response.setCharacterEncoding("UTF-8");
设置客户端的字符串显示编码。
//告诉浏览器输出的内容是html,并且以utf-8的编码来查看这个内容。
response.setContentType("text/html;charset=utf-8");
这两行语句要在获取输出流之前执行。才会生效。
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//设置服务器输出的编码为UTF-8
response.setCharacterEncoding("UTF-8");
//告诉浏览器输出的内容是html,并且以utf-8的编码来查看这个内容。
response.setContentType("text/html; charset=utf-8");
// 通过response响应对象获取到字符输出流
Writer writer = response.getWriter();
// 往 客户 端 输出数据。
// writer.write("this is response content!");
// 输出中文数据到客户端
writer.write("这是中文的输出");
}
再次通过浏览器访问。得到的是正确的中文。
JDBC连接数据库保存中文出现乱码
通过前面的方式将前台数据传过来的中文数据正确编码后,如果需要将数据保存到数据库,此时如果按照这种方式连接数据库,会出现中文乱码:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcmessageboard
user=root
password=root
此时需要在连接数据库时设置其编码格式为:
url=jdbc:mysql://localhost:3306/jdbcmessageboard?characterEncoding=utf-8
这样,保存到数据库的中文就不会出现中文乱码了。