How to disable some request calling @ModelAttribute method in the same controller?

StackOverflow https://stackoverflow.com/questions/16769005

  •  30-05-2022
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

If the populateTypes reference data is not required for all views you may be best to remove the annotated populateTypes() method and just add the data when it is required - by adding it to the ModelAndViews of the specific @RequestMapping methods that need it.

So if you have a @RequestMapping method called foo() that has a view that does need the data, then you could do something like:

@RequestMapping(value = "/foo", method = RequestMethod.GET)
public ModelAndView foo() {
    ModelAndView modelAndView = new ModelAndView("fooView");
    modelAndView.addObject("types", typeRepository.findAll());
    return modelAndView;
}

Outras dicas

You should use @ResponseBody if you are not returning a view

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top