使用jsp+jdbc完成一个用户登陆程序,登录成功后可以使用session进行用户的登录验证,用户根据需要也可以直接进行系统的退出操作。本程序在mysql数据库里建立了一个member表。
mid varchar pk,
password varchar,
name varchar.
login.jsp:
<%@page contentType="text/html; charset=utf-8"%>
<html>
<head><title>登录页面</title></head>
<body>
<center>
<%=request.getAttribute("info")!=null?request.getAttribute("info"):"" %>
<h1>登陆页面</h1>
<form action="check.jsp" method="post">
用户名:<input type="text" name="mid"><br>
密 码:<input type="password" name="password"><br>
<input type = "submit" value="登录">
<input type = "reset" value="重置">
</form>
</center>
</body>
</html>
check.jsp:
<%@page contentType="text/html; charset=utf-8" %>
<%@page import="java.sql.*" %>
<html>
<head><title>验证页面</title></head>
<body>
<%!
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
public static final String DBURL = "jdbc:mysql://localhost:3306/mysql";
public static final String DBUSER = "root";
public static final String DBPASS = "123456";
%>
<%
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
boolean flag = false;
String name = null;
%>
<%
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String mid = request.getParameter("mid");
String password = request.getParameter("password");
String sql = "select name from member where mid=? and password=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, request.getParameter("mid"));
pstmt.setString(2, request.getParameter("password"));
rs = pstmt.executeQuery();
if(rs.next()){
session.setAttribute("id", mid);
flag = true;
}
rs.close();
pstmt.close();
conn.close();
%>
<%
if(flag){
%>
<jsp:forward page="welcome.jsp"/>
<%
}else{
request.setAttribute("info", "错误的用户名或密码");
%>
<jsp:forward page="login_failure.jsp"/>
<%
}
%>
</body>
</html>
welcome.jp:
<%@page contentType="text/html; charset=utf-8"%>
<html>
<head><title>welcome</title></head>
<body>
<center>
<h1>登陆程序</h1>
<%
if(session.getAttribute("id")!=null){
%>
<h2>欢迎<font color="RED"><%=session.getAttribute("id") %></font>光临!</h2>
<h3><a href="logout.jsp">登陆注销</a></h3>
<%
}else{
request.setAttribute("info","请先登陆!");
%>
<jsp:forward page="login.jsp"/>
<%
}
%>
</center>
</body>
</html>
logout.jsp:
<%@page contentType="text/html; charset=utf-8"%>
<html>
<head><tile>logout</head>
<body>
<center>
<%
response.setHeader("refresh", "2;URL=login.jsp");
session.invalidate();//让session失效
%>
<h3>您已经成功退出本系统,两秒后跳转回首页!</h3>
<h3>如果没有跳转,请按<a href="login.jsp">这里</a></h3>
<center/>
</body>
</html>