0

私はSpring mvcを初めて使用します.Name、age、IDのフィールドを持つフォームを作成するサンプルアプリケーションを作成しました.Controllerメソッドは

@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
4

1 に答える 1