我决定使用以下方法。假设我们有一个模型类Question,它有一个属性body。
@Entity
@Table(name = "Questions")
public final class Question {
// other properties & code
private String body;
// other properties & code
}
我们希望将正文长度限制为1024 符号,并仅在服务器上定义一次此限制,并在应用程序的后端和前端使用此限制。
在服务器端,在我们的模型类Question 中,我们定义了静态映射,其中包含所有类属性的大小限制。
@Entity
@Table(name = "Questions")
public final class Question {
private static class ModelConstraints {
static final int MAX_BODY_LENGTH = 1024;
// limits for other fields are going here
}
private static final Map<String, Integer> modelConstraintsMap;
static
{
final Map<String, Integer> localConstraintsMap = new HashMap<>();
localConstraintsMap.put("MAX_BODY_LENGTH", ModelConstraints.MAX_BODY_LENGTH);
// .... putting all constants from ModelConstraints to the map here
// composing unmodifable map
modelConstraintsMap = Collections.unmodifiableMap(localConstraintsMap);
}
@Column(length = ModelConstraints.MAX_BODY_LENGTH, nullable = false)
@Size(max = ModelConstraints.MAX_BODY_LENGTH)
private String body;
// other properties and code
public static Map<String, Integer> getModelConstraintsMap() {
return modelConstraintsMap;
}
// other properties and code
}
内部类ModelConstraints 包含所有相关模型属性的最大长度值的定义。
在静态块中,我创建了一个不可修改的地图,其中包含这些约束,并通过公共方法返回此地图。
在控制器中,与模型类相关,我添加了一个返回属性长度约束的休息端点。
@RequestMapping(path = "/questions/model-constraints", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<Map<String, Integer>> getModelConstraints() {
return new ResponseEntity<>(Question.getModelConstraintsMap(), HttpStatus.OK);
}
此方法返回带有属性长度约束的地图的 json 表示。
在(角)前端,我称之为端点并设置表单字段的maxlength 属性,与模型类属性相关。
在我添加并调用这个方法的组件打字稿文件中:
loadConstraints() {
var url: string = "/questions/model-constraints";
this.http
.get(url)
.subscribe((data: Map<string, number>) => (this.modelConstraints = data));
}
调用此方法后,组件属性modelConstraints 将包含具有字段长度限制的映射。
我在组件模板 (html) 文件中设置了这些约束。
<textarea
matInput
rows="7"
placeholder="Question body"
maxlength="{{ modelConstraints['MAX_BODY_LENGTH'] }}"
[(ngModel)]="questionBody"
></textarea>
就是这样。使用这种方法,您只能在服务器上定义一次字段长度,然后在服务器和客户端上使用此定义。