Search code examples
springspring-mvccontrollermodelattribute

Retrieve data from ModelAttribute method in the view


In my current spring project, I have a generic controller like this:

public class basicController<E> {
  @Autowired
  private basicService<E> serv;

  protected Class<?> clazz;

  public basicController(Class<?> clazz) {
    this.clazz = clazz;
  }

  ...

}

with a method like this:

  @ModelAttribute("lista")
  public List<E> populateList() {
    return serv.lista();
  }

I wonder if it's possible use the value for lista in a structure like that (in the html page):

<select class="form-control" th:name="...">
    <option th:each="opt : ${lista}" th:value="${opt.getId()}"><span th:text="${opt}"/>
    </option>
</select>

this page is mapped in the controllers with methods like that:

generic controller

  @RequestMapping(value = "cadastra")
  @PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)")
  @Menu(label = "cadastra")
  public String cadastra(Model model) throws Exception {
    model.addAttribute("command", serv.newObject());
    return "private/cadastra";
  }

home controller (contains mappings for public views, among others things)

  @RequestMapping(value = "/settings")
  public String settings(Model model) throws Exception {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    model.addAttribute("usuario", auth.getName());
    model.addAttribute("menu", MenuList.index());
    model.addAttribute("settings", MenuList.settings());
    return "private/settings";
  }

  @RequestMapping(value = "/profile")
  public String profile(Model model) throws Exception {
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    model.addAttribute("usuario", auth.getName());
    model.addAttribute("menu", MenuList.index());
    model.addAttribute("command", usuario(auth.getName()));
    return "private/profile";
  }

Anyone have any idea about this?


Solution

  • Ok, I just test and verify no extra configuration is needed for use the value from a ModelAttribute method. So, I just add methods like this in my controller:

      @ModelAttribute("lista")
      public List<E> populateListPagina() {
        return serv.lista();
      }
    
      @ModelAttribute("classe")
      public String getName() {
        return clazz.getSimpleName();
      }
    

    and when I access any mapped view, I can use the value returned by this method in the way I like:

      <tbody class="content">
        <tr th:each="item : ${lista}">
          <th></th>
          <th th:each="coluna : ${campos}" th:text="${item[coluna]}"></th>
          <th>
            <div class="btn-group" role="group" aria-label="menu_item">
              <button th:each="btn : ${menu_item}" type="button" class="btn btn-default link" th:attr="data-href=@{/__${classe}__/__${btn}__/__${item.getId()}__}" th:text="${btn}"></button>
            </div>
          </th>
        </tr>
      </tbody>