连接mysql
<%!
//定义数据库驱动程序
//public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
//数据库连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/test";
public static final String DBUSER = "root";
public static final String DBPASS = "123";
%>
<%
Connection conn = null; //声明数据库连接对象
PreparedStatement pstmt = null; //声明数据库操作
ResultSet rs = null; //声明数据库结果集
boolean flag = false; //定义标志位
String name = null;
%>
<%
//JDBC操作会抛出异常,使用try...catch处理
try {
Class.forName(DBDRIVER); //加载驱动程序
conn = DriverManager.getConnection(DBURL, DBUSER, DBPASS); //取得数据库连接
//编写要使用的SQL语句,验证用户id和密码,如果正确,则取出真实姓名
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()) {//如果可以查询到,则表示合法用户
name = rs.getString(1);//取出真实姓名
flag = true;
}
} 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 value="<%=name%>" name="uname"/>
</jsp:forward>
<%
} else {
%>
<jsp:forward page="login_failure.html" />
<%
}
%>