use*_*462 2 java message thymeleaf
使用百里香叶
人.java
public class Person {
@NotEmpty(message="{Valid.Password}")
private String password;
}
Run Code Online (Sandbox Code Playgroud)
消息属性
Valid.Password = Password is Empty!!
Run Code Online (Sandbox Code Playgroud)
登录.html
<span class="error" th:errors="person.password"></span>
Run Code Online (Sandbox Code Playgroud)
th:errors无法检索“有效密码”消息 该区域显示为空。
如果消息密钥更改为 message.properties 的 NotEmpty.person.password,则它可以正常工作。
如何使用自定义消息键?
在类上使用 javax.validation 约束并添加自定义消息需要您基本上覆盖默认消息。例如:
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
@Size(min=17, max=17, message="VIN number must have 17 characters")
private String vin;
@NotEmpty
@Pattern(regexp="[a-z]*", flags = Pattern.Flag.CASE_INSENSITIVE)
private String make;
@NotEmpty
@Pattern(regexp="[a-z]*", flags = Pattern.Flag.CASE_INSENSITIVE)
private String model;
Run Code Online (Sandbox Code Playgroud)
要覆盖默认值,您可以在验证本身中插入自定义消息(如 VIN),或将它们添加到 messages.properties 文件中:
# Validation messages
notEmpty.message = The value may not be empty!
notNull.message = The value cannot be null!
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以覆盖以下默认值:
javax.validation.constraints.NotEmpty.message
javax.validation.constraints.NotNull.message
Run Code Online (Sandbox Code Playgroud)
如果您需要不同字段的特定消息,则消息属性应按以下格式包含它们:[constraintName.Class.field]。例如:
NotEmpty.Vehicle.model = Model cannot be empty!
Run Code Online (Sandbox Code Playgroud)
如果您不包含上面的覆盖值,它将显示默认值,或常规覆盖,例如 notEmpty 消息。
当然,还有其他显示验证消息的方法,例如使用来自 Validator 实例的 ConstraintViolation 对象所需的信息。
希望这可以帮助,
| 归档时间: |
|
| 查看次数: |
5269 次 |
| 最近记录: |