WEB开发网
开发学院WEB开发Jsp jstl实现在jsp中动态添加下拉列表项 阅读

jstl实现在jsp中动态添加下拉列表项

 2013-04-16 15:38:22 来源:WEB开发网   
核心提示:使用下面这个jsp的前,你需要写一个Stu类,jstl实现在jsp中动态添加下拉列表项,生成set和get方法,Public Class Stu{ private int id; private String name; public void setId(int id){ this.id

使用下面这个jsp的前,你需要写一个Stu类,生成set和get方法。

Public Class Stu{
    private int id;
    private String name;

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

    public int getId(){
       return this.id;
    }

    public void setName(String name){
       this.name=name;
    }

    public String getName(){
       return this.name;
    }
}

写个简单的servlet

public class gotoMall extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		ArrayList<Stu> stus=new ArrayList<Stu>();
		Stu stu1=new Stu();
		stu1.setId(1);
		stu1.setName("aa");
		stu2.setId(2);
		stu2.setName("bb");
		stus.add(stu1);
		stus.add(stu2);
		request.setAttribute("stus", stus);
		request.getRequestDispatcher("/WEB-INF/admin/my.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doGet(request, response);
	}

}

my.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!-- 引入jstl标签库 -->
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <script type="text/javascript" language="javascript" src="js/js_delete.js" charset="gbk"></script>
    <link href="css/main.css" rel="stylesheet" type="text/css" />   
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>My JSP page</title>
  </head>
  
  <body>
  LIST:<select>
  	<!-- 前提是已经把stus这个list放到了request.attribute中. 在servlet或action中  request.setAttribute(stus); -->
  	<c:forEach items="${stus}" var="stu">
  		<!-- Stu类中必须有set和get方法 -->
     	<option>${stu.name}</option>
     </c:forEach>
  </select>
  </body>
</html>

Tags:jstl 实现 jsp

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接