Spring Boot登录
要实现Spring Boot登录功能,你需要定义一个控制器来处理登录请求,并使用Spring Security来进行身份验证。以下是一个简单的例子:
- 添加Spring Security依赖到你的
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 创建一个简单的登录表单HTML页面(
login.html
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="/login" method="post">
<div>
<label>Username:</label>
<input type="text" name="username" />
</div>
<div>
<label>Password:</label>
<input type="password" name="password" />
</div>
<div>
<input type="submit" value="Login" />
</div>
</form>
</body>
</html>
- 创建一个控制器来处理登录请求(
LoginController.java
):
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
@Controller
public class LoginController {
@GetMapping("/login")
public String loginForm() {
return "login";
}
@PostMapping("/login")
public String loginAction(@RequestParam String username, @RequestParam String password) {
// 这里应该是身份验证逻辑,通常会使用UserDetailsService
// 为了示例,我们简单地检查用户名和密码
if ("user".equals(username) && "password".equals(password)) {
Authentication authentication = new UsernamePasswordAuthenticationToken(username, null, null);
SecurityContextHolder.getContext().setAuthentication(authentication);
return "welcome"; // 重定向到欢迎页面
} else {
return "loginError"; // 登录错误,返回错误页面
}
}
}
- 配置Spring Security(
SecurityConfig.java
):
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCon
评论已关闭