春季3表单验证显示错误信息,但不显示字段名 [英] Spring 3 form validation shows error messages but field name not displayed
问题描述
我有2项形式,即要求两个字段中输入。我使用的注解验证,和我收到错误消息,但他们不打印的字段名称,只是不能为空,而不是一不能为空,其中一个是字段名。
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.
任何想法?这是一个pretty简单的例子:
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.
表单验证!
<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>
推荐答案
您需要 / WEB-INF /消息的
与此类似(比如)一个条目: validation.properties
文件
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
和不要忘记添加一个Spring bean解决您的验证消息:
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>
这篇关于春季3表单验证显示错误信息,但不显示字段名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!