How to personalize a message for data conversion failure in Spring MVC?

I have a Spring MVC web application as follows:

@Controller
@RequestMapping("/users")
public class UserController extends FrontEndController {

    @RequestMapping(method = RequestMethod.POST)
    public String post(@Valid @ModelAttribute("user") User user, Errors errors, Model model) {
        ...
    }
}

class User {
    @NotBlank(message = "user name is mandatory")
    String userName;

    public enum Color {RED, GREEN, YELLO}

    @NotNull(message = "color is mandatory)
    private Color color;
    // getters and setters
}

When my web controller validates the user, it reports that "color is required" if this parameter is not specified. This message is displayed in a web form. However, if the string "BLUE" is passed in color (which is not one of the 3 enumeration options), I get the message as follows:

Failed to convert property value of type java.lang.String to required type User$Color for property color; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @javax.validation.constraints.NotNull User$Color for value BLUE; nested exception is java.lang.IllegalArgumentException: No enum constant User.Color.BLUE.

This message is displayed in a web form.

hibernate? ; . Spring "BLUE" , .

, Spring MVC, ? " java.lang.String to...", - , " ".

+4
1

.properties, Spring / MVC ( ). (JSR-303), ( ).

.

, (, ). . . " " .

+6

Source: https://habr.com/ru/post/1547589/


All Articles