将地图数据从servlet传递到jsp选择标记

时间:2014-12-29 15:46:16

标签: jsp servlets jstl

我无法看到以下代码有什么问题,它没有将任何数据从Map传递给jsp select标签选项。

继承我的模特课:

@Entity
@Table(name="customer")
public class Customer implements Serializable {

@Id
@SequenceGenerator(name = "my_seq", sequenceName = "seq1", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")
public int id;
public String customerType;

@ElementCollection
@Column(name = "customerType")
public Map<String, String> customerTypes;


public Customer() {}


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}


  public void setCustomerTypes(Map<String, String> customerTypes) {

  this.customerTypes = customerTypes;

  }

  public Map<String, String> getCustomerTypes() {

      return customerTypes;
   }


public String getCustomerType() {
    return customerType;
}


public void setCustomerType(String customerType) {



    this.customerType = customerType;
}


}

Servlet,我在这里添加地图中的选择选项并将它们传递给jsp页面

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


    showForm(request, response);

}
private void showForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    Map<String, String> map = new LinkedHashMap<String, String>();

       map.put("", " ");
       map.put("customerType.private", "Private");
       map.put("customerType.corporate", "Corporate");

    Customer customer = new Customer();

    customer.setCustomerTypes(map);
    request.setAttribute("customerType", customer);

    request.getRequestDispatcher("/Add.jsp").forward(request, response);    
}

和jsp部分:

  <select id="customerTypeSelect" name="customerType" >

   <c:forEach var="entry" items="${customer.customerTypes}">

    <c:set var="selected" value="" scope="request"/>

      <c:if test="${entry.key == customer.customerType}">
      <c:set var="selected" value="selected=\"selected\"" scope="request"/>
    </c:if>
    <option value="${entry.key}" ${selected}>${entry.value}</option>
  </c:forEach>

 </select>

1 个答案:

答案 0 :(得分:2)

尝试更改代码,如下所示

您正在设置customer对象,如下所示

 request.setAttribute("customerType", customer);

此处的密钥为customerType,您使用了customer

1。)所以用户customerType作为jsp的密钥,如下所示

<select id="customerTypeSelect" name="customerType" >

   <c:forEach var="entry" items="${customerType.customerTypes}">

    <c:set var="selected" value="" scope="request"/>

      <c:if test="${entry.key == customerType.customerType}">
      <c:set var="selected" value="selected=\"selected\"" scope="request"/>
    </c:if>
    <option value="${entry.key}" ${selected}>${entry.value}</option>
  </c:forEach>

 </select>

2。)在你的servlet中执行以下操作

request.setAttribute("customer", customer);