【问题标题】:How to map a complex structure in jsp view to a model object in spring MVC如何将jsp视图中的复杂结构映射到spring MVC中的模型对象
【发布时间】:2014-01-16 09:45:58
【问题描述】:

我是第一次使用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
}

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

@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());
}

在我的 sn-p.jsp 中,我想显示带有比例的 sn-p 句子,并在保存时将带有句子和比例的 sn-p 传递给控制器​​进行存储:

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

我想我必须找到使用路径属性的正确方法,但我想不通。

【问题讨论】:

    标签: java spring jsp spring-mvc jstl


    【解决方案1】:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-06
      相关资源
      最近更新 更多