再纯净的白开水也过滤不了渣茶。
Servlet登陆页面
引入数据库,创建用户表,包括用户名和密码:客户端通过login.jsp发出登录请求,请求提交到loginServlet处理。如果用户名和密码跟用户表匹配则视为登录成功,跳转到loginSuccess.jsp页面,显示“欢迎你”跟用户名;否则跳转到loginFail.jsp页面,显示“登录失败”,通过超链接返回login.jsp。
旧题重拾,不过是多了个连接数据库,修改一下servlet即可。
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 javax.servlet.RequestDispatcher;
import java.io.IOException;
import java.sql.*;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
// 数据库连接信息
private static final String url = "jdbc:mysql://localhost:3306/dbjsp?serverTimezone=UTC";
private static final String user = "root";
private static final String psd = "123456";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置响应的内容类型及字符编码
response.setContentType("text/html;charset=utf-8");
// 获取提交的用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 检查用户名和密码是否在数据库中匹配
if (checkLogin(username, password)) {
// 登录成功,重定向到登录成功页面
RequestDispatcher dispatcher = request.getRequestDispatcher("loginSuccess.jsp?username=" + username);
dispatcher.forward(request, response);
} else {
// 登录失败,重定向到登录失败页面
RequestDispatcher dispatcher = request.getRequestDispatcher("loginFail.jsp");
dispatcher.forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// POST请求时直接调用doGet方法处理
doGet(request, response);
}
// 验证登录方法
private boolean checkLogin(String username, String password) {
boolean b = false;
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection(url, user, psd);
// 查询用户
String sql = "SELECT * FROM student2 WHERE id = ? AND psd = ?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
rs = stmt.executeQuery();
// 如果有匹配的记录,则登录验证成功
if (rs.next()) {
b = true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return b;
}
}
Servlet过滤器
编写过滤器实现用户登录身份验证,防止未经登录用户越权访问页面。
登录页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="LoginServlet2" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
主页
<%@ page import="Servlet.User" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h2>欢迎来到网站!</h2>
<%
User user = (User) session.getAttribute("user");
String username = user.getUsername();
%>
<p>您已登录: <%= username %></p>
</body>
</html>
User用户实体类
package Servlet;
public class User {
private String username;
private String password;
// public User(String username, String password) {
// this.username = username;
// this.password = password;
// }
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Servlet类
import java.io.IOException;
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 Servlet.User;
@WebServlet("/LoginServlet2")
public class LoginServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if ("gdpu".equals(username) && "123".equals(password)) {
User user = new User();
user.setUsername(username);
user.setPassword(password);
request.getSession().setAttribute("user", user);
// response.sendRedirect("index1.jsp");
request.getRequestDispatcher("index1.jsp").forward(request, response);
} else {
response.sendRedirect("login1.jsp");
}
}
}
过滤器
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebFilter("/*")
public class loginfilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
// 过滤器初始化
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String path = request.getRequestURI().substring(request.getContextPath().length());
HttpSession session = request.getSession(false);
// 如果请求的是登录页面或者正在进行登录操作,则允许访问
if (path.equals("/login1.jsp") || path.equals("/LoginServlet2")) {
filterChain.doFilter(request, response);
return;
}
// 检查用户是否已经登录
if (session == null || session.getAttribute("username") == null) {
// 用户未登录,重定向到登录页面
response.sendRedirect(request.getContextPath() + "/login1.jsp");
}
else {
// 用户已登录,允许访问其他页面
filterChain.doFilter(request, response);
}
}
public void destroy() {
// 过滤器销毁
}
}
实验心得
滤到点设计思路就好了。