Thymeleaf - 如何在 Thymeleaf 标签“th:if”中将字符串与 html 中的请求参数进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23243277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:36:56  来源:igfitidea点击:

Thymeleaf - How to compare string with request parameter in html in Thymeleaf tag "th:if"?

htmlspring-mvcthymeleaf

提问by user3515080

How to compare string with request parameter in html in Thymeleaf tag "th:if" ? right now i am using this

如何在 Thymeleaf 标签“th:if”中将字符串与 html 中的请求参数进行比较?现在我正在使用这个

<div class="error" th:if="${param.error == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">                      
     <p class="errorMsg"><span th:text="${errorMsg}"></span></p>
</div>

But no luck, it is not working.

但没有运气,它不起作用。

回答by michal.kreuzman

It's not working because param.erroris array of strings. You must retrieve first element of array (param.error[0]) to get first value of parameter (see documentation). Besides that you can access request parameter via Web context object method #httpServletRequest.getParameterthat returns first value when parameter is multivalued (see documentation).

它不起作用,因为param.error是字符串数组。您必须检索数组 ( param.error[0]) 的第一个元素才能获得参数的第一个值(请参阅文档)。除此之外,您可以通过 Web 上下文对象方法访问请求参数#httpServletRequest.getParameter,该方法在参数为多值时返回第一个值(请参阅文档)。

  1. Usage of Web context namespaces for request attributes

    <div class="error" th:if="${param.error[0] == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">                      
        <p class="errorMsg"><span th:text="${errorMsg}"></span></p>
    </div>
    
  2. Usage of Web context object

    <div class="error" th:if="${#httpServletRequest.getParameter('error') == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">                      
        <p class="errorMsg"><span th:text="${errorMsg}"></span></p>
    </div>
    
  1. 对请求属性使用 Web 上下文命名空间

    <div class="error" th:if="${param.error[0] == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">                      
        <p class="errorMsg"><span th:text="${errorMsg}"></span></p>
    </div>
    
  2. Web 上下文对象的使用

    <div class="error" th:if="${#httpServletRequest.getParameter('error') == 'badCredentialsException'}" th:with="errorMsg=#{login.badCredentials}">                      
        <p class="errorMsg"><span th:text="${errorMsg}"></span></p>
    </div>
    

回答by RiZKiT

With Thymeleaf 3, I normally use #request(a short form of #httpservletrequest) and #strings.equals()for that, which will look like this:

对于 Thymeleaf 3,我通常使用#request(的缩写形式#httpservletrequest),#strings.equals()为此,它看起来像这样:

<div th:if="${#strings.equals(#request.getParameter('error'), 'badCredentialsException')}"></div>