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

Jaa*_*nus 3 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>
Run Code Online (Sandbox Code Playgroud)

现在我正在从JSP更改为Thymeleaf并尝试执行相同的操作,但是当登录失败时,sessionScope变量似乎为null.

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

</div>
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*dez 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>
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*tör 5

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

${sessionScope.SPRING_SECURITY_LAST_EXCEPTION.message}
Run Code Online (Sandbox Code Playgroud)

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

<%@ page session="false|true" %>
Run Code Online (Sandbox Code Playgroud)