我无法读取我的messages.properties文件(在/ src / main / resources下)
环境:Spring MVC 4.3.14
MyAppConfig.java:
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
在我的jsp(newuserregistration.jsp)中,我有:
<form:form method="POST" modelAttribute="user" class="form-horizontal">
<div class="row">
<label class="col-md-3 control-label" for="userfirstname">First
Name</label>
<div class="col-md-7">
<form:input type="text" path="userfirstname" id="userfirstname"
class="form-control input-sm" />
<div class="has-error">
<form:errors path="userfirstname" class="help-inline" />
</div>
</div>
在我的CSS中我有:
.has-error{
color:red;
}
实体类(AppUsers.java)具有:
@Basic(optional = false)
@NotNull
@NotEmpty
//@Size(min = 1, max = 45)
@Column(name = "USERFIRSTNAME", nullable = false, length = 45)
private String userfirstname;
我的messages.properties有:
NotEmpty.user.userfirstname=First name can not be blank.
控制器有:
@Autowired
MessageSource messageSource;
@RequestMapping(value = {"/registernewuser"}, method = RequestMethod.GET)
public String newUser(ModelMap model) {
AppUsers user = new AppUsers();
model.addAttribute("user", user);
@RequestMapping(value = {"/registernewuser"}, method = RequestMethod.POST)
public String saveUser(@Valid AppUsers user, BindingResult result,
ModelMap model) {
model.addAttribute("user", user);
if (result.hasErrors()) {
model.addAttribute("user", user);
model.addAttribute("loggedinuser", getPrincipal());
return "newuserregistration";
}
不知何故,我的jsp上没有显示错误消息。我在这里缺少什么或做错了什么?
我为了结果做了sysout,它给了我 -
org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'appUsers' on field 'userfirstname': rejected value []; codes [NotEmpty.appUsers.userfirstname,NotEmpty.userfirstname,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [appUsers.userfirstname,userfirstname]; arguments []; default message [userfirstname]]; default message [may not be empty]
答案 0 :(得分:0)
您可以从资源文件中删除NotEmpty.user前缀吗?
资源文件 message.properties
userfirstname=First name can not be blank.
答案 1 :(得分:0)
以下对我有用:
删除了model.addAttribute(&#34; user&#34;,user);和添加 - @ModelAttribute(&#34; user&#34;) - 我的POST方法的属性。这是工作片段:
@RequestMapping(value = {"/registernewuser"}, method = RequestMethod.POST)
public String saveUser(@ModelAttribute("user") @Valid AppUsers user, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
model.addAttribute("loggedinuser", getPrincipal());
return "newuserregistration";
}
但是我仍然想知道最初情况出了什么问题。