GVKun编程网logo

Thymeleaf-自定义属性(thymeleaf自定义函数)

15

此处将为大家介绍关于Thymeleaf-自定义属性的详细内容,并且为您解答有关thymeleaf自定义函数的相关问题,此外,我们还将为您介绍关于java–用Mockito测试Thymeleaf自定义方

此处将为大家介绍关于Thymeleaf-自定义属性的详细内容,并且为您解答有关thymeleaf自定义函数的相关问题,此外,我们还将为您介绍关于java – 用Mockito测试Thymeleaf自定义方言、java+thymeleaf-layout-dialect+thymeleaf 的使用、org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties的实例源码、Spring + Thymeleaf自定义验证显示的有用信息。

本文目录一览:

Thymeleaf-自定义属性(thymeleaf自定义函数)

Thymeleaf-自定义属性(thymeleaf自定义函数)

我需要从消息资源中设置自定义属性(data-validation-matches-message)值。

<input data-validation-matches-message="Text from messages resources" />

我可以接收和打印消息资源值为:

<p th:text="#{user.notfound}"></p>

但是,如何为自定义属性(data-validation-matches-message)设置此值?

UPD (我用这个)

<input th:attr="data-validation-matches-message=#{user.notfound}"/>

答案1

小编典典

尝试这个:

<input th:attr="data-validation-matches-message=''\'''' + #{user.notfound}" + ''\''''"/>

java – 用Mockito测试Thymeleaf自定义方言

java – 用Mockito测试Thymeleaf自定义方言

我最近为Thymeleaf编写了一个自定义方言以及一个自定义处理器来处理一些自定义标签,并在某些情况下用不同的标签替换它们,但是我在为处理器编写测试时遇到了问题:

AbstractProcessor类需要覆盖

protected ProcessorResult doProcess(Arguments arguments,ProcessorMatchingContext processorMatchingContext,Node node)

方法,这是我需要测试的方法.

由于我的处理器涉及从arguments参数中获取变量,所以我尝试模拟它;但是,Arguments,ProcessorMatchingContextand Node类都被声明为final,这意味着它们不能被Mockito模拟.

我真的不想实例化一个实际的Arguments对象,因为它依赖于其他5个无法模拟的对象,我最终会编写大量代码来测试处理器中的一行.

有关可能的测试策略的任何想法?

解决方法

我不知道这是否有帮助,但你可以使用 Objenesis实例化一个实际的(非模拟的)参数而不需要所有其他5个依赖类

java+thymeleaf-layout-dialect+thymeleaf 的使用

java+thymeleaf-layout-dialect+thymeleaf 的使用

【源创会预告】1024 程序员节(的前两天),相约开源中国办公室,我们一起聊 AI!>>>

一,添加 pom.xml 文件依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>nz.net.ultraq.thymeleaf</groupId>
            <artifactId>thymeleaf-layout-dialect</artifactId>
            <version>2.4.1</version>
        </dependency>

二,如下两个文件代码

index.html 引用模板文件,PS:(layout:decorate="testlayout/layout", 这个必须注意,模板文件的地址)

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{testlayout/layout}">
<head lang="en">
    <title>Search</title>
</head>
<body>
<div class="row" layout:fragment="content">
    <h4 class="indigo-text center">中间部分e</h4>

</div>
</body>
</html>

模板文件

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no" />
  <title>Insert title here</title>

</head>
<body>
<div>
  <div th:replace="/testlayout/test::nav"></div>
</div>
<section layout:fragment="content">
  <p>Page content goes here</p>
</section>
<div>
 尾部
</div>
</body>
</html>

test.html 导航文件代码,PS:<div th:replace="/testlayout/test::nav"></div > 注意这个地址,不能写错,我的文件都是在 testlayout 这个文件目录下的

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="nav">
  <nav>
    <ul class="columnbar">
      <li><a href="/#">首页</a></li>
      <li><a href="/#">首页</a></li>
      <li><a href="/#">首页</a></li>
      <li><a href="/#">首页</a></li>
      <li><a href="/#">首页</a></li>
    </ul>
  </nav>
</div>
</body>
</html>

 

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties的实例源码

org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties的实例源码

项目:cas-5.1.0    文件:CasProtocolView.java   
/**
 * Instantiates a new Cas protocol view.
 *
 * @param templateName       the template name
 * @param applicationContext the application context
 * @param templateEngine     the template engine
 * @param properties         the properties
 */
public CasProtocolView(final String templateName,final ApplicationContext applicationContext,final SpringTemplateEngine templateEngine,final ThymeleafProperties properties) {
    super(templateName);
    setApplicationContext(applicationContext);
    setTemplateEngine(templateEngine);
    setCharacterEncoding(properties.getEncoding().displayName());
    setLocale(Locale.getDefault());
}
项目:ogham    文件:ThymeLeafConfigurer.java   
public ThymeLeafConfigurer(SpringTemplateEngine springTemplateEngine,OghamCommonTemplateProperties templateProperties,OghamEmailProperties emailProperties,OghamSmsProperties smsProperties,ThymeleafProperties springProperties) {
    super();
    this.springTemplateEngine = springTemplateEngine;
    this.templateProperties = templateProperties;
    this.emailProperties = emailProperties;
    this.smsProperties = smsProperties;
    this.springProperties = springProperties;
}

Spring + Thymeleaf自定义验证显示

Spring + Thymeleaf自定义验证显示

如何解决Spring + Thymeleaf自定义验证显示?

这可能是因为您的@PasswordsEqualConstraint被分配给整个bean(类型)而不是字段“ confirmPassword”。要将可能违反约束的条件添加到具体字段,您可以像以下示例一样进行操作。

如果两个字段不相等,则FieldMatch比较两个字段,然后将验证错误分配给第二个字段。

顺便说一句。这是您正在做的事情的更通用的解决方案。密码示例,您可以像这样使用它

@FieldMatch(first = "password", second = "confirmPassword", message = "Passowords are not equal.")

验证器:

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {

  private String firstFieldName;
  private String secondFieldName;

  @Override
  public void initialize(final FieldMatch constraintAnnotation) {
    firstFieldName = constraintAnnotation.first();
    secondFieldName = constraintAnnotation.second();
  }

  @Override
  public boolean isValid(final Object value, final ConstraintValidatorContext context) {
    try {
      final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
      final Object secondobj = BeanUtils.getProperty(value, secondFieldName);

      boolean isValid = firstObj == null && secondobj == null || firstObj != null && firstObj.equals(secondobj);

      if (!isValid) {
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addNode(secondFieldName).addConstraintViolation();
      }

      return isValid;
    }
    catch (final Exception ignore) {
      // ignore
    }
    return true;
  }
}

解决方法

我一直在尝试使自定义javax验证正常工作(Spring Boot和Thymeleaf),但是我不知道如何显示错误消息。问题似乎是“正常”错误(例如@
Size,@
NotNull等)似乎将FieldError添加到绑定结果中。我的自定义验证器虽然提供了ObjectError。我不知道如何让Thymeleaf来显示我的自定义错误(由于th:errors="*{*}"显示了此错误,显然已经通过了)。

任何帮助是极大的赞赏。

更新:我现在可以通过显示错误消息

<p th:if="${#fields.hasErrors(''${user}'')}" th:errors="${user}"></p>

但是,如果我需要多个验证者(例如,确认密码和确认电子邮件),则该解决方案将无法正常工作(如果一个不合适,则显示两个错误消息。如果有任何建议,请不要犹豫)。

以下是我为此使用的代码:

模板:

<p th:if="${#fields.hasErrors(''username'')}"th:errors="*{username}"></p>
<!-- works just fine -->
<p th:if="${#fields.hasErrors(''*'')}" th:errors="*{*}"></p>
<!-- works and displays all errors (for every field with an error,including my custom validator) -->
<p th:if="${#fields.hasErrors(''confirmPassword'')}" th:errors="*{*}"></p>
<!-- does not work -->
<p th:if="${#fields.hasErrors(''*'')}" th:errors="*{confirmPassword}"></p>
<!-- does not work -->

验证器实现:

public class PasswordsEqualConstraintValidator implements
        ConstraintValidator<PasswordsEqualConstraint,Object> {

    @Override
    public void initialize(PasswordsEqualConstraint arg0) {
    }

    @Override
    public boolean isValid(Object candidate,ConstraintValidatorContext arg1) {
        User user = (User) candidate;
        return user.getPassword().equals(user.getConfirmPassword());
    }
}

验证器界面:

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PasswordsEqualConstraintValidator.class)
public @interface PasswordsEqualConstraint {
    String message();

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

User.java:

@PasswordsEqualConstraint(message = "passwords are not equal")
public class User implements java.io.Serializable {
...     
@Size(min=2,max=40)
private String username;
...
private String confirmPassword;
...

控制器:

@RequestMapping(value = "/signup",method = RequestMethod.POST)
public String signup(@Valid User user,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "signup";
        }
        ... do db stuff .. return "success";
}

今天关于Thymeleaf-自定义属性thymeleaf自定义函数的分享就到这里,希望大家有所收获,若想了解更多关于java – 用Mockito测试Thymeleaf自定义方言、java+thymeleaf-layout-dialect+thymeleaf 的使用、org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties的实例源码、Spring + Thymeleaf自定义验证显示等相关知识,可以在本站进行查询。

本文标签: