Can*_*o63 9 java jsp jstl jdbc
我正在尝试从数据库表填充JSP下拉列表.
这是将创建数组并用数据库信息填充它的代码:
// this will create my array
public static ArrayList<DropDownBrands> getBrandsMakes() {
ArrayList<DropDownBrands> arrayBrandsMake = new ArrayList<DropDownBrands>();
while (rs.next()) {
arrayBrandsMake.add(loadOB(rs));
}
return arrayBrandsMake;
}
// this will load my array object
private static DropDownBrands loadOB(ResultSet rs) throws SQLException {
DropDownBrands OB = new DropDownBrands();
OB.setBrands("BRAN");
return OB;
}
Run Code Online (Sandbox Code Playgroud)
如何从我的JSP调用该类并填充下拉列表?
Cas*_*sey 11
我建议尽量避免混合显示和模型代码.将所有html保存在jsp页面中,并创建提供所需信息的模型支持对象.例如,假设您有一个包含对象列表的简单Java类:
package com.example;
import java.util.ArrayList;
import java.util.List;
public class ListBean {
public List<String> getItems() {
List<String> list = new ArrayList<String>();
list.add("Thing1");
list.add("Thing2");
list.add("Thing3");
return list;
}
}
Run Code Online (Sandbox Code Playgroud)
getItems方法如何构造它返回的列表并不重要.要使用JSTL在JSP页面中显示这些项,您将执行以下操作:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="obj" class="com.example.ListBean" scope="page"/>
<select>
<c:forEach var="item" items="${obj.items}">
<option>${item}</option>
</c:forEach>
</select>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
而不是使用useBean,forEach循环中使用的项集合也可以来自会话或请求对象.
这个链接也有很好的建议:http: //java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/