我正在使用JHipster 3.3。在生成的"实体" -dialog.html中,我注意到标记 jhi-alert-error 元素将显示服务器验证错误,例如,如果字段是实体中指定的必填字段JPA类喜欢
@NotNull
private String name;
如果该字段的值为空,则在单击“提交”按钮后将返回该字段的错误消息。
所以问题:
如何实施 jhi-alert-error ?我似乎无法看到它的实现
我尝试调整JPA注释以使字段唯一但这次没有错误消息将显示在 jhi-alert-error 中如果我通过添加2个记录来打破唯一约束该领域的价值相同, E.g。
// note' unique = true'以下
@NotNull @Column(name =" name",unique = true)
私有字符串名称;
或
@Table(name =" Module",uniqueConstraints = @UniqueConstraint(columnNames =" Name")) public Class Module实现Serializable {...
那么我将如何实现自己的服务器端表单验证,以便在单击“提交”按钮后字段的唯一约束被破坏时,错误消息将显示在 jhi-alert-error 中?
提前致谢,
答案 0 :(得分:3)
我使用较旧版本的jhipster(2.26),因此代码可能会有一些差异。要回答第一个问题,jhi-alert-error是一个自定义的Angular指令,请查看alert.directive.js文件和jhAlertError指令(应该出现在jhAlert指令之后)。该指令期望httpResponse.data对象是ErrorDTO服务器端对象。
要添加自定义错误消息,您需要返回ErrorDTO对象,该指令将显示该消息。为此,您需要抛出异常并确保将spring AOP - ExceptionTranslator配置为捕获它。如果您不想创建新的自定义异常,则可以使用CustomParameterizedException:
@RequestMapping(value = "/pizzas",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Pizza> create(@RequestBody Pizza pizza) throws URISyntaxException {
if(pizza.isDisgusting()){
throw new CustomParameterizedException("Sorry, your pizza recipe is horrible");
}
log.debug("REST request to save Pizza : {}", pizza);
if (pizza.getId() != null) {
return ResponseEntity.badRequest().header("Failure", "A new pizza cannot already have an ID").body(null);
}
Pizza result = pizzaRepository.save(pizza);
return ResponseEntity.created(new URI("/api/pizzas/" + pizza.getId())).body(result);
}