2

私はSpringMVC3でフォーム検証をできるだけ簡単で邪魔にならないようにする方法を探していました。@Validをモデル(バリデーターアノテーションで注釈が付けられている)に渡し、 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";
    }
}

これは魅力のように機能します。データベースの例外(フィールドに一意の制約があるものを保存しようとするなど)は引き続き発生します。舞台裏で行われている検証プロセスにこれらの例外のキャッチを組み込む方法はありますか?この検証方法は非常に簡潔なので、コントローラーで手動でキャッチする必要はありません。

これに関する情報はありますか?

4

1 に答える 1

3

これは、PersistentExceptionsをよりわかりやすいメッセージに変換するために使用する例です。これは、コントローラーに組み込まれるメソッドです。これはあなたのために働きますか?

/**
 * 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;
}
于 2012-05-10T20:00:38.203 に答える