在Thymeleaf中关于使用#httpSession出现的异常:Exception evaluating SpringEL expression

页面出错位置是这部分,注意页面中使用的${#httpSession.getAttribute('user')}

<div th:if="${#httpSession.getAttribute('user')} == null">
            
            <div class="register">
                <h3>收益率h3>
                <h4><span id="avg" th:text="${historyAvgRate}">13.8span> %h4>
                <div class="bn_register"><a th:href="@{/loan/toRegister}" class="btn-1">注册领999红包a>div>
                <div class="login">有账号? <a th:href="@{/loan/page/login}">立即登录a>div>
            div>
        div>
        <div th:if="${#httpSession.getAttribute('user')} ne null">
            <div class="register welcome">
                <div class="welcome-txt">欢迎 <span><b th:text="${#httpSession.getAttribute('user').phone}">张三b>span><br/>来投资!div>
                <div class="bn_register"><a th:href="@{/loan/myCenter}" class="btn-1">进入我的小金库a>div>
            div>
        div>

从异常信息中也看出${#httpSession.getAttribute(‘user’)}有问题。

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Dec 27 17:11:17 CST 2019
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/index.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/index.html]")
	at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241)
...

Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "#httpSession.getAttribute('user').phone" (template: "index" - line 47, col 55)
	at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
...

Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#httpSession.getAttribute('user').phone" (template: "index" - line 47, col 55)
	at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:290)
	at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
...

Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method getAttribute(java.lang.String) on null context object
	at org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:154)

我了解的是在Thymeleaf中如果获取session中的对象需要使用#session,它相当于 HttpSession 对象,这是 3.x 版本,若是 2.x 版本使用 #httpSession
结果发现不管使用#session还是#httpSession都会报上面的错误

解决方法:
#session或者#httpSession改成session,取值方式改成${session.user}${session.user.phone}问题就解决了

为什么用#session或者#httpSession不可以,但是session就可以呢?
求路过的大佬指导一下。。。

你可能感兴趣的:(exception)