我是 spring mvc 的新手。我创建了示例应用程序,该应用程序创建了带有字段名称、年龄、ID 的表单。控制器方法是
@RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("home", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@Valid Student student,BindingResult result, Model model) {
if(result.hasErrors()) {
return "home";
}
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
我的模型类 Student.java
public class Student {
private Integer age;
@NotEmpty @Email
private String name;
private Integer id;
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
}
当我输入正确的电子邮件 ID 数据时它工作正常,但是当我输入无效的电子邮件或 NULL 时它会给出异常。而不是给出错误它应该显示适当的错误消息。我的观点 Home.jsp 是
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Student Information</h2>
<form:form method="POST" action="/controller/addStudent" >
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
<form:errors path="name" >Invalid Name</form:errors>
</tr>
<tr>
<td><form:label path="age">Age</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="id">id</form:label></td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
</body>
</html>
例外是:
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/views/home.jsp at line 12
9: <form:form method="POST" action="/controller/addStudent" >
10: <table>
11: <tr>
12: <td><form:label path="name">Name</form:label></td>
13: <td><form:input path="name" /></td>
14: <form:errors path="name" >Invalid Name</form:errors>
15: </tr>
根本原因
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute