使用Thymeleaf时,Spring security sessionscope似乎为null

时间:2012-12-26 14:41:23

标签: java spring jsp spring-security thymeleaf

当使用spring security登录失败时,它会抛出异常,并在我的JSP中显示它:

<c:if test="${not empty error}">
    <div class="errorblock">
        Your login attempt was not successful, try again.<br /> Caused :
        ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
    </div>
</c:if>

现在我正在从JSP更改为Thymeleaf并尝试做同样的事情,但是当登录失败时,sessionScope变量似乎为空。

<div th:if="${error}" class="errorblock" th:text="'testing ' + ${sessionScope}">

</div>

打印出testing null。当我将视图解析器更改回JSP时,它可以很好地工作。我想我做错了什么。有什么建议吗?

3 个答案:

答案 0 :(得分:17)

在Thymeleaf中,您不使用sessionScope令牌名称访问会话变量。您改用session。所以你需要做一些事情:

<div class="error" 
     th:if="${param.login_error}"
     th:with="errorMsg=${session["SPRING_SECURITY_LAST_EXCEPTION"].message}">
  Your login attempt was not successful, try again.<br />
  Reason: <span th:text="${errorMsg}">Wrong input!</span> 
</div>

免责声明,根据StackOverflow规则:我是Thymeleaf的作者。

答案 1 :(得分:4)

第二个与第一个不同。如果你在没有变量名的情况下调用隐式EL变量sessionScope,我不确定你应该得到什么。怎么样:

${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}

此外,您确定您的页面加入了会话吗?在JSP中,session指令控制会话范围是否可通过EL获得。

<%@ page session="false|true" %>

答案 2 :(得分:0)

以下适用于Thymeleaf 3.0和Bootstrap 4.1

<div th:if="${param.error} and ${session}" th:with="errorMsg=${session['SPRING_SECURITY_LAST_EXCEPTION']}">
     <div class="alert alert-dismissible alert-danger error">
          Reason: <span th:text="${errorMsg}">Demo Invalid input</span>
     </div>
</div>
相关问题