c:forEach实现动态select标签

c:forEach实现动态select标签

<c:forEach>标签是更加通用的标签,因为它迭代一个集合中的对象。

<c:forTokens>标签通过指定分隔符将字符串分隔为一个数组然后迭代它们。

  • JavaBean

    public class SelectData {
    	private String	key;	// 键
    	private String	value;	// 值
    							
    	public SelectData(String key, String value) {
    		super();
    		this.key = key;
    		this.value = value;
    	}
    	
    	public String getKey() {
    		return key;
    	}
    	
    	public void setKey(String key) {
    		this.key = key;
    	}
    	
    	public String getValue() {
    		return value;
    	}
    	
    	public void setValue(String value) {
    		this.value = value;
    	}
    	
    }
    
  • Servlet

    public class ServletDemo3 extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
          List<SelectData> list = new ArrayList<SelectData>();
    		proList.add(new SelectData("1", "北京"));
    		proList.add(new SelectData("2", "上海"));
    		proList.add(new SelectData("3", "广州"));
    		proList.add(new SelectData("4", "深圳"));
    		proList.add(new SelectData("5", "河北"));
    		proList.add(new SelectData("6", "河南"));
    		proList.add(new SelectData("7", "山西"));
    		proList.add(new SelectData("8", "山东"));
    		proList.add(new SelectData("9", "江苏"));
    		proList.add(new SelectData("10", "浙江"));
            req.setAttribute("proList",proList);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            doGet(req,resp);
        }
    
    }
    
  • 前端核心代码

<select name="sel_Province">
    <c:forEach items="${proList}" var="user" varStatus="status">
            <option value="${user.key}">${list.value}</option>
    </c:forEach>
</select>
posted @ 2021-03-04 11:16  崔安兵  阅读(1042)  评论(0编辑  收藏  举报