在写demo的时候发现存入数据库的中文,查询出来以页面形式展示时候,中文显示乱码,其中一个原因是提交的jsp编码与servlet展示页面的编码规范不一致。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'form.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form id = "form1" method = "post" action = "firstServlet" >
用户名:<br>
<input type="texy" name="name"><hr>
性别:<br>
男:<input type="radio" name="gender" value="男">
女:<input type="radio" name="gender" value="女">
<hr>
喜欢的颜色:<br>
红:<input type="checkbox" name="color" value="红">
绿:<input type="checkbox" name="color" value="绿">
蓝:<input type="checkbox" name="color" value="蓝">
黄:<input type="checkbox" name="color" value="黄">
粉:<input type="checkbox" name="color" value="粉">
<hr>
来自的国家:<br>
<select name="country">
<option value="中国">中国</option>
<option value="日本">日本</option>
<option value="美国">美国</option>
</select>
<hr>
<input type="submit" value="提交">
<input type="reset" value="重置" >
</form>
</body>
</html>
上面显示的提交的JSP页面。
展示如下:
用户名:
性别:
男: 女:
喜欢的颜色:
红: 绿: 蓝: 黄: 粉:
来自的国家:
servlet处理:
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response) {
try {
//设置解码方式
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String gender = request.getParameter("gender");
String[] color = request.getParameterValues("color");
String national = request.getParameter("country");
PrintStream out = new PrintStream(response.getOutputStream());
out.println("<!DOCTYPE HTML PUBLIC \""
+ "-//W3C//DTD HTML 4.01 Transitional//EN \">");
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>servlet测试</TITLE>");
out.println("<BODY>");
out.println("您的名字: " + name + "<hr>");
out.println("您的性别: " + gender + "<hr>");
out.println("您喜欢的颜色: ");
for (String c:color) {
out.println(c + " ");
}
out.println("<hr>");
out.println("您来自的国家: " + national + "<hr>");
out.println("<BODY>");
out.println("<HTML>");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
两者选择的编码都是utf-8,此时前端显示的中文正常。
您的名字: 张三
您的性别: 女
您喜欢的颜色: 红 蓝
您来自的国家: 中国
否则显示如下:
您的名字: 寮犱笁
您的性别: 鐢?
您喜欢的颜色: 绾? 榛? 绮?
您来自的国家: 涓浗