在Spring MVC中编写控制器和视图 - 具有包含域对象的字段的表单

时间:2013-03-26 15:09:02

标签: spring-mvc

我是Spring MVC的新手。我找不到办法做到这一点:

假设我有一个域类。

class CourseRegistration {
  Student student; // Have id and name
  Course course; // Have id and name
  String semester;
}

我想创建一个弹簧形式来创建课程注册。

该课程由控制器填充的组合框选择。

学生姓名将写入文本字段,但有一项服务可以按名称查找用户。

如何编写这样的控制器和视图?

  • 您可以假设我有适合学生,课程和课程注册的商业服务。

1 个答案:

答案 0 :(得分:2)

首先,定义表单底层的模型。必须是POJO。

注册将成立:用户名和课程(添加您想要的任何内容)。

class RegistrationModel{
    @NotNull
    private String username;

    @NotNull
    private Course course;

    // getters and setters
}

控制器

@RequestMapping("/registration/**")
@Scope("session")
@Controller
class RegistrationController{
    @Autowired  // or inject manually in app context
    private courseService;

    @Autowired  // or inject manually in app context
    private studentService;

    // No need for getter and setter. However is a best practice to write them
    // Storing the mode in the controller will allow you to reuse the same
    // model between multiple posts (for example, validation that fails)
    private RegistrationModel registrationModel; 

    // getters and setters as usual

    // inject into the view the course list
    // there are other ways to do that, 
    // i'll get my preferred one. 
    // refer to Spring online documentation
    @ModelAttribute("courses")
    public List<Course> injectCourses(){
        return courseService.findAll();
    }

    // create and inject the registration model
    @ModelAttribute("registration")
    public RegistrationModel injectRegistration(){
        if(registrationModel==null)
            registrationModel = new RegistrationModel();

        return registrationModel;
    }

    // handles the post
    @RequestMapping(method=RequestMethod.POST)
    public ModelAndView doRegistration(@Valid @ModelAttribute("registration") registration, BindingResult bindingResult){
        if(bindingResult.hasError())
            return new ModelAndView("registration/index"); // redraw the form

        CourseRegistration cr = new CourseRegistration(); // or get it as a bean from the context
        cr.setStudent(studentService.findByUsername(registrationModel.getUsername()));
        cr.setCourse(registrationModel.getCourse());

        courseService.save(cr);

        return new ModelAndView("registration/confirm"); // imaginary path... 
    }

    // "draws" the form
    @RequestMapping
    public ModelAndView registration(){
        return new ModelAndView("registration/index"); // the path is hypothetic, change it
    }

}

JSPX(表格的摘录)

<form:form modelAttribute="registration" method="POST">
    <form:input path="username" />
    <form:errors path="username" />
    <form:select path="course">
        <c:foreach items="${courses}" var="course">
            <form:option value="${course}" label="${course.name [the property to be shown in the drop down]}" />
        </c:foreach>
    </form:select>
    <form:errors path="course" />
</form:form>

您需要导入以下命名空间:

http://www.springframework.org/tags/form

http://java.sun.com/jsp/jstl/core

(检查一下)

我添加了模型验证代码。实施自己的验证器来检查学生的存在应该是一个好主意。只需谷歌“JSR 303 spring validation”,您就会找到一堆资源。

这应该是一个很好的支柱。

而且......不要相信代码的正确性。我是基于我没有智能感知的东西(上帝保佑intellisense!:-))而动态写的。

斯特凡诺