使用Spring MVC 3进行适当的表单验证 - 捕获PersistenceException

时间:2012-05-10 19:12:44

标签: java spring spring-mvc

我一直在寻找一种方法,使表单验证在Spring MVC 3中尽可能简单且不引人注目。我喜欢spring通过将@Valid传递给我的模型来处理Bean验证的方式(已经使用验证器注释进行了注释)并使用result.hasErrors()方法。

我正在设置我的控制器操作:

@RequestMapping(value = "/domainofexpertise", method = RequestMethod.PUT)
public String addDomainOfExpertise(@ModelAttribute("domainOfExpertise") 
@Valid DomainOfExpertise domainOfExpertise, final BindingResult result) {

    if (result.hasErrors()) {
        return "/domainofexpertise/add";
    } else {
        domainOfExpertiseService.save(domainOfExpertise);
        return "redirect:/admin/domainofexpertise/list";
    }
}

这就像魅力一样。数据库异常(比如尝试在字段上保存具有唯一约束的内容)仍然可以通过。有没有办法在幕后的验证过程中加入捕获这些异常?这种验证方式非常简洁,所以我想避免在我的控制器中手动捕获它们。

关于此的任何信息?

1 个答案:

答案 0 :(得分:3)

这是我用来将PersistentExceptions转换为更友好的消息的示例。这是Controller中的一种方法。这对你有用吗?

/**
 * Shows a friendly message instead of the exception stack trace.
 * @param pe exception.
 * @return the exception message.
 */
@ExceptionHandler(PersistenceException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handlePersistenceException(final PersistenceException pe) {
    String returnMessage;
    if (pe.getCause()
            instanceof ConstraintViolationException) {
        ConstraintViolationException cve =
                (ConstraintViolationException) pe.getCause();
        ConstraintViolation<?> cv =
                cve.getConstraintViolations().iterator().next();
        returnMessage = cv.getMessage();
    } else {
        returnMessage = pe.getLocalizedMessage();
    }
    if (pe instanceof EntityExistsException) {
        returnMessage = messages.getMessage("user.alreadyexists");
    }
    return returnMessage;
}