java mysql 中文乱码问题 求高手指教

q917769032 2012-08-20 11:46:57
做了一个登录界面以下是代码:
login.jsp

<%@ page contentType="text/html; charset=gb2312"%>
<%
request.setCharacterEncoding("gb2312");
%>
<!-- 该Login页面是一个简单的登录界面 -->
<!--
该JSP程序是用来测试与MySQL数据库的连接,
需要一个数据库:LearnJSP,和其中一个表:userinfo
表中有两个字段分别为:UserName varchar (20) not null,UserPwd varchar (20) not null
-->
<html>
<head>
<title>登录</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<meta http-equiv="Content-Language" content="ch-cn">
</head>
<body bgcolor=cyan>
<!-- Form 用来提取用户填入并提交的信息-->
<form method="POST" name="frmLogin" action="LoginServlet">
<h1 align="center">用户登录</h1><br>
<div align="center">用户名:
<input type="text" name="txtUserName" value=""
size="20" maxlength="20"
onfocus="if(this.value=='Your name')this.value=";"><br>密码:
<input type="password" name="txtPassword" value=""
size="20" maxlength="20"
onfocus="if(this.value=='Your password')this.value=";"><br>
<input type="submit" name="Submit" value="提交" onClick="validateLogin();" >
     
<input type="reset" name="Reset" value="重置"><br>
</div>
</form>
<!-- javaScript 函数 validateLogin(),用来验证用户名和密码是否为空 -->
<script language="javaScript">
function validateLogin()
{
var sUserName = document.frmLogin.txtUserName.value;
var sPassword = document.frmLogin.txtPassword.value;
if( sUserName=="" )
{
alert("请输入用户名!");
return false;
}
if( sPassword=="" )
{
alert("请输入密码!");
return false;
}
}
</script>
</body>
</html>

LoginServlet.java

/**
* 该JSP程序是用来测试与MySQL数据库的连接,
* 需要一个数据库:LearnJSP,和其中一个表:userinfo
* 表中有两个字段分别为:UserName varchar (20) not null,UserPwd varchar (20) not null
*/
package zieckey.login.servlet;
import java.sql.Statement;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet implements Servlet
{
public LoginServlet ()
{
// TODO Auto-generated constructor stub

}
/*
* (non-Javadoc)
*
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override

protected void doGet ( HttpServletRequest arg0, HttpServletResponse arg1 )
throws ServletException, IOException
{

}
/*
* (non-Javadoc)
*
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost ( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{
response.setContentType ( "text/html;charset=GB2312" );
String result = "";
// 获取用户名

String sUserName = request.getParameter ( "txtUserName" );
if ( sUserName == "" || sUserName == null || sUserName.length ( ) > 20 )
{
try
{
result = "请输入用户名(不超过20字符)!";
request.setAttribute ( "ErrorUserName", result );
response.sendRedirect ( "login.jsp" );
} catch ( Exception e )
{
}
}
// 获取密码

String sPasswd = request.getParameter ( "txtPassword" );
if ( sPasswd == "" || sPasswd == null || sPasswd.length ( ) > 20 )
{
try
{
result = "请输入密码(不超过20字符)!";
request.setAttribute ( "ErrorPassword", result );
response.sendRedirect ( "login.jsp" );
} catch ( Exception e )
{
}
}
// 登记JDBC驱动程序

try
{
Class.forName ( "org.gjt.mm.mysql.Driver" ).newInstance ( );
} catch ( InstantiationException e )
{
// TODO Auto-generated catch block

e.printStackTrace ( );
System.out.println ("InstantiationException");
} catch ( IllegalAccessException e )
{
// TODO Auto-generated catch block

e.printStackTrace ( );
System.out.println ("IllegalAccessException");
} catch ( ClassNotFoundException e )
{
// TODO Auto-generated catch block

e.printStackTrace ( );
System.out.println ("ClassNotFoundException");
}
// 连接参数与Access不同
String url = "jdbc:mysql://localhost:3306/LearnJSP";
// 建立连接

java.sql.Connection connection = null;
Statement stmt = null;
ResultSet rs = null;
try
{
connection = DriverManager.getConnection ( url, "root", "root" );
stmt = connection.createStatement ( );
// SQL语句
String sql = "select * from userinfo where username='" + sUserName
+ "' and userpwd = '" + sPasswd + "'";
rs = stmt.executeQuery ( sql );// 返回查询结果

} catch ( SQLException e )
{
// TODO Auto-generated catch block

e.printStackTrace ( );
}
try
{
if ( rs.next ( ) )// 如果记录集非空,表明有匹配的用户名和密码,登陆成功

{
// 登录成功后将sUserName设置为session变量的UserName

// 这样在后面就可以通过 session.getAttribute("UserName") 来获取用户名,

// 同时这样还可以作为用户登录与否的判断依据

request.getSession ( ).setAttribute ( "UserName", sUserName );
response.sendRedirect ( "login_success.jsp" );
} else
{
// 否则登录失败

//response.sendRedirect ( "MyJsp.jsp" );

request.getSession ( ).setAttribute ( "UserName", sUserName );
response.sendRedirect ( "login_failure.jsp" );

}
} catch ( SQLException e )
{
// TODO Auto-generated catch block

e.printStackTrace ( );
}
try
{
if ( null!=rs )
{
rs.close ( );
}
if ( null!=stmt )
{
stmt.close ( );
}
if ( null!=connection )
{
connection.close ( );
}
} catch ( SQLException e )
{
// TODO Auto-generated catch block

e.printStackTrace ( );
}
}
/**
*
*/
private static final long serialVersionUID = 1L;
}

login_failure.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'login_failure.jsp' starting page</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<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 bgcolor=cyan>
<%
String userName = (String)session.getAttribute ( "UserName" );
%>
<div align=center>
<%=userName%>
对不起,登录失败!
</div>
</body>
</html>

login_success.jsp

<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'login_failure.jsp' starting page</title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<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 bgcolor=cyan>
<%
String userName = (String)session.getAttribute ( "UserName" );
%>
<div align=center>
<%=userName%>
欢迎您,登录成功!
</div>
</body>
</html>

然后这是数据库中的截图:

如果你在登录页面查英文的用户名,它会顺利显示成功页面,如下图:


?????????????但问题是:如果你在登录界面输入中文用户名,他就会显示以下页面:

...全文
358 22 打赏 收藏 转发到动态 举报
写回复
用AI写文章
22 条回复
切换为时间正序
请发表友善的回复…
发表回复
q917769032 2012-11-24
  • 打赏
  • 举报
回复
回过头来看看,大家说的都有道理,说的都对。再次感谢大家
  • 打赏
  • 举报
回复
保持数据在传送过程中编码格式一致就不会出现格式乱码问题。 统一使用utf-8格式吧,关键的问题要与数据库的编码格式保持一致。
q917769032 2012-08-20
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 的回复:]

页面默认是使用get方法发送的,如果是get方法的话,建议在tomcat的安装目录下conf文件夹中的server.xml中的 <Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="U……
[/Quote]
这个也试过,还是不行

虽然还没有解决,但还是谢谢大家了
q917769032 2012-08-20
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

试试:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
......
……
[/Quote]
我最初也是这么想的,但是你改变了doGet()少了arg0 和arg1这个程序按“提交查询”之后根本没法运行。
无情天下 2012-08-20
  • 打赏
  • 举报
回复
直接在百度搜索一个处理中文乱码的类就可以了,我现在无法上传资料,我有,如果有意向请联系:QQ137688026,说是csdn的
hanhan313 2012-08-20
  • 打赏
  • 举报
回复
页面默认是使用get方法发送的,如果是get方法的话,建议在tomcat的安装目录下conf文件夹中的server.xml中的 <Connector port="8081" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="UTF-8" /> 后面加一个URIEnconding的编码,我这里设置的是"utf-8",我建议以后使用utf-8因为它的使用范围比gbk更广
如果是post方法发送的话,就像楼上有过提到的直接设置request.setCharacterEncoding("gb2312");
就可以了,我前段时间久刚好也到了java mysql的问题,现在解决了,就是我上面说的方法,希望能能帮上忙,最后还是建议你去看一篇文章,这里详细讲解了各种编码的问题http://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/
liangjw1018 2012-08-20
  • 打赏
  • 举报
回复
可以加个过滤器 过滤编码
丶顛簸人生 2012-08-20
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
做了一个登录界面以下是代码:
login.jsp

HTML code

<%@ page contentType="text/html; charset=gb2312"%>
<%
request.setCharacterEncoding("gb2312");
%>
<!-- 该Login页面是一个简单的登录界面 -->
<!--
该JSP程序是用来测试与MySQL数据库的……
[/Quote]

以上方法可以解决乱码问题!祝你好运
streamcc 2012-08-20
  • 打赏
  • 举报
回复
试试:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
......
response.setContentType("text/html;charset=gb2312");
response.sendRedirect ( "login_success.jsp" );
}
YAVA_2009 2012-08-20
  • 打赏
  • 举报
回复
可以在你的loginservlet.java中加入request.setCharacterEncoding("gb2312");
或者:
String sUserName = new String(request.getParameter("txtUserName").getBytes("ISO-8859-1"),"gb2312");
具体可参考:
http://blog.csdn.net/southcamel/article/details/7703317
q917769032 2012-08-20
  • 打赏
  • 举报
回复
[Quote=引用 16 楼 的回复:]
楼主不妨使用javascript或jquery 在前台把简单的是否为空判断好了、在把传递的数据跟数据库里的资料比对、
你servlet的功能有点超出了他本身所负责的区域、

可以尝试着分离代码层、代码全部都写到了servlet里不好维护、
从实体domain、 数据库访问对象DAO、 服务service 、跳转分发servlet、在到视图jsp

还有一点 楼主记得下次写 连……
[/Quote]
新手,多谢前辈指教,帮大忙了!
q917769032 2012-08-20
  • 打赏
  • 举报
回复
[Quote=引用 19 楼 的回复:]

楼主用的是哪个方法???
[/Quote]
用15楼前辈的方法,一次性改到位!
leenleebei 2012-08-20
  • 打赏
  • 举报
回复
楼主用的是哪个方法???
q917769032 2012-08-20
  • 打赏
  • 举报
回复
[Quote=引用 15 楼 的回复:]

Java code
@Override

protected void doGet ( HttpServletRequest arg0, HttpServletResponse arg1 )
throws ServletException, IOException
{
this.doPost(arg0,arg1 );
}
/*
* (non-Javadoc)
……
[/Quote]
前辈,感动两眼泪哗哗的!谢谢前辈,那个“张三”终于出来了!
wwwww112233 2012-08-20
  • 打赏
  • 举报
回复
过滤器好使么
  • 打赏
  • 举报
回复

楼主不妨使用javascript或jquery 在前台把简单的是否为空判断好了、在把传递的数据跟数据库里的资料比对、
你servlet的功能有点超出了他本身所负责的区域、

可以尝试着分离代码层、代码全部都写到了servlet里不好维护、
从实体domain、 数据库访问对象DAO、 服务service 、跳转分发servlet、在到视图jsp

还有一点 楼主记得下次写 连接数据库 记得把那些关闭资源 写到 finnally{}块 里、
  • 打赏
  • 举报
回复
 @Override

protected void doGet ( HttpServletRequest arg0, HttpServletResponse arg1 )
throws ServletException, IOException
{
this.doPost(arg0,arg1 );
}
/*
* (non-Javadoc)
*
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost ( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException
{//把这倆个写在该方法的最上
request.setCharacterEncoding("gb2312");
response.setCharacterEncoding("gb2312");


response.setContentType ( "text/html;charset=GB2312" );

//your code...end

}




楼主照5楼那样设置tomcat 的服务器编码集
<!-- 因为楼主的编码集是gb2312  所以你也要统一编码集  -->
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="gb2312"
useBodyEncodingForURI="true"
/>



最好设置一个拦截器 filter、转码 、具体百度之、记得要放行 、
pe23ter 2012-08-20
  • 打赏
  • 举报
回复
把my.ini文件设置default-character-set=utf8
kuailexiaobuding4 2012-08-20
  • 打赏
  • 举报
回复
发送和接收保持一致。接受可以转码。发送可以进行过滤器拦截或者固定编码格式。。另外用户名一般不使用中文。
streamcc 2012-08-20
  • 打赏
  • 举报
回复

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
......
response.setContentType("text/html;charset=gb2312");
response.sendRedirect ( "login_success.jsp" );
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}


这样也不行?
加载更多回复(2)

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧