今天终于写登陆验证那部分了,心情好激动,因为之前一直写页面,没敢尝试这个。今天写的时候好心塞,运行的时候一直提示密码错误后来查了资料才知道因为后台与前台的编码问题,因为后台传入的是中文字符的用户名,所以传过来的用户名一直为空,可以用下面的方法:
String userName = request.getParameter("userName");
byte b1[] = userName.getBytes("ISO-8859-1");
userName = new String(b1,"UTF-8");
String password = request.getParameter("password");
byte b2[] = password.getBytes("ISO-8859-1");
password = new String(b2,"UTF-8");
下面是完整的程序:
//login.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>登陆页面</title>
</head>
<body>
<br>
<br>
<br><br>
<form action="../login/loginCheck.jsp" method="post">
<table align="center" width="500">
<tr>
<td>用户名: </td>
<td><input type="text" name="userName"></td>
</tr>
<tr>
<td>密码: </td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="sure" value="登陆">
<input type="reset" name="clear" value="取消">
</td>
</tr>
</table>
</form>
</body>
</html>
//loginCheck.jsp //登陆验证的
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!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>登陆数据处理页面</title>
</head>
<body>
<%
String userName = request.getParameter("userName");
byte b1[] = userName.getBytes("ISO-8859-1"); /*处理中文乱码*/
userName = new String(b1,"UTF-8");
String password = request.getParameter("password");
byte b2[] = password.getBytes("ISO-8859-1");
password = new String(b2,"UTF-8");
Connection con = null;
PreparedStatement pstmt = null; //数据库预处理操作
ResultSet rs = null;
boolean flag = false;
if (userName != null && !userName.equals("")) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/xiaojing?useUnicode=true&characterEncoding=UTF-8";
con = DriverManager.getConnection(url, "root", "fxj4620");
//String sql = "select * from login where userName = '"+userName+"', password = '"+password +"'";
String sql = "select * from login where userName = ? and password = ?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, userName);
pstmt.setString(2, password);
rs = pstmt.executeQuery();
while (rs.next()) {
// response.sendRedirect("../main/main.jsp");
flag = true; //表示登陆成功
}
// System.out.print(userName+"ddd");
%>
<%
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
pstmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
%>
<%
if (flag == true) {
response.sendRedirect("../main/main.jsp");
} else {
out.println("用户名或密码输入错误!");
out.println("<a href=../login/login.jsp>返回</a>");
}
%>
<%
} else {
out.println("请先登录!");
%>
<br>
<a href="../login/login.jsp">返回</a>
<%
}
%>
</body>
</html>