1

当我想要在 Spring 3 中的 Session 范围内的模型时,我使用以下方法。控制器中的注释:-

    @SessionAttribute("myModel");

然而,这只是 myModel 的声明。在什么时候它会被初始化,以便我在视图中使用它。Spring 如何知道这个模型的类类型?

有人可以用例子解释一下吗?

4

2 回答 2

7

@SessionAttribute工作方式如下:

  • @SessionAttribute当您将相应的属性放入模型时初始化(显式或使用@ModelAttribute-annotated 方法)。

  • @SessionAttribute当调用签名中具有相应模型属性的控制器方法时,由来自 HTTP 参数的数据更新。

  • @SessionAttribute当您调用作为参数传递给控制器​​方法的对象setComplete()时, s 将被清除。SessionStatus

例子:

@SessionAttribute("myModel")
@Controller
public class MyController {
    @RequestMapping(...)
    public String displayForm(@RequestParam("id") long id, ModelMap model) {
        MyModel m = findById(id);
        model.put("myModel", m); // Initialized
        return ...;
    }

    @RequestMapping(...)    
    public String submitForm(@ModelAttribute("myModel") @Valid MyModel m,
        BindingResult errors, SessionStatus status) {
        if (errors.hasErrors()) {
            // Will render a view with updated MyModel
            return ...;
        } else {
            status.setComplete(); // MyModel is removed from the session
            save(m);
            return ...;
        }

    }
}
于 2011-12-27T14:19:08.490 回答
0

您可以使用@ModelAttribute 注释方法,如果属性名称与@SessionAttribute 注释中指定的相同,则该属性将存储在会话中。这是一个完整的例子:

@Controller   
@RequestMapping(value = "/test.htm") 
@SessionAttributes("myModel")
public class DeleteNewsFormController {

    // Add you model object to the session here
    @ModelAttribute("myModel")
    public String getResultSet() {
        return "Hello";
    }

    //retreive objects from the session
    @RequestMapping(method = RequestMethod.GET)
    public @ResponseBody testMethod(@ModelAttribute("resultSet") String test, Model model) {
于 2011-12-27T14:14:39.720 回答