3

I am using Spring3 MVC. In my controller, I have many methods such as create, edit, and search.

In my form in the view, I need a list which contains some values from db. So I add a following method

```

@ModelAttribute("types") 
public Collection<BooleanValue> populateTypes() {
    return typeRepository.findAll();
}

```

Then, every request will call this method first and put the 'types' object in to my model object. But for some request, such like searh or listAll. I don't want to this method be called. How can I filter some request for the method which has @ModelAttribute("types") on it?

```

@RequestMapping(value = "/search", method = RequestMethod.GET)
public String search(Model model) {
    List<User> result = userService.findAll();
    model.add("result");
    return "index";
}

```

I don't want search request call populateTypes first since I don't need populateTypes in my search view.

4

2 回答 2

4

如果populateTypes所有视图都不需要参考数据,则最好删除带注释的populateTypes()方法,并在需要时添加数据 - 通过将其添加到需要它ModelAndView的特定@RequestMapping方法的 s 中。

因此,如果您有一个@RequestMapping调用的方法,该方法foo()的视图确实需要数据,那么您可以执行以下操作:

@RequestMapping(value = "/foo", method = RequestMethod.GET)
public ModelAndView foo() {
    ModelAndView modelAndView = new ModelAndView("fooView");
    modelAndView.addObject("types", typeRepository.findAll());
    return modelAndView;
}
于 2013-05-29T08:01:23.430 回答
-1

如果您不返回视图,则应使用 @ResponseBody

于 2013-08-06T01:35:11.803 回答