使用数据库信息填充JSP下拉列表 [英] Populate JSP dropdown with database info

查看:148
本文介绍了使用数据库信息填充JSP下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据库表中填充JSP下拉列表。

I'm trying to populate a JSP dropdown from a database table.

这是创建数组并用数据库信息填充它的代码:

Here's the code that will create the array and fill it with the database info:

// 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;
}

如何从我的JSP调用该类并填充下拉列表?

How do I call that class from my JSP and populate the dropdown?

推荐答案

我建议尽量避免混合显示和型号代码。将所有html保存在jsp页面中,并创建提供所需信息的模型支持对象。例如,假设您有一个包含对象列表的简单Java类:

I would suggest trying to stay away from mixing the display and model code. Keep all of your html in the jsp page and create model backing objects that provide the information you need. For example, let's say you have a simple Java class that has a list of objects:

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;
    }
}

getItems方法构造的方式无关紧要列表它正在返回。要使用JSTL在JSP页面中显示这些项,您将执行以下操作:

It doesn't matter how the getItems method constructs the list that it is returning. To display these items in the JSP Page using JSTL you would do the following:

<%@ 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>

而不是使用useBean,forEach循环中使用的项集合也可以来自会话或请求对象。

Instead of using useBean the items collection used in the forEach loop could also come from the session or a request object.

此链接也有很好的建议:
http://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/

This link also has good advice: http://java.sun.com/developer/technicalArticles/javaserverpages/servlets_jsp/

这篇关于使用数据库信息填充JSP下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆