【问题标题】:Form in Spring MVCSpring MVC 中的表单
【发布时间】:2017-06-22 18:46:24
【问题描述】:

我想创建一个页面,处理来自用户的数据并创建我的 Employee 类的实例。我根据互联网上的教程创建了表单,但是当我运行应用程序时,出现以下错误:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute

表格代码如下:

<html>
<head>
    <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <h1>Employee add</h1>
<form:form method="POST" action="/employee/add">
   <table>
<tr>
    <td><form:label path="name">Name</form:label></td>
    <td><form:input path="name" /></td>
</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>

员工控制器

@Controller
@RequestMapping(value = {"/employee"})
public class EmployeeController {

@RequestMapping(value = {"/employeeForm"}, method = RequestMethod.GET)
public String employeePage() {
    System.out.println("EmployeeController");
    return "/employee/add";
}

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute("ProjectSpring") Employee employee,
        ModelMap model) {
    model.addAttribute("name", employee.getFirstName());
    model.addAttribute("age", employee.getLastName());

    return "index";
}   
}

谁能告诉我,这个错误是什么原因造成的??

【问题讨论】:

  • 您需要向我们展示您的控制器正在处理来自此表单的 POST。
  • 你的模型属性"ProjectSpring"是在哪里定义的?

标签: java spring jsp model-view-controller


【解决方案1】:

首先将'commandName'属性添加到表单标签,它的值是bean name,它作为属性添加到ModelMap中,如下所示:

<form:form method="POST" commandName="ProjectSpring" action="/employee/add">

请在控制器的 ModelMap 中添加 bean 实例,以便它可以在 jsp 中使用。即:-

@RequestMapping(value = {"/employeeForm"}, method = RequestMethod.GET)
public String employeePage(ModelMap model) {
    model.addAttribute("ProjectSpring", new Employee ());
    System.out.println("EmployeeController");
    return "index";
}

现在你的代码可以工作了……享受吧……

【讨论】:

    猜你喜欢
    • 2015-12-20
    • 1970-01-01
    • 2014-06-09
    • 2013-03-05
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多