数据库:
DROP TABLE IF EXISTS t_user;
CREATE TABLE t_user(
id INT(10),
username VARCHAR(32) NOT NULL,
PASSWORD VARCHAR(32) NOT NULL);
INSERT INTO t_user(id,username,PASSWORD) VALUES(1,'admin','123');
INSERT INTO t_user(id,username,PASSWORD) VALUES(2,'zhangsan','123');
COMMIT;
SELECT * FROM t_user;
login.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/29/LoginServlet" method="post">
username <input type="text" name="username"><br>
password <input type="password" name="password"><br>
<input type="submit" value="login">
</form>
</body>
</html>
LoginServlet文件:
package Login;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置字符编码方式
request.setCharacterEncoding("UTF-8");
//获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//链接数据库验证用户名和密码
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs= null;
boolean loginSuccess=false;
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost:3366/db1","root","123");
conn.setAutoCommit(false);
String sql ="select * from t_user where username=? and password=?";
ps=conn.prepareStatement(sql);
ps.setString(1,username);
ps.setString(2,password);
rs = ps.executeQuery();
if(rs.next()){
loginSuccess=true;
}
conn.commit();
} catch (ClassNotFoundException | SQLException e) {
if(conn!=null){
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
}finally {
if(rs!=null){
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//登录成功调整需到登录页面,失败跳转到失败页面
if(loginSuccess){
response.sendRedirect(request.getContextPath()+"/welcome.html");
}else{
response.sendRedirect(request.getContextPath()+"/fail.html");
}
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
welcome.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
welcome
</body>
</html>
fail.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
登录失败,请重新 <a href="/29/login.html">登录</a>
</body>
</html>