代码之家  ›  专栏  ›  技术社区  ›  Joseph Hwang

如何使用Thymeleaf设置登录/注销链接可见/不可见?

  •  0
  • Joseph Hwang  · 技术社区  · 7 年前

    我是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语句生成登录/注销链接切换代码。如您所知,登录链接和注销链接不能同时显示。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alien    7 年前

    您可以像下面这样检查用户是经过身份验证的还是匿名的,并可以做出决定。

    <div sec:authorize="#{isAuthenticated()}">
      <a th:href="@{/logout}">Log out</a>
    </div>
    <div sec:authorize="#{isAnonymous()}">
      <a th:href="@{/login}">Log in</a>
    </div>