一般来说web项目遇到乱码,要先分析错误的来源。
我这里使用的Tomcat服务器
1.源文件编译格式不同。
2.在传输的过程编码格式改变了。
3.没有统一编码格式。
4.输出方和输入方的编码格式不同。
在web项目中乱码一般都出现在servlet的doGet()方法中
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- pageEncoding="UTF-8" 等于设置页面的编码-->
<!-- jsp头部的这段文字:contentType="text/html; charset=UTF-8" 等于告诉编译器使用该字符集对jsp页面进行编译 -->
<!-- html头部的这段文字:contentType="text/html; charset=UTF-8" 等于告诉浏览器使用该字符集对网页进行解析 -->
出现乱码问题先查看头部的编码格式
使用form表单提交数据
下面是servlet的代码 post方法
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("---------------doPost()---------------------");
// 如果使用post方式提交,首先将request请求编码设置为utf-8,那么你拿到的数据就不是乱码
req.setCharacterEncoding("utf-8");
String password = req.getParameter("password");
System.out.println("password:" + password);
//设置响应内容的编码形式:utf-8
resp.setCharacterEncoding("utf-8");
//告诉浏览器使用utf-8进行编码
//这里的text/plain是普通文本的意思, 详细可以查看MIME(Multipurpose Internet Mail Extensions)多用途互联网邮件扩展类型。
resp.setContentType("text/plain; charset=UTF-8");
PrintWriter pw = resp.getWriter();
if ("lin".equals(password)) {
pw.write("注册成功");
//刷新
pw.flush();
//关闭
pw.close();
} else {
pw.write("注册失败");
pw.flush();
pw.close();
}
}
<form action="RegisterServlet" method="get">
password:<input type="text" name="password"/><br/>
<input type="submit"/>
</form>
注意点:doGet处理请求,已经不会出现乱码,只要你使用的Tomcat是8.0及以上,因为Tomcat8.0默认字符集是UTF-8
如果是是Tomcat7.0或以下是默认iso-8859-1编码格式,就会出现乱码
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应内容的编码形式:utf-8
resp.setCharacterEncoding("utf-8");
//告诉浏览器使用utf-8进行编码
resp.setContentType("text/plain; charset=UTF-8");
PrintWriter pw = resp.getWriter();
if ("666".equals(password)) {
pw.write("注册成功");
pw.flush();
pw.close();
} else {
pw.write("注册失败");
pw.flush();
pw.close();
}
}
在特殊情况下如果是老一点的版本的话,出现乱码可以吧拿到的乱码反向解码,在用utf-8编译
//获取参数
String username=req.getParameter("username");
//用字节去接收解码的数据
byte[] bytes=username.getBytes("iso-8859-1");
//把字节编译 成utf-8
String username_utf=new String(bytes,"utf-8");
System.out.println(username_utf);
个人感觉容易出问题的都在传输过程中,两者的编码格式不同,这点要很注意。