从 Bean 类型的数组列表填充 JSP 中的下拉列表 [英] Populating a drop down list in JSP from a Array List of Bean type

查看:34
本文介绍了从 Bean 类型的数组列表填充 JSP 中的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Java EE 项目中,我有以下 Servlet:

In my Java EE project I have the following Servlet:

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * Servlet implementation class TitlePopulatorServlet
 */
@WebServlet("/TitlePopulatorServlet")
public class TitlePopulatorServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TitlePopulatorServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("Inside doGet()!");

        ArrayList<BeanTitle> bt=new ArrayList<BeanTitle>();

        java.io.PrintWriter out = response.getWriter();
        response.setContentType("text/html"); 

        Connection conn=null;


        try {
            /* get the DataSource from using the JNDI name */
            Class.forName("com.mysql.jdbc.Driver");
            InitialContext ctx = new InitialContext();
            DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/Test");

            //Create connection and then continue as usual other JDBC calls 
            conn=ds.getConnection();
            System.out.println("\nConnection Successful in TitlePopulatorServlet !");
            Statement s= conn.createStatement();
            ResultSet rs=s.executeQuery("SELECT * FROM story");

            while (rs.next() ) 
            {
                BeanTitle b = new BeanTitle();
                b.setBtitle(rs.getString(1));
                bt.add(b);
            }

        } catch (Exception e){
            out.println("Failed!"+ e);
        }


            request.setAttribute("bt", bt);                                                         
            request.getRequestDispatcher("/StoryTitlePage.jsp").forward(request,response);


    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



    }
}

BeanTitle 如下:

The BeanTitle is as follows:

public class BeanTitle 
{
    private String btitle;

    public String getBtitle() {
        return btitle;
    }

    public void setBtitle(String btitle) {
        this.btitle = btitle;
    }
}

和JSP页面(StoryTitlePage.jsp")如下:

And the JSP page ("StoryTitlePage.jsp") is as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


<html>
<head>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="storylist" class="serv.TitlePopulatorServlet" scope="request" />

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Story Title Page</title>
</head>
<body>

<form action="/ReportData/DisplayReport" method="post" >

        Please select an element: 

        <select id="selectedRecord" name="selectedRecord">

            <c:forEach var="item" items=${storylist.bt} >
                <option>${item.tarr}</option>
            </c:forEach>
        </select>

        <input type="submit" value="Submit"> 

    </form>

</body>
</html>

但是当我在服务器上启动 TitlePopulatorServlet 时它不起作用.我在迭代/EL 中哪里出错了?

But when I launch the TitlePopulatorServlet on the server it doesn't work. Where am I going wrong in the iteration/EL?

推荐答案

servlet 将列表存储在请求中,在名为bt"的属性下.所以它已经在那里,在请求中.没有必要做

The servlet store the list in the request, under the attribute named "bt". So it's already there, in the request. There is no need to do

<jsp:useBean id="storylist" class="serv.TitlePopulatorServlet" scope="request" />

那只会创建一个新的 servlet 实例,这没有任何意义.bt 是请求属性.它不是 servlet 的属性.所以使用 ${storylist.bt} 也没有任何意义.

That will only create a new instance of your servlet, which doesn't make any sense. and bt is a request attribute. It's not a property of the servlet. So using ${storylist.bt} doesn't make any sense either.

你想遍历bt的元素,所以你只需要

You want to iterate over the elements of bt, so all you need is

<c:forEach var="item" items="${bt}">

最后,bt 的每一项都是 BeanTitle 类型.而你正在做

Finally, each item of bt is of type BeanTitle. And you're doing

${item.tarr}

这相当于调用

beanTitle.getTarr()

并且在 BeanTitle 中没有 tarr 属性.唯一的属性是 btitle(因为该类的唯一 getter 名为 getBTitle()).

And there is no tarr property in BeanTitle. The only property is btitle (since the only getter of the class is named getBTitle()).

所以你必须使用的是

${item.btitle}

你的名字很糟糕,只会让你更加困惑.你为什么不使用真实的词来命名你的类和属性?举个例子

Your naming is awful, and that only makes you more confused. Why don't you use real words to name your classes and properties? Like for example

public class Book {
    private String title;

    public String getTitle() 

    ...
}

这篇关于从 Bean 类型的数组列表填充 JSP 中的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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