我是Spring框架的初学者。我尝试登录和注销页面。下面的代码是使用Thymeleaf的Spring引导登录/注销文件。
首先,登录控制器代码
@Autowired
private HttpSession userSession;
@Autowired
private UserService userService;
@RequestMapping("/users/login")
public String login(LoginForm loginForm) {
return "users/login";
}
@RequestMapping(value="/users/login", method = RequestMethod.POST)
public String loginPage(@Valid LoginForm loginForm, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
userSession.setAttribute("blogLogin", false);
System.out.println("Wrong Input!!");
return "users/login";
}
if(!userService.authenticate(loginForm.getUsername(), loginForm.getPassword())) {
userSession.setAttribute("blogLogin", false);
System.out.println("login failed!!");
return "users/login";
}
userSession.setAttribute("blogLogin", true);
System.out.println("Login succesfully.");
return "redirect:/";
}
<header th:fragment="site-header" th:remove="tag">
<header>
<a href="index.html" th:href="@{/}">
<img src="../public/img/site-logo.png" th:src="@{/img/site-logo.png}" />
</a>
<a href="index.html" th:href="@{/}">Home</a>
<a href="users/login.html" th:href="@{/users/login}">Log in</a>
<a href="users/logout.html" th:href="@{/users/logout}">Log out</a>
<a href="users/register.html" th:href="@{/users/register}">Register</a>
<a href="users/index.html" th:href="@{/users}">Users</a>
<a href="posts/index.html" th:href="@{/posts}">Posts</a>
<a href="posts/create.html" th:href="@{/posts/create}">Write Post</a>
<div id="logged-in-info"><span>Hello, <b>(user)</b></span>
<form method="post" th:action="@{/users/logout}">
<input type="submit" value="Log out"/>
</form>
</div>
</header>
</header>
问题是我不知道如何使用thymeleaf的th:if语句生成登录/注销链接切换代码。如您所知,登录链接和注销链接不能同时显示。