基于 Spring Boot 博客系统开发
在这个系列的最后一部分,我们将完成博客系统的最后一个功能——用户登录。
首先,我们需要在BlogController
中添加登录逻辑:
@Controller
public class BlogController {
// ... 其他代码
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password,
HttpSession session, RedirectAttributes redirectAttributes) {
boolean isLoginSuccess = userService.loginUser(username, password, session);
if (isLoginSuccess) {
return "redirect:/";
} else {
redirectAttributes.addFlashAttribute("error", "用户名和密码错误");
return "redirect:/login";
}
}
@GetMapping("/logout")
public String logout(HttpSession session) {
session.invalidate();
return "redirect:/";
}
}
在UserService
中添加登录方法:
@Service
public class UserService {
// ... 其他代码
public boolean loginUser(String username, String password, HttpSession session) {
User user = userRepository.findByUsername(username);
if (user != null && user.getPassword().equals(password)) {
session.setAttribute("currentUser", user);
return true;
}
return false;
}
}
在login.html
模板中添加登录表单:
<!-- login.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<!-- ... 其他代码 -->
</head>
<body>
<!-- ... 其他代码 -->
<div class="col-md-8">
<h3 class="my-3">登录</h3>
<form th:action="@{/login}" method="post">
<input type="text" class="form-control mb-2" placeholder="用户名" name="username" required>
<input type="password" class="form-control mb-2" placeholder="密码" name="password" required>
<button type="submit" class="btn btn-primary btn-block">登录</button>
<div class="alert alert-danger" th:if="${isNotEmpty(error)}" th:text="${error}" role="alert"></div>
</form>
</div>
</body>
</html>
在application.properties
中配置Spring Security:
spring.datasource.url=jdbc:mysql://localhost:3306/blog_example?useSSL=false
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.thymeleaf.ca
评论已关闭