在thymeleaf模板中调用Web上下文对象的方法的问题

时间:2017-02-10 19:57:05

标签: java spring spring-boot thymeleaf

我正在尝试在mymeleaf 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>

这是一个例子,但在我尝试这样做的任何地方,我都会遇到这些错误。有没有我遗失的作品?

3 个答案:

答案 0 :(得分:4)

原来#request需要是#httpServletRequest

答案 1 :(得分:0)

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

另外,只需对您的编码风格进行一些评论,您可以格式化:

<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')}" />

答案 2 :(得分:0)

我认为如果单独使用该模型就可以了。所以你的方法看起来像这样:

@Controller
public class Controller {

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