两个页面login2.jsp 和 check2.jsp
数据表里存放用户名和密码,在login2.jsp页面上输入用户名密码登录,如果成功,显示“登录成功”,如果失败,显示“登录失败”。
核心:将JAVA中的JDBC代码,复制到JSP中的<% ... %>
注意事项:需要将MySQL jar包导入到WEB-INF下的lib目录下
login2.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录界面</title>
</head>
<body>
<form action="check2.jsp" method="post">
用户名:<input type="text" name="uname" /> <br/>
密码:<input type="password" name="upwd" /><br/>
<input type="submit" value="登录"/><br/>
</form>
</body>
</html>
check2.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>检验界面</title>
</head>
<body>
<%
String URL="jdbc:mysql://localhost:3306/lds?serverTimezone=UTC";
String USERNAME="root";
String PWD="prolific";
Connection connection = null;
PreparedStatement pstmt =null;
ResultSet rs=null;
try {
// a.导入驱动,加载具体的驱动类
Class.forName("com.mysql.cj.jdbc.Driver");//加载具体的驱动类
// b.与数据库建立连接
connection = DriverManager.getConnection(URL,USERNAME,PWD);
//c.发送sql,执行(增、删、改、查)
String sql="select count(*)from login where uname=? and upwd=?";
pstmt=connection.prepareStatement(sql);
String name=request.getParameter("uname");
String pwd=request.getParameter("upwd");
pstmt.setString(1,name);
pstmt.setString(2,pwd);
//String sql="select count(*)from login where uname='"+name+"' and upwd='"+pwd+"'";
rs=pstmt.executeQuery();
int count =-1;
if(rs.next()) {
count=rs.getInt(1);
}
if (count>0) {
out.println("登录成功!");
}
else {
out.println("登录失败!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
if(rs!=null) rs.close();
if (pstmt!=null) pstmt.close(); //对象.方法
if (connection!=null) connection.close();
}catch(SQLException e) {
e.printStackTrace();
}
}
%>
</body>
</html>