在寫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,此時前端顯示的中文正常。
您的名字: 張三
您的性別: 女
您喜歡的顏色: 紅 藍
您來自的國家: 中國
否則顯示如下:
您的名字: 寮犱笁
您的性別: 鐢?
您喜歡的顏色: 綰? 榛? 綺?
您來自的國家: 涓浗