链接:https://pan.baidu.com/s/1mGIVpoagCt4qM97MhKQ3Sw 提取码:bh7q
首先你得有这个jdbc的jar包 才行
一、
JDBC API可做三件事:与数据库建立连接、执行SQL 语句、处理结果。
2、在WEB-INF里创建lib目录,添加数据库驱动jar包
作为库添加到项目:
其中处理部分的代码是核心的代码:
<%@ page import="java.sql.*" %>
<%@ page import="java.net.URLEncoder" %>
<%
// 设置请求对象字符编码
request.setCharacterEncoding("utf-8");
// 获取表单提交的数据
String username = request.getParameter("username");
String password = request.getParameter("password");
// 设置连接数据库的参数值
final String DRIVER = "com.mysql.jdbc.Driver";
final String URL = "jdbc:mysql://localhost:3306/hwdb";
final String USER = "root";
final String PASSWORD = "root";
try {
// 安装数据库驱动程序
Class.forName(DRIVER);
// 获取数据库连接
Connection conn = DriverManager.getConnection(URL + "?useUnicode=true&characterEncoding=utf8", USER, PASSWORD);
// 定义SQL字符串
String strSQL = "select * from t_user where username = ? and password = ?";
// 创建预备语句对象
PreparedStatement pstmt = conn.prepareStatement(strSQL);
// 设置占位符的值
pstmt.setString(1, username);
pstmt.setString(2, password);
// 执行SQL查询,返回结果集
ResultSet rs = pstmt.executeQuery();
// 判断结果集是否有记录
if (rs.next()) {
// 清除session里可能存在的属性值
if (session.getAttribute("errMsg") != null) {
session.removeAttribute("errMsg");
}
// 采用重定向,跳转到登录成功页面
response.sendRedirect("success.jsp?username=" + URLEncoder.encode(username, "utf-8"));
} else {
// 设置session属性值
session.setAttribute("errMsg", "用户名或密码错误,请重新登录");
// 采用重定向,跳转到登录页面
response.sendRedirect("login.jsp");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
%>