NMLcygni
NMLcygni

Reputation: 71

Spring: Using GET parameters inside of a ModelAttribute

I'm trying to use GET parameters to alter the Model Attribute that's creates a table like object returned to the view. To be specific: I want to send the name of a column as a GET parameter and highlight that column by coloring it differently. My current setup looks like this:

private String highlightedCol;

  @ModelAttribute("model")
  public Model populateModel() {
    Model model = new Model();
    generateModel();
    //Use Highlighted Col
    return model;
  }

  @RequestMapping("/index")
  public String getIndex(@RequestParam(value="ts", required = false, defaultValue="") String col) {
    highlightedCol = col;
    return "index";
  }

I'm having trouble using the "col" parameter in the ModelAttribute because the ModelAttribute gets executed before the RequestMapping. How would i go about using the GET parameter for my Model?

Upvotes: 0

Views: 1135

Answers (2)

NMLcygni
NMLcygni

Reputation: 71

After asking a colleague about my problem he came up with this answer: I got rid of the @ModelAttribute Annotation and changed the getIndex method to this:

@RequestMapping("/index")
  public ModelAndView getIndex(@RequestParam(value="ts", required = false, defaultValue="") String col) {
    highlightedCol = col;

    Map<String, Object> model = new HashMap<>();
    model.put("model", populateModel());

    return new ModelAndView("index", model);
  }

This way the populateModel method is no longer executed before the getIndex method, allowing me to set the highlightedCol before creating the model, where i need that field.

Upvotes: 0

varman
varman

Reputation: 8894

You can simply use method=RequestMethod.GET . Beware in GET or POST method. Make sure if you want t read/get date, use GET. If you want to use insert data, use POST

@RequestMapping(value="/your_url", method=RequestMethod.GET)
@ModelAttribute("model")

Upvotes: 1

Related Questions