在Spring MVC中填充Select下拉列表

时间:2016-06-30 20:47:02

标签: spring-mvc select arraylist

这是我使用arraylist值填充select标签的代码

首先Dao看起来像

     public List<Student> getStudents() {

    String hql = "FROM Student";
    Session session = HibernateUtil.getSessionFactory().openSession();
    Query query = session.createQuery(hql);
    List queryResults = query.list();
    List<Student> result = new ArrayList<Student>();

    Iterator it = queryResults.iterator();
    while (it.hasNext()) {
        Student student = (Student) it.next();
        result.add(student);
    }
    session.close();
    return result;
}

和控制器

   public ModelAndView select() {

    List<Student> students = service.getStudents();
    ModelAndView modelAndView = new ModelAndView("select",
            "students", students);

    return modelAndView;
}

和jsp页面

     <body>
   <select>
  <c:forEach var="student" items="${students}">
    <option value="${student.id}">${student.name}</option>
  </c:forEach>
</select>
   </body>

这是最好的方法吗?

1 个答案:

答案 0 :(得分:0)

这是解决方案。

     <body>
         <form:form ... >
           <form:select path="" items="${students}" itemLabel="name" itemValue="id"/>
         </form:form>   
     </body>