Spring 3 form validation shows error messages but field name not displayed

≡放荡痞女 提交于 2019-12-12 23:20:54

问题


I have a 2 item form, that requires that both fields be entered. I'm using annotated validations, and am getting error messages, but they do not print the field name, just "may not be blank" instead of "one may not be blank" where one is the field name.

Any ideas? This is a pretty simple example:

@Controller
@SessionAttributes
 public class HomeController
{

private static final Logger logger  = LoggerFactory
                                            .getLogger(HomeController.class);

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
    logger.info("Welcome home! The client locale is {}.", locale);
    model.addAttribute("homeformitem", new HomeFormItem());
    return "home";
}

@RequestMapping(value = "/", method = RequestMethod.POST)
public String home(
        @ModelAttribute("homeformitem") @Valid HomeFormItem item,
        BindingResult result)
{
    logger.info("Posting form");
    logger.info(item.toString());
    if (result.hasErrors())
    {
        return "home";
    } else
    {
        logger.info("No Errors");
        return "done";
    }
}
}

Here is the form. I get the error message, but not the field name.

Form Validation!

    <f:form method="post" modelAttribute="homeformitem">
    <fieldset>
        <legend>Fields</legend> 
    <table>
        <tr><td colspan="3"><f:errors path="*"/></td></tr>
        <tr>
            <td><f:label path="one" for="one">One: </f:label></td>
            <td><f:input path="one" /></td>
            <td><f:errors path="one" cssClass="errorblock"/></td>
        </tr>
        <tr>
            <td><f:label path="two" for="two">Two: </f:label></td>
            <td><f:input path="two" /></td>
            <td><f:errors path="two" cssClass="errorblock"/></td>
        </tr>
        <tr>
            <td colspan="3"><input type="submit" value="Test" /></td>
        </tr>
    </table>
</fieldset>
</f:form>


回答1:


You need a validation.properties file at /WEB-INF/messages with an entry similar to this (for example):

NotEmpty.homeFormItem.one=The field {0} is empty

And don't forget to add a spring bean to resolve your validation messages:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages/validation" />
</bean>


来源:https://stackoverflow.com/questions/16105282/spring-3-form-validation-shows-error-messages-but-field-name-not-displayed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!