文本框中的中文内容直接在第二个页面中从request中读出来能够通过设置 request.setCharacterEncoding("UTF-8")来实现,但 如果先存到session中 再从session中取出来 为什么设置 request.setCharacterEncoding("UTF-8") 没有效果? 要怎样设置才能取出session中的汉字?例子如下:
一:有两个页面 第一个
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="b.jsp" method="post">
USER:<input type="text" name="user"/>
<input type="submit" name="submit" value="submiT">
</form>
</body>
</html>
第二个:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3> b.jsp</h3>
<%
request.setCharacterEncoding("UTF-8");
%>
<%=request.getParameter("user")%>
</body>
</html>
这时得到的中文汉字能够正常显示。
如果我把user中的内容先通过一个servlet放到session中,再从session中取出来就不能正常显示了,如下所示:
第一个页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="aServlet" method="post">
USER:<input type="text" name="user"/>
密码PASSWORD:<input type="password" name="password">
<input type="submit" name="submit" value="submiT">
</form>
</body>
</html>
AServlet中内容为:
package com.wang.helloWorld;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().setAttribute("user", request.getParameter("user"));
response.sendRedirect("b.jsp");
}
}
然后再从b.jsp中读出来:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3> b.jsp</h3>
<%
request.setCharacterEncoding("UTF-8");
%>
<%=session.getAttribute("user") %>
</body>
</html>
就变成乱码了, 这是为什么,并且求问老司机怎么设置也能都出来正常中文
在你setSession之前先request.setCharacterEncoding("UTF-8");设置编码 就可以了