Spring 从视图中的ModelAttribute方法检索数据

Spring 从视图中的ModelAttribute方法检索数据,spring,spring-mvc,controller,modelattribute,Spring,Spring Mvc,Controller,Modelattribute,在我当前的spring项目中,我有一个这样的通用控制器: public class basicController<E> { @Autowired private basicService<E> serv; protected Class<?> clazz; public basicController(Class<?> clazz) { this.clazz = clazz; } ... } @Mod

在我当前的spring项目中,我有一个这样的通用控制器:

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

  protected Class<?> clazz;

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

  ...

}
  @ModelAttribute("lista")
  public List<E> populateList() {
    return serv.lista();
  }
此页面在控制器中映射,方法如下:

通用控制器

  @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";
  }
主控制器(包括公共视图映射等)


有人知道这一点吗?

@modeldattribute在您的控制器方法启动之前启动,我相信一旦您的方法运行就会消失。因此,视图中不再有对象,它的行为更像@RequestParam


但是,如果您使用的是较新版本的Spring(我相信是4+),那么可以尝试添加@SessionAttributes(“lista”)。但是,您必须小心确保关闭会话属性。最后,做这个家伙做的事-。

好的,我只是测试并验证使用ModelAttribute方法中的值不需要额外的配置。因此,我只是在控制器中添加了如下方法:

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

  @ModelAttribute("classe")
  public String getName() {
    return clazz.getSimpleName();
  }
@modeldattribute(“lista”)
公共列表populateListPagina(){
返回serv.lista();
}
@ModelAttribute(“classe”)
公共字符串getName(){
返回clazz.getSimpleName();
}
当我访问任何映射视图时,我可以用我喜欢的方式使用此方法返回的值:

  <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>


你知道变量
团队在这里做了什么吗?控制器:和视图:。这就是我希望实现的。模型的全部目的是供视图使用。您的答案可能是错误的。
lista
可以通过视图访问。您是否遇到任何问题?@zeroflagL是的,当我运行项目并访问视图时,
在最后一页中不生成任何选项,例如如果
lista
为空,即使它不是空的。您的控制器是否继承自
basicController
?我不确定SpringMVC是否处理继承的注释。因此可能不会调用
populateList
。@zeroflagL是的,控制器继承自
basicController
  @ModelAttribute("lista")
  public List<E> populateListPagina() {
    return serv.lista();
  }

  @ModelAttribute("classe")
  public String getName() {
    return clazz.getSimpleName();
  }
  <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>