一个用户登录页面的结构
在数据库中下建立登录表:
/*=============删除数据库=============*/
DROP DATABASE IF EXISTS usr;
/*=============创建数据库=============*/
CREATE DATABASE usr;
/*=============使用数据库=============*/
USE usr;
/*=============删除数据库表===========*/
DROP TABLE IF EXISTS login;
/*=============创建数据库表===========*/
CREATE TABLE login(
userid VARCHAR(30) PRIMARY KEY,
name VARCHAR(30) NOT NULL,
password VARCHAR(32) NOT NULL
);
INSERT INTO login(userid, name, password)VALUES('admin', 'admin', 'admin');
用login.html写出登录页面表单:
<html>
<head>
<title>www.thystar.com</title>
</head>
<body>
<center>
<h1>登陆操作</h1>
<hr>
<form action = "login_check.jsp" method = "post">
<table border = "1">
<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>www.thystar.com</title>
</head>
<body>
<%!
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
public static final String DBURL = "jdbc:mysql://localhost:3306/usr";
public static final String DBUSER = "root";
public static final String DBPASS = "mysqladmin";
%>
<%
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 login WHERE userid = ? 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){
System.out.println(e);
}
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.html"/>
<%
}
%>
</body>
</html>
登录成功页:login_success.jsp
<%@ page contentType = "text/html" pageEncoding = "GBK"%>
<html>
<head>
<title>www.thystar.com</title>
</head>
<body>
<center>
<h2>登陆成功</h2>
<h2>欢迎<font color = "red"><%=request.getParameter("uname")%></font></h2>
</center>
</body>
</html>
登陆失败页:login_failure.html
<html>
<head>
<title>www.thystar.com</title>
</head>
<body>
<center>
<h2>登陆失败</h2>
</center>
</body>
</html>
结果:
《Java Web开发实战经典--基础篇》