在Spring Boot中使用Thymeleaf显示当前登录的用户,可以按照以下步骤进行:
以下是一个简单的示例:
Step 1: 添加依赖
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Step 2: 配置文件(application.properties)
spring.security.user.name=admin
spring.security.user.password=admin
spring.security.user.roles=ADMIN
Step 3: 创建UserDetailsService实现类
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 根据用户名查询用户信息
// 可以从数据库中获取用户信息
// 返回一个实现了UserDetails接口的自定义UserDetails对象
}
}
Step 4: 创建UserDetails实现类
public class UserDetailsImpl implements UserDetails {
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
// 构造方法
// 实现UserDetails接口的所有方法
}
Step 5: 配置类(SecurityConfig)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().permitAll();
}
}
Step 6: 创建Controller类
@Controller
public class UserController {
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/profile")
public String profile(@AuthenticationPrincipal UserDetailsImpl userDetails, Model model) {
model.addAttribute("username", userDetails.getUsername());
model.addAttribute("roles", userDetails.getAuthorities());
return "profile";
}
}
Step 7: Thymeleaf模板(login.html)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="/login" method="post">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div>
<button type="submit">Login</button>
</div>
</form>
</body>
</html>
Step 8: Thymeleaf模板(profile.html)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Profile</title>
</head>
<body>
<h1>Welcome, <span th:text="${username}"></span>!</h1>
<h2>Your roles:</h2>
<ul>
<li th:each="role : ${roles}" th:text="${role}"></li>
</ul>
</body>
</html>
请注意,以上示例中的代码仅供参考,具体实现可能需要根据您的实际需求进行调整。同时,推荐的腾讯云产品链接地址如下:
请注意,以上仅为示例,并非实际的腾讯云产品推荐,具体产品选择应根据实际需求进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云