帮我用SpringBoot写cookie与session登录界面
时间: 2024-05-05 07:15:37 浏览: 9
以下是使用SpringBoot实现cookie与session登录界面的示例代码:
1. 创建一个SpringBoot项目并添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
```
2. 创建一个登录页面
在src/main/resources/templates目录下创建一个login.html文件,代码如下:
```
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h2>Login</h2>
<form action="/login" method="post">
<p>
<label>Username:</label>
<input type="text" name="username"/>
</p>
<p>
<label>Password:</label>
<input type="password" name="password"/>
</p>
<p>
<input type="checkbox" name="remember-me"/>Remember me
</p>
<p>
<input type="submit" value="Login"/>
</p>
</form>
</body>
</html>
```
3. 创建一个控制器
创建一个LoginController类,并添加以下代码:
```
@Controller
public class LoginController {
@GetMapping("/login")
public String loginPage() {
return "login";
}
@PostMapping("/login")
public String login(HttpServletRequest request, HttpServletResponse response,
@RequestParam String username, @RequestParam String password,
@RequestParam(required = false) Boolean rememberMe) {
// TODO: 验证用户名和密码是否正确
// 如果rememberMe为true,则设置cookie,否则删除cookie
if (rememberMe != null && rememberMe) {
Cookie cookie = new Cookie("username", URLEncoder.encode(username, StandardCharsets.UTF_8));
cookie.setMaxAge(7 * 24 * 60 * 60); // 保存7天
response.addCookie(cookie);
} else {
Cookie cookie = new Cookie("username", null);
cookie.setMaxAge(0); // 删除cookie
response.addCookie(cookie);
}
// 设置session
request.getSession().setAttribute("username", username);
return "redirect:/home";
}
@GetMapping("/home")
public String homePage(HttpServletRequest request) {
// 如果session中没有username,则重定向到登录页面
if (request.getSession().getAttribute("username") == null) {
return "redirect:/login";
}
return "home";
}
}
```
4. 创建一个主页
在src/main/resources/templates目录下创建一个home.html文件,代码如下:
```
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<h2>Welcome, <span th:text="${session.username}"></span>!</h2>
</body>
</html>
```
5. 运行应用程序
运行应用程序,并在浏览器中访问http://localhost:8080/login,输入用户名和密码并勾选“Remember me”,然后单击“登录”按钮。如果用户名和密码正确,则将重定向到主页,并显示欢迎消息。如果关闭浏览器并重新打开该页面,则用户名应该仍然存在,因为我们已经设置了一个cookie。如果不勾选“Remember me”,则cookie将被删除。