【问题标题】:Check if Thymeleaf template url contains string检查 Thymeleaf 模板 url 是否包含字符串
【发布时间】:2023-02-18 09:55:16
【问题描述】:

如何检查此 URL“http://localhost:8080/employees/subordinates/1”是否包含字符串“subordinates”?我试图使锚点的存在以包含该短语的 URL 为条件。这是我一直希望达到的目标。

<div th:if="${#strings.contains(#httpServletRequest.requestURI, 'subordinates')}">
    <a href="/employees/list">employee directory</a>
</div>

【问题讨论】:

  • I'm unable to reproduce your behavior。当我有一个带有 /subordinates 的控制器时,我正确地看到了链接 employee directory。你确定这是错误发生的地方吗?
  • 一旦我将我的代码包含在模板中,我就会收到一个白色标签错误页面,其中包含以下消息“原因:org.springframework.expression.spel.SpelEvaluationException:EL1007E:属性或字段‘requestURI’无法在 null 上找到”。默认情况下,httpServletRequest 对象是否可用于模板,还是必须显式提供?
  • 我问是因为,当我用#request 替换#httpServletRequest 时,我得到这个错误:'The 'request','session','servletContext' and 'response' expression utility objects are no longer available by default for template expressions and their use不推荐。在确实需要它们的情况下,应将它们手动添加为上下文变量。
  • 当我将 HttpServletRequest 自动连接到控制器并将其添加为模型属性时,我得到一个“org.springframework.expression.EvaluationException: Accessing member 'requestURI' is forbidden for type...”错误
  • 我能找到的唯一解决方法是将 URI 添加到模型并在模板中引用它:model.addAttribute("URI", request.getRequestURI());和 <div th:if="${#strings.contains(URI, 'subordinates')}">。

标签: spring templates thymeleaf


【解决方案1】:

是的,您在 cmets 中提到的解决方法就是这样做的方法。

#request#response#session#servletContext 表达式实用程序对象在 Thymeleaf 3.1 中不再可用。根据这个issue

#request、#response、#session 和#servletContext 表达式实用程序对象应该从标准方言中删除,这既是出于安全原因(为了避免直接访问可能不安全的属性,例如请求参数),也是因为这些当前绑定到 javax.* Servlet API,并在 Thymeleaf 核心中概括 Web 接口以支持 jakarta.* 和其他 Web 技术将与这些仍然可用的特定对象不兼容。

文章 Thymeleaf 3.1: What’s new and how to migrate 建议在控制器级别向您的模型添加您的模板需要来自这些对象的特定信息。例如,您可以将以下内容添加到您的控制器中:

@ModelAttribute("requestURI")
public String requestURI(final HttpServletRequest request) {
   return request.getRequestURI();
}

并以这种方式在模板中使用该属性:

<div th:if="${#strings.contains(${requestURI}, 'subordinates')}">
    <a href="/employees/list">employee directory</a>
</div>

【讨论】:

    猜你喜欢
    • 2016-05-06
    • 2012-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 2011-11-09
    • 2013-05-18
    • 2012-06-30
    相关资源
    最近更新 更多