【问题标题】:Creating collection fields JSP Java创建集合字段 JSP Java
【发布时间】:2013-04-08 16:01:38
【问题描述】:

我正在使用 Spring 框架、JSP 页面来显示和验证表单。

我来自 PHP 世界,其中像 somefield[] 这样的字段名称由数组表示(Java 中的 ArrayList)。我想从表单的输入中获取字符串集合。

我已经定义了private List<String> waypoints;,它工作得很好,但在 JSP 中我必须保留符号 somefield[0]somefield[1]somefield[2] 等...

问题:
这带来不便,导致该序列只有两个字段:somefield[0]somefield[9] 实际上生成 10 个字段。

显示现有字段值的简单代码。

<c:forEach items="${routeAddInput.waypoints}" var="waypoint" varStatus="status">
    <input name="waypoints[${status.index}]" type="text" value="${waypoint}"  placeholder="Enter name here" />
</c:forEach>

问题:
是否可以由用户(在 UI 中)动态生成字段,其中索引无关紧要?如果用户添加该字段,我可以简单地计算下一个索引,但如果用户删除该字段,则列表中有一个间隙。

问题背景:
我的 Servlet 方法来验证表单:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String step1ValidateForm(
    @ModelAttribute("routeAddInput")
    @Valid RouteAddInput form,
    BindingResult result, ModelMap model) {

    if (result.hasErrors()) {
        return "route/add";
    }

    return "redirect:addDetails";
}

要验证的表单:

public class RouteAddInput {
    @NotNull
    @Length(min=1)
    private String locationSource;

    @NotNull
    @Length(min=1)
    private String locationDestination;

    private List<String> waypoints;

  public RouteAddInput() {
    setLocationSource("");
    setLocationDestination("");
    waypointsCoords = new ArrayList<String>();
  }

    public String getLocationSource() {
        return locationSource;
    }

    public void setLocationSource(String locationSource) {
        this.locationSource = locationSource;
    }

    public String getLocationDestination() {
        return locationDestination;
    }

    public void setLocationDestination(String locationDestination) {
        this.locationDestination = locationDestination;
    }

    public List<String> getWaypoints() {
        return waypoints;
    }

    public void setWaypoints(List<String> waypoints) {
        this.waypoints = waypoints;
    }
}

【问题讨论】:

    标签: java spring jsp servlets


    【解决方案1】:

    我已经设法解决了这个问题。关键是使用LinkedHashMap 而不是ArrayList

    LinkedHashMap 保留值顺序并允许根据需要保留索引。特别是整数。

    所以在表单类中这个字段将是: 私有 HashMap 路点;

    还有JSP的区别forEach

    <c:forEach items="${routeAddInput.waypoints}" var="waypoint">
      <input name="waypoints['${waypoint.key}']" type="text" value="${waypoint.value}"  placeholder="Enter name here" />
    </c:forEach>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 2020-03-25
      • 2012-10-03
      • 2013-03-03
      相关资源
      最近更新 更多