繁体   English   中英

如何将jsp视图中的复杂结构映射到spring MVC中的模型对象

[英]How to map a complex structure in jsp view to a model object in spring MVC

我第一次使用spring mvc而且我正在尝试在jsp中显示和编辑一个结构。

我有一个类Snippet,它包含Sentence类型的对象列表:

public class Snippet {
  private int id;
  private List<Sentence> sentences;
  // getters, setters, default constructor
}

public class Sentence {
  private int id;
  private int scale;
  private String text;
  // getters, setters, default constructor
}

在我的控制器中,我提供了一个新的代码片段进行编辑,当用户点击“保存”将其存储到我的数据库中,然后返回另一个。 目前,片段的句子列表为空:

@RequestMapping("/snippet")
public ModelAndView getSnippet() {
  return new ModelAndView("snippet", "snippet", snippetService.getSnippet());
}

@RequestMapping("/save")
public ModelAndView saveSnippet(@ModelAttribute Snippet snippet) {
  if(snippet != null && snippet.getSentences() != null && !snippet.getSentences().isEmpty()) {
    snippetService.updateSnippet(snippet);
  }
  return new ModelAndView("snippet", "snippet", snippetService.getSnippet());
}

在我的snippet.jsp中,我想用它们的比例显示片段句子,并在保存时,将带有句子和缩放的片段传递给控制器​​进行存储:

<form:form method="post" action="save" modelAttribute="snippet">
  ...
  <c:forEach var="sentence" items="${snippet.sentences}">
    <tr>
      <td>${sentence.id}</td>
      <td>${sentence.text}</td>
      <td><input type="range" name="sentence.scale" value="${sentence.scale}"
         path="sentence.scale" min="0" max="5" /></td>
    </tr>
  </c:forEach>
  <tr>
    <td colspan="4"><input type="submit" value="Save" /></td>
  </tr>

我想我必须找到使用path属性的正确方法,但我无法弄明白。

JSTL c:forEach标记提供属性varStatus ,它将循环状态公开给指定的变量。 引用varStatusindex以获取当前循环的索引,并使用该索引指定要绑定或显示的集合项的索引。

<c:forEach var="sentence" items="${snippet.sentences}" varStatus="i">
    <tr>
      <td>${sentence.id}</td>
      <td>${sentence.text}</td>
      <td>
        <form:input type="range" 
          name="snippet.sentences[${i.index}].scale" 
          path="sentences[${i.index}].scale" 
          min="0" max="5" 
          /></td>
    </tr>
  </c:forEach>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM