我是Spring Framework的初学者。我尝试创建登录和注销百里叶页面。以下代码是带有Thymeleaf的Spring Boot登录/注销文件。
首先,登录控制器代码
@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:/";
}
和使用胸腺叶的layout.html代码。
<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>
问题是我不知道如何使用th:if语句使登录/注销链接切换代码。如您所知,登录链接和注销链接不能同时显示。
发布于 2018-09-29 20:23:32
您可以像下面这样检查用户是经过身份验证还是匿名的,并可以做出决定。
<div sec:authorize="#{isAuthenticated()}">
<a th:href="@{/logout}">Log out</a>
</div>
<div sec:authorize="#{isAnonymous()}">
<a th:href="@{/login}">Log in</a>
</div>
https://stackoverflow.com/questions/52567556
复制相似问题