日期:2014-05-16  浏览次数:20339 次

JSP和servlet中文乱码终极解决

一、首先解决TOMCAT的问题

打开Tomcat\conf\server.xml,将

??? <Connector port="8080" protocol="HTTP/1.1"
?????????????? connectionTimeout="20000"
?????????????? redirectPort="8443"? />

改成

??? <Connector port="8080" protocol="HTTP/1.1"
?????????????? connectionTimeout="20000"
?????????????? redirectPort="8443"? URIEncoding='GBK' />

二、其次解决JSP中文传送问题

发送页面的index.jsp为(注意红色部分设定了编码):

<%@ page contentType="text/html; charset=gb2312" language="java"? errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>登录窗口</title>
</head>

<body>
<form id="form1" name="form1" method="get" action="login.jsp">
? <p align="center">
??? <label>用户
????? <input type="text" name="username" id="username" />
??? </label>
? </p>
? <p align="center">
??? <label>密码
????? <input type="text" name="password" id="password" />
??? </label>
? </p>
? <p align="center">
??? <label>
????? <input type="submit" name="submit" id="submit" value="提交" />
?????? </label><label><input type="reset" name="reset" id="reset" value="重置" />
??? </label>
? </p>
</form>
</body>
</html>

接收页面的login.jsp如下(注意红色部分设定了编码):

<%@ page contentType="text/html; charset=gb2312" language="java"? errorPage="" %>
<%request.setCharacterEncoding("GB2312");%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>登录信息</title>
</head>
<h2>用户登录实例</h2>
<h3>欢迎您,您输入的用户登录信息如下:</h3>
<body>
<p>用户名:<%out.println(request.getParameter("username"));%> </p>
<p>密&nbsp;&nbsp;&nbsp;码:<%out.println(request.getParameter("password"));%></p>
</body>
</html>

或者:

<%@ page contentType="text/html; charset=gb2312" language="java"? errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>登录信息</title>
</head>
<h2>用户登录实例</h2>
<h3>欢迎您,您输入的用户登录信息如下:</h3>
<body>
<p>用户名:<%out.println(request.getParameter("username").getBytes("ISO8859_1")));%> </p>
<p>密&nbsp;&nbsp;&nbsp;码:<%out.println(request.getParameter("password"));%></p>
</body>
</html>

三、最后是servlet,注意红色部分

package myservlet;

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;

/**
?* Servlet implementation class MyServlet
?*/
public class LoginServlet extends HttpServlet {
?private static final long serialVersionUID = 1L;
??? /**