- 基本语法:<%@page%> <%@include%> <jsp:include> <jsp:forward>
- 而且既然现在的JSP可以进行数据库连接操作了,那么就具备了动态Web开发的能力。
login.jsp
<%@page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>songjs</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 colspan="2">登陆ID :</td>
<td><input type="text" name="id"/></td>
</tr>
<tr>
<td colspan="2">登陆密码 :</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>songjs</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/mldn" ;
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 user 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){
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>songjs</title></head>
<body>
<center>
<h1>登陆操作</h1><hr>
<h2>登陆成功</h2>
<h2>欢迎 <%=request.getParameter("uname")%> 光临!</h2>
</center>
</body>
</html>
login_failure.jap
<%@ page contentType="text/html" pageEncoding="GBK"%>
<html>
<head><title>songjs</title></head>
<body>
<center>
<h1>登陆操作</h1>
<hr>
<h2>用户名或密码错误!登陆失败!</h2>
<h2>请重新<a href="login.jsp">登陆</a></h2>
</center>
</body>
</html>