1.1 创建数据库表
表名:user
字段:
userid 保存用户的登录id
name 用户名
password 密码
1.2 实现思路
a. 用户登录,则需要有个一个表单页,此页面可输入用户的登录id和密码;
b.提交到一个验证的jsp页面进行数据库的操作验证,如果可查询到用户信息,则为合法用户,则跳转至登录成功页;
c.如果未查询到,则用户不是合法用户,则跳转错误页进行提示;
1.3实现
login.jsp : 提供用户的登录表单,可输入登录id及密码;
<%@page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>登录页面</title></head>
<body>
<center>
<h1>登陆</h1>
<hr>
<form action="login_check.jsp" method="post">
<table>
<tr>
<td colspan="2">
用户登陆
</td>
</tr>
<tr>
<td>登陆ID:</td>
<td><input type="text" name="id"></td>
</tr>
<tr>
<td>登陆密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="登陆">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
login_check.jsp : 登录检查页,根部表单提交过来的信息进行验证,成功登录成功页,否则跳转到错误提示页面;
<%@page contentType="text/html" pageEncoding="GBK"%>
<%@page import="java.sql.*"%>
<html>
<head><title>验证页面</title></head>
<body>
<center>
<h1>登陆操作</h1>
<hr>
<% // 定义若干个数据库的连接常量
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ;
public static final String DBURL = "jdbc:mysql://localhost:3306/procs" ;
public static final String DBUSER = "root" ;
public static final String DBPASS = "root" ;
%>
<%
Connection conn = null ; // 数据库连接
PreparedStatement pstmt = null ; // 数据库预处理操作
ResultSet rs = null ; // 查询要处理结果集
boolean flag = false ; // 保存标记
String name = null ; // 保存真实姓名
%>
<%
try{
%>
<%
Class.forName(DBDRIVER) ;
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS) ;
String sql = "SELECT name FROM user WHERE id=? AND password=?" ;
pstmt = conn.prepareStatement(sql) ;
pstmt.setString(1,request.getParameter("id")) ;
pstmt.setString(2,request.getParameter("password")) ;
rs = pstmt.executeQuery() ; // 查询
if(rs.next()){ // 如果有数据,则可以执行
flag = true ; // 表示登陆成功
name = rs.getString(1) ;
}
%>
<%
}catch(Exception e) {
e.printStackTrace() ;
}
finally{
try{
rs.close() ;
pstmt.close() ;
conn.close() ;
} catch(Exception e){}
}
%>
<%
if(flag){ // 登陆成功
%>
<jsp:forward page="login_success.jsp">//登录成功页面
<jsp:param name="uname" value="<%=name%>"/>//获取参数值
</jsp:forward>
<%
} else { // 登陆失败
%>
<jsp:forward page="login_failure.jsp"/>
<%
}
%>
</center>
</body>
</html
login_success.jsp 登录成功页,显示欢迎信息;
<%@page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>验证成功</title></head>
<body>
<center>
<h1>登陆操作</h1>
<h2>登陆成功</h2>
<h2>欢迎<font color="red"><%=request.getParameter("uname")%></font>光临!</h2>
</center>
</body>
</html>
login_failure.jsp : 登录失败页,提示用户输入错误,并提供重新登录的超链接;
<%@page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>登录失败页面</title></head>
<body>
<center>
<h1>登陆操作</h1>
<h2>登陆失败,请重新<a href="login.jsp">登陆</a>!</h2>
</center>
</body>
</html>