Spring: How to resolve a validation error -> error code -> error message

后端 未结 1 437
你的背包
你的背包 2021-02-09 03:37

In Spring, after validation we get a BindingResult object in the controller.

Simple enough, if I get validation errors I want to re-display my

1条回答
  •  无人及你
    2021-02-09 04:16

    You are, as you guessed, making it way harder on yourself than it needs to be. The FieldError object is itself a MessageSourceResolvable. You don't need to get the codes off of it then take individual codes manually to your message source and go looking. You can just pass it to your MessageSource and it will find the most specific one that has a translation defined in your locale. (assuming your code resolver put them on in the right order.)

    You really don't even need to do that in most cases though. Putting the Errors on your backing object and translating them yourself isn't usually needed. The form namespace in the jsp library provides a tag that looks up error messages for you. All you need to do is put the Errors in the ModelMap. See docs:

    http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-errorstag

    0 讨论(0)
提交回复
热议问题