@ModelAttribute 注解,什么时候用? [英] @ModelAttribute annotation, when to use it?

查看:33
本文介绍了@ModelAttribute 注解,什么时候用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个实体 Person、一个控制器 PersonController 和一个 edit.jsp 页面(创建新人或编辑现有人)

Lets say we have an entity Person, a controller PersonController and an edit.jsp page (creating a new or editing an existing person)

控制器

@RequestMapping(value = "/edit", method = RequestMethod.POST)
public String editPerson(@RequestParam("fname") String fname, Model model) {
    if(fname == null || fname.length() == 0){
        model.addAttribute("personToEditOrCreate", new Person());
    }
    else{
        Person p = personService.getPersonByFirstName(fname);
        model.addAttribute("personToEditOrCreate", p);
    }

    return "persons/edit";
}

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String savePerson(Person person, BindingResult result) {

    personService.savePerson(person);
    return "redirect:/home";
}

编辑.jsp

<form:form method="post" modelAttribute="personToEditOrCreate" action="save">
    <form:hidden path="id"/> 
    <table>
        <tr>
            <td><form:label path="firstName">First Name</form:label></td>
            <td><form:input path="firstName" /></td>
        </tr>
        <tr>
            <td><form:label path="lastName">Last Name</form:label></td>
            <td><form:input path="lastName" /></td>
        </tr>
        <tr>
            <td><form:label path="money">Money</form:label></td>
            <td><form:input path="money" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Add/Edit Person"/>
            </td>
        </tr>
    </table> 

</form:form>

我正在尝试上面的代码(在 savePerson 方法中没有使用 @ModelAttribute 注释,它工作正常.为什么以及何时需要将注释添加到 person 对象中:

Im trying the code above (without using the @ModelAttribute annotation in the savePerson method, and it works correct. Why and when do i need to add the annotation to the person object:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String savePerson(@ModelAttribute("personToEditOrCreate") Person person, BindingResult result) {

    personService.savePerson(person);
    return "redirect:/home";
}

推荐答案

你不需要@ModelAttribute(参数)只是为了使用一个Bean作为参数

You don't need @ModelAttribute (parameter) just to use a Bean as a parameter

例如,这些处理程序方法可以很好地处理这些请求:

For example, these handler methods work fine with these requests:

@RequestMapping("/a")
void pathA(SomeBean someBean) {
  assertEquals("neil", someBean.getName());
}

GET /a?name=neil

@RequestMapping(value="/a", method=RequestMethod.POST)
void pathAPost(SomeBean someBean) {
  assertEquals("neil", someBean.getName());
}

POST /a
name=neil


使用@ModelAttribute(方法)在每次请求时将默认数据加载到您的模型中 - 例如从数据库中,尤其是在使用@SessionAttributes.这可以在 ControllerControllerAdvice 中完成:


Use @ModelAttribute (method) to load default data into your model on every request - for example from a database, especially when using @SessionAttributes. This can be done in a Controller or in a ControllerAdvice:

@Controller
@RequestMapping("/foos")
public class FooController {

  @ModelAttribute("foo")
  String getFoo() {
    return "bar";  // set modelMap["foo"] = "bar" on every request
  }

}

FooController 转发到的任何 JSP:

Any JSP forwarded to by FooController:

${foo} //=bar

@ControllerAdvice
public class MyGlobalData {

  @ModelAttribute("foo")
  String getFoo() {
    return "bar";  // set modelMap["foo"] = "bar" on every request
  }

}

任何 JSP:

${foo} //=bar


如果你想使用@ModelAttribute(方法)的结果,请使用@ModelAttribute(参数)作为默认:


Use @ModelAttribute (parameter) if you want to use the result of @ModelAttribute (method) as a default:

@ModelAttribute("attrib1")
SomeBean getSomeBean() {
  return new SomeBean("neil");  // set modelMap["attrib1"] = SomeBean("neil") on every request
}

@RequestMapping("/a")
void pathA(@ModelAttribute("attrib1") SomeBean someBean) {
  assertEquals("neil", someBean.getName());
}

GET /a


使用@ModelAttribute(参数)获取存储在flash属性中的对象:


Use @ModelAttribute (parameter) to get an object stored in a flash attribute:

@RequestMapping("/a")
String pathA(RedirectAttributes redirectAttributes) {
  redirectAttributes.addFlashAttribute("attrib1", new SomeBean("from flash"));
  return "redirect:/b";
}

@RequestMapping("/b")
void pathB(@ModelAttribute("attrib1") SomeBean someBean) {
  assertEquals("from flash", someBean.getName());
}

GET /a


使用@ModelAttribute(参数)获取@SessionAttributes

@Controller
@SessionAttributes("attrib1")
public class Controller1 {

    @RequestMapping("/a")
    void pathA(Model model) {
        model.addAttribute("attrib1", new SomeBean("neil")); //this ends up in session due to @SessionAttributes on controller
    }

    @RequestMapping("/b")
    void pathB(@ModelAttribute("attrib1") SomeBean someBean) {
        assertEquals("neil", someBean.getName());
    }
}

GET /a
GET /b

这篇关于@ModelAttribute 注解,什么时候用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆