用idea代码写出:添加必要的验证,用户名或密码没输入则跳转login_info_error.html,创建File对象使用该用户名.obj作为文件名定位users目录下对应文件,如果该文件存在则说明用户存在,需要反序列化读取文件中的User对象,该对象记录着该用户曾经的注册信息,此时读取后比较密码,密码一致,则登录成功,跳转:login_success.html,密码不一致,则登录失败,跳转:login_fail.html,如果该文件不存在说明没有这个注册用户,这属于登录失败,跳转:login_fail.html
时间: 2024-02-09 20:08:12 浏览: 23
好的,下面是用idea实现用户登录功能的Java代码:
```java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null || username.trim().isEmpty() || password == null || password.trim().isEmpty()) {
response.sendRedirect("login_info_error.html");
return;
}
File file = new File(getServletContext().getRealPath("/users"), username + ".obj");
if (!file.exists()) {
response.sendRedirect("login_fail.html");
return;
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
User user = (User) ois.readObject();
if (!user.getPassword().equals(password)) {
response.sendRedirect("login_fail.html");
return;
}
request.getSession().setAttribute("user", user);
response.sendRedirect("login_success.html");
} catch (ClassNotFoundException e) {
e.printStackTrace();
response.sendRedirect("login_fail.html");
}
}
}
```
代码解析:
1. 首先获取用户提交的用户名和密码,如果有任何一个为空,则重定向到登录信息错误页面(login_info_error.html)。
2. 创建File对象,使用用户名作为文件名定位到users目录下对应的文件。
3. 如果该文件不存在,则重定向到登录失败页面(login_fail.html)。
4. 如果该文件存在,则使用ObjectInputStream反序列化读取文件中的User对象,该对象记录着该用户曾经的注册信息。
5. 比较读取到的User对象的密码与用户提交的密码是否一致,如果不一致,则重定向到登录失败页面(login_fail.html)。
6. 如果密码一致,则将User对象存入Session中,重定向到登录成功页面(login_success.html)。
7. 如果反序列化过程中出现ClassNotFoundException异常,则重定向到登录失败页面(login_fail.html)。
以上就是添加必要的验证,实现用户登录功能的Java代码。