3

我的问题是我有一个表单,其中包含带有一些选择选项值的 html 选择元素,我想使用以下方法验证这些值:

org.hibernate.validator.constraints
or
javax.validation.constraints

注释。在这里您可能会看到我的表单和我的选择元素:

<form:form action="../agents/add" method="POST" commandName="myAgent">
     <form:select path="state">
            <form:option value="ACTIVE" path="state">ACTIVE</form:option>
            <form:option value="LISTEN" path="state">LISTEN</form:option>
            <form:option value="DOWN" path="state">DOWN</form:option>
    </form:select>
</form:form>

我已经像这样定义了我的控制器方法:

    @RequestMapping(value = "agents/add", method = RequestMethod.POST)
    public String addAgentSubmit(@ModelAttribute("myAgent") @Valid final AgentValidator agent, BindingResult result, RedirectAttributes redirect) {
      if (result.hasErrors()) {
        return "admin/agent/add";
      } 
       ...
    }

我还定义了一个 ModelAttribute 像这样:

@ModelAttribute("myAgent")
 public AgentValidator getLoginForm() {
    return new AgentValidator();
 }

这也是我的 AgentValidator 类:

public class AgentValidator {
    @NotEmpty(message = "your state can not be empty !")
    private AgentState state;
        getter & setter ...
}

这是我的代理状态:

public enum AgentState {
    ACTIVE, DOWN, PAUSED
 }

当我在表单中输入错误的值时(类似这样):

<form:form action="../agents/add" method="POST" commandName="myAgent">
     <form:select path="state">
            <form:option value="ACTIVE!NVALID" path="state">ACTIVE</form:option>
            <form:option value="LISTEN" path="state">LISTEN</form:option>
            <form:option value="DOWN" path="state">DOWN</form:option>
    </form:select>
</form:form>

提交表单后,我的 JSP 中没有显示自定义消息,而是看到以下消息:

无法将 java.lang.String 类型的属性值转换为属性状态所需的类型 tm.sys.validator.AgentState;嵌套异常是 org.springframework.core.convert.ConversionFailedException: 无法从 java.lang.String 类型转换为 @javax.validation.constraints.NotNull tm.sys.validator.AgentState 值 ACTIVE!NVALID;嵌套异常是 java.lang.IllegalArgumentException: No enum constant tm.sys.validator.AgentState.ACTIVE!NVALID

我为此问题进行了很多搜索,但没有一个解决方案可以帮助我向用户提供我的自定义消息。如果您对此有任何解决方案,请提供完整的解决方案,因为我还不是那么先进的程序员。

4

1 回答 1

4

You need to add one of the following keys: typeMismatch, typeMismatch.state or typeMismatch.agentValidator.state into your Messages.properties (or ValidationMessages.properties - whichever messages properties file you have configured with your validator).

typeMismatch.state=You provided invalid state

Exact key name(s) that you need add to message properties can be found from BindingResult. Take a look at result.getFieldError().getCodes() (this should contain codes for the first field error if there is any).

This will override default message (the one which you are seeing) for situations when form submitted value cannot be converted to required type (enum in your case).

于 2013-03-30T14:18:08.417 回答