【问题标题】:How to find out which properties are callable for a template variable如何找出模板变量可调用的属性
【发布时间】:2019-01-03 23:54:17
【问题描述】:

我有以下控制器:

public class MyErrorController implements ErrorController {

  @RequestMapping("/error")
  public String handleError(HttpServletRequest request, Model model) {
     model.addAttribute("request", request);

   }
}

在我的模板中,我可以做到:

Method: <span th:text="${request.method}">method</span><br/>

它会给我以下html:

Method: POST

有没有一种简单的方法可以知道 request 方法在 Thymeleaf 中的所有属性?例如,执行%{request.toDict} 之类的操作(出于演示目的而编造)。 HttpServletRequest 方法在此处列出,但我不确定哪些可以用作属性,此外,如何(希望)从模板中轻松显示。

【问题讨论】:

  • 可能不是最好的例子,因为在这种情况下您不需要控制器方法。您可以简单地在 HTML 中执行 #request.whateverstackoverflow.com/questions/41395024/…
  • 否则,如果你使用 IntelliJ IDEA,你可以做 &lt;!--/*@thymesVar id="beanName" type="com.somedomain.BeanName"*/--&gt; 并将其包含在你的 HTML 中以完成。
  • @bphilipnyc 当然可以,但是有没有办法将它们全部打印出来,以便我可以一次看到它们的值?
  • 您想将它们打印到页面上吗?还是仅用于您的 IDE(例如,tab 补全)?
  • @bphilipnyc 我想将所有值打印到一个页面,因为很多值都是空的。所以是的,在 html 中,而不是在 TelliJ 中。

标签: java spring thymeleaf


【解决方案1】:

在当前版本的 Thymeleaf (3.0.9) 中,没有特定的实用方法可以打印出对象的属性。所以不,没有简单的方法。

但是,一种方法是构建您自己的方法并使用反射打印它们。当然,我的假设是 Java 可用的方法也应该对 Thymeleaf 可用。如果这不是您想要的,您可以修改此方法 (inspiration)。

public static List<Method> toDict(Class aClass) {
    List<Method> methods = new ArrayList<>();
    do {
        Collections.addAll(methods, aClass.getDeclaredMethods()); //using just this would return the declared methods for the class and not any parent classes
        aClass = aClass.getSuperclass();
    } while (aClass != null);
    return methods;
}

然后在你的 HTML 中调用静态方法:

<div th:each="field : ${T(com.somedomain.util.SomeUtil).toDict(#request.class)}">
    <span th:text="${field}" th:remove="tag">[field]</span><br>
</div>

还要注意单元测试和静态方法的常见注意事项。最后,您可以查看#vars,以防您要访问模型变量。

不需要控制器方法。

【讨论】:

    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2013-08-04
    相关资源
    最近更新 更多