看了网上韩顺平老师的Servlet教学视频,有一个关于中文乱码的问题,整理来和大家分享一下。发生中文乱码的三种情况:表单提交过程中、超链接以及sendRedirect()重定向过程中的乱码。
假设有user.html、FormServlet.java、AcceptServlet.java三个文件,其中user.html中含有表单,FormServlet.java用于接收表单提交的内容,从FormServlet.java可以跳转到AcceptServlet.java。
以下是三个文件的代码,估计大家都能看懂的,所以就不解释啦~
user.html
<html>
<body>
<form action="/WebSiteTest/FormServlet" method="get">
说一句话:<input type="text" name="description" >
<input type="submit" value="submit">
</form>
</body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FormServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//1.使用post提交表单
//request.setCharacterEncoding("utf-8");
//String description = (String)request.getParameter("description");
//System.out.println(description);
//2.使用get提交表单
//String description = new String(request.getParameter("description").getBytes("iso-8859-1"),"utf-8");
//System.out.println(description);
//3.由于超链接中的参数放于URL中,当参数值为中文时,可能出现乱码。使用超链接类似于get方法
//4.使用sendRedirect()跳转
String description = (String)request.getParameter("description");
response.sendRedirect("/WebSiteTest/AcceptServlet?ff="+description);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
AcceptServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AcceptServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
String description = new String(request.getParameter("ff").getBytes("iso-8859-1"),"utf-8");
System.out.println(description);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
另外,在学习的过程中发现,通过sendRedirect()传中文参数需要进行一定的处理,否则直接传中文的话会出现乱码。可以如下处理:
在传送参数的文件中编码URL
String str = "中文参数";
String tmp = URLEncoder.encode(str, "gb2312"); //编码URL中文参数
response.sendRedirect("/Webapp/AcceptServlet?tt="+tmp);
在接收参数的文件中解码URL
String newStr= new String(request.getParameter("tt").getBytes("iso-8859-1"),"gb2312"); //解码URL中文参数
上述的编码解码过程中的gb2312可以但需要同时换成utf-8,也能实现相同的效果。不同之处在于使用gb2312时URL将中文参数转换为如“%B4%AB%C6%E6”的形式,而使用utf-8时URL会使用中文参数会以如“传奇”的形式传输。