简体   繁体   English

spring 表格中的欢迎页面

[英]Welcome page in spring form

Why we returned ModelAndView in showForm() method of Controller class when using Spring Form.为什么我们在使用 Spring 表单时在 Controller class 的 showForm() 方法中返回了 ModelAndView。

@Controller
public class EmployeeController {

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public ModelAndView showForm() {
        return new ModelAndView("employeeHome", "employee", new Employee());
    }

    @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    public String submit(@Valid @ModelAttribute("employee")Employee employee, 
      BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "error";
        }
        model.addAttribute("name", employee.getName());
        model.addAttribute("contactNumber", employee.getContactNumber());
        model.addAttribute("id", employee.getId());
        return "employeeView";
    }
}

If you return a String from a controller method its value is treated as the name of a view you want to show to the user.如果您从 controller 方法返回一个字符串,则其值将被视为您要向用户显示的视图的名称。 While rendering the view the data is taken from Model or ModelMap instance, which you pass to the method as a parameter and fill with your data in the method body.在呈现视图时,数据取自 Model 或 ModelMap 实例,您将其作为参数传递给方法并在方法主体中填充数据。

    model.addAttribute("name", employee.getName());
    model.addAttribute("contactNumber", employee.getContactNumber());
    model.addAttribute("id", employee.getId());
    return "employeeView";

If you return ModelAndView, however, the name of the view as well as the data needed to render the view are both taken from the single returned instance.但是,如果您返回 ModelAndView,则视图的名称以及呈现视图所需的数据都取自单个返回的实例。

return new ModelAndView("employeeHome", "employee", new Employee());

Here you return an instance of ModelAndView, which carries the name of the view('employeeHome') and data represented by an Employee object inside an attribute named 'employee'.在这里,您返回一个 ModelAndView 的实例,它带有视图的名称 ('employeeHome') 和由名为 'employee' 的属性中的 Employee object 表示的数据。

The difference in use of each option is insignificant, so use whatever you feel is more convenient to you.每个选项的使用差异不大,因此请使用您认为更方便的任何选项。

Also you might want to check out this article to get a more clear understanding: https://www.baeldung.com/spring-mvc-model-model-map-model-view您也可能想查看这篇文章以获得更清晰的理解: https://www.baeldung.com/spring-mvc-model-model-map-model-view

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM