0

Here is form.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add Student</title>
</head>
<body>
    <form:form action="addStudent" commandName="addStudent" method="post">
        <table>
            <tr>
                <td><form:label path="name">Name:</form:label></td> <td><form:input path="name"/></td>
            </tr>
            <tr>
                <td><form:label path="email">Email:</form:label></td> <td><form:input path="email"/></td>
            </tr>
            <tr>
                <td><form:label path="age">Age:</form:label></td> <td><form:input path="age"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Submit"></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

Here is controller method

@RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String addStudent(@ModelAttribute("addStudent") Student student) {
    System.out.println("Saving Info...");
    System.out.println("Name: "+student.getName());
    System.out.println("Email: "+student.getEmail());
    System.out.println("Age: "+student.getAge());
    return "form";
}

Here is Student model

public class Student {

    private String name;
    private String email;
    private int age;
    private int id;

    public Student() {
        super();
    }
}

I guess there is no need for web.xml or dispatcher-servlet.xml . Every thing is correctly binded, I mean commandName is right in jsp. ModelAttribute is correct in controller then why contol is not reaching controller? :(

Please help. I have already wasted half of the day on this. PS:I am new to Spring and stackoverflow.

EDIT:

after suggestions, my code look like this:

controller method:

public String addStudent(@ModelAttribute("student") Student student, BindingResult result) {

jsp form:

<form:form action="addStudent" commandName="student" method="post">

EDIT:

resolved it myself added this method for modelattibute

@ModelAttribute("student")
    public Student getForm() {
        return new Student();
    }
4

1 回答 1

0

只要 commandName 和 modelAttribute String 相同就可以了。

同样,我是 Spring 的新手。但我猜它找不到正确的请求映射,因为您在请求映射中有 /addStudent 并且在表单操作中只有 addStudent 。如果表单在上下文根中,那很好。你能试试看吗?

另外请在 arg 列表中添加一个 BindingResult 对象 public String addStudent(@ModelAttribute("addStudent") Student student, BindingResult result)

于 2014-10-10T08:04:24.133 回答