用Java写一个cookie与session实现登录的代码
时间: 2024-05-08 14:20:22 浏览: 17
好的,以下是示例Java代码实现cookie与session实现登录的功能:
```
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO: 从请求对象中获取用户名和密码参数
String username = request.getParameter("username");
String password = request.getParameter("password");
// TODO: 校验用户名和密码是否正确
if ("user".equals(username) && "password".equals(password)) {
// 登录成功
HttpSession session = request.getSession(true); // 创建或者获取会话对象
session.setMaxInactiveInterval(60 * 60 * 2); // 设置会话有效期为2小时
session.setAttribute("username", username); // 在会话中存储用户信息
// 创建一个cookie存储sessionId, 并设置有效期为2小时
Cookie cookie = new Cookie("sessionId", session.getId());
cookie.setMaxAge(60 * 60 * 2);
response.addCookie(cookie);
// TODO: 登录成功后跳转到主页
response.sendRedirect("/index.jsp");
} else {
// 登录失败
response.getWriter().write("Username or password is incorrect!");
}
}
}
```
在以上代码中,我们通过HttpServletRequest对象从请求中获取用户名和密码参数,然后校验用户名和密码是否正确。如果正确,就创建一个新的HttpSession对象,并在其中存储用户信息,并将sessionId存储在Cookie中。之后,将sessionId返回给客户端,客户端会自动将其存储在浏览器中。登录成功之后会自动跳转到主页。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)