我遇到显示错误消息的问题。我使用Spring MVC并发送类似对象UserForm的表单,我想使用Hibernate验证器,这是工作但我看不到任何错误消息。
这是形式home.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<link rel="stylesheet" type="text/css"
href="./resources/styles/style.css" media="screen" />
<title>Home</title>
</head>
<body>
<h1>
User Form
</h1>
<form:form action="addUser" commandName="userform" method="get">
<table>
<tr>
<td>Name: </td>
<td><form:input path="name"/></td>
<td><form:errors path="name" cssClass="error"/></td>
</tr>
<tr>
<td>Text: </td>
<td><form:textarea path="text"/></td>
<td><form:errors path="text" cssClass="error"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Send"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
我的控制器UserController处理上面的表单
package cz.solution.controllers;
import java.util.Date;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import cz.morosystems.form.UserForm;
import cz.morosystems.tools.JobSheduler;
@Controller
public class UserController {
@RequestMapping(value="/", method=RequestMethod.GET)
public String showMyform(Model model) {
model.addAttribute("userform", new UserForm());
return "home";
}
@RequestMapping(value = "/addUser")
public String showFilledForm(@Valid @ModelAttribute("usermessage") UserForm userform, BindingResult result,
Model model) {
userform.setDate(new Date());
model.addAttribute("userform", userform);
if(result.hasErrors()){
return "/home";
}else{
return "displayUser";
}
}
}
UserForm用于处理来自home.jsp的表单
package cz.solution.form;
import java.util.Date;
import org.hibernate.validator.constraints.NotEmpty;
public class UserForm {
@NotEmpty
private String name;
@NotEmpty
private String text;
private Date date;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
我将此添加到servlet-context.xml
<beans:bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<beans:property name="basename" value="messages" />
</beans:bean>
我在文件夹src / main / resources
中有messages.propertiesNotEmpty.userForm.name = Name is required!
NotEmpty.userForm.text = Text is required!
当其中一个输入为空时,再次显示该表单,但没有错误消息。我尝试添加到UserForm
@NotEmpty(message="Name is required")
private String name;
但又没有成功。感谢所有提示。
答案 0 :(得分:1)
解决!方法showFilledForm将@Valid放在@ModelAttribute
之后