【问题标题】:Issues calling methods on web context objects in thymeleaf template在 thymeleaf 模板中调用 Web 上下文对象的方法的问题
【发布时间】:2017-06-29 06:59:41
【问题描述】:

我正在尝试在 thymeleaf 3.0.3 和 Spring Boot 1.5.1 的模板中调用 Web 上下文对象的方法,例如 #request 和 #response。

我不断收到这样的错误:

org.springframework.expression.spel.SpelEvaluationException: EL1011E: 方法调用:试图在空上下文对象上调用方法方法(java.lang.String)

这是一个控制器:

@Controller
public class Controller {

@RequestMapping(method = RequestMethod.GET, value = "/endpoint", produces = "text/html")
public String customerServiceSignin(Model uiModel, HttpServletRequest request) {
    uiModel.addAttribute("attr1", true); // show proper header
    uiModel.addAttribute("attr2", false);
    return "template";
}

还有一个模板:

<html xmlns:th="http://www.thymeleaf.org">
<div>
<div style="...">

    <div class="errorblock" th:unless="${#strings.isEmpty(#request.getAttribute('some_attr'))}" th:utext="${#request.getAttribute('some_other_attr')}"></div>

    <form name='f' action="action" method='POST'>
        <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='username' value="" />
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='password' />
                </td>
            </tr>
            <tr>
                <td><input name="submit" type="submit" value="submit" />
                </td>
                <td><input name="reset" type="reset" />
                </td>
            </tr>
        </table>
    </form>
</div>
</div>
</html>

这是一个示例,但在我尝试这样做的任何地方都会遇到这些错误。有没有我遗漏的部分?

【问题讨论】:

    标签: java spring spring-boot thymeleaf


    【解决方案1】:

    我认为这里的问题是您应该使用#strings 而不是#string#request 部分看起来不错。

    另外,你的编码风格只是一些 cmets,你可以格式化:

    <th:block th:if="${not #string.isEmpty(#request.getAttribute('some_attr'))}">
        <div class="errorblock" th:utext="${#request.getAttribute('some_other_attr')}"></div>
    </th:block>
    

    简单地说

    <div th:unless="${#strings.isEmpty(#request.getAttribute('some_attr'))}" class="errorblock" th:utext="${#request.getAttribute('some_other_attr')}" />
    

    【讨论】:

    • 感谢您的风格提示。不幸的是,我仍然遇到同样的错误,并且很确定这是由于#request 和其他 Web 上下文对象的一些问题。这发生在我使用 Web 上下文对象的任何模板上,即使是我不使用 #strings 的模板。
    • 嗯...好吧,我不知道从这里去哪里。我重新创建了您上面的相同代码,并且使用#strings 或#request / #response 没有任何问题。 (Thymeleaf 3,弹簧靴 1.4.2)
    【解决方案2】:

    原来#request 需要是#httpServletRequest

    【讨论】:

    • 没错,但为什么呢?该文档引用了#request 而不是#httpServletRequest。
    • 这取决于 thymeleaf 版本。在版本 2 中,它似乎是 #httpServletRequest: thymeleaf.org/doc/tutorials/2.1/… 和版本 3 #request: thymeleaf.org/doc/tutorials/3.0/… - 但是,您声称您已经使用 thymeleaf 3,所以我不确定这里的问题。也许您使用的版本比您想象的要旧?
    猜你喜欢
    • 2014-06-26
    • 2017-08-06
    • 1970-01-01
    • 2017-10-15
    • 2021-02-28
    • 2014-03-19
    • 2023-04-09
    • 2015-03-20
    • 2023-01-16
    相关资源
    最近更新 更多