首页 > 解决方案 > 了解 Spring Boot 中的 @ModelAttribute 和 @RequestMapping

问题描述

代码示例取自这里:https ://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation

拿下代码:

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

        employeeMap.put(employee.getId(), employee);

        return "employeeView";
    }

我知道这@RequestMapping只是将端点映射到此方法,但是我不明白的是:

  1. 调用方法时,方法参数“来自”哪里?我不知道从哪里来ModelMap

  2. 它怎么知道@ModelAttribute("employee")是什么?这是来自View(HTML),对吧?

  3. 什么是Model真的?它只是地图的类型<String, Object>吗?的寿命是Model多少?

标签: javaspring-bootannotations

解决方案


推荐阅读