将ArrayList从servlet传递给JSP

时间:2013-11-04 11:39:56

标签: java jsp servlets arraylist

我正在尝试将包含servlet对象的ArrayList传递给JSP。但是

Servlet文件:

request.setAttribute("servletName", categoryList); //categorylist is an arraylist      contains object of class category  
getServletConfig().getServletContext().getRequestDispatcher("/GetCategory.jsp").forward(request,response);

JSP文件:

//category class    
<% Category category = new Category();
//creating arraylist object of type category class
ArrayList<Category> list = ArrayList<Category>();
//storing passed value from jsp
list = request.getAttribute("servletName");

for(int i = 0; i < list.size(); i++) {

category = list.get(i);

out.println( category.getId());

out.println(category.getName());

out.println(category.getMainCategoryId() );
}
%>

6 个答案:

答案 0 :(得分:16)

在servlet代码中,使用指令request.setAttribute("servletName", categoryList),将列表保存在请求对象中,并使用名称“servletName”进行引用。
顺便说一句,使用名称“servletName”作为列表是相当混乱的,也许最好称之为“列表”或类似的东西:request.setAttribute("list", categoryList)
无论如何,假设您不更改serlvet代码,并使用名称“servletName”存储列表。当您到达JSP时,有必要从请求中检索列表,为此您只需要request.getAttribute(...)方法。

<%  
// retrieve your list from the request, with casting 
ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("servletName");

// print the information about every category of the list
for(Category category : list) {
    out.println(category.getId());
    out.println(category.getName());
    out.println(category.getMainCategoryId());
}
%>

答案 1 :(得分:5)

request.getAttribute("servletName")方法会返回您需要投放到Object的{​​{1}}

ArrayList

答案 2 :(得分:1)

<html>
    <%

        ArrayList<Actor> list = new ArrayList<Actor>();
        list = (ArrayList<Actor>) request.getAttribute("actors");
    %>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Actor</title>
</head>

<body>

    <h2>This is Actor Class</h2>
    <table>
        <thead>
            <tr>
                <th>Id</th>
                <th>First Name</th>
                <th>Last Name</th>
            </tr>
        </thead>
        <tbody>
            <% for(int i = 0; i < list.size(); i++) {
                Actor actor = new Actor();
                actor = list.get(i);
                //out.println(actor.getId());
                //out.println(actor.getFirstname());
                //out.println(actor.getLastname());
            %>


            <tr>
                <td><%=actor.getId()%></td>
                <td><%=actor.getFirstname()%></td>
                <td><%=actor.getLastname()%></td>
               </tr>
            <%
            };
            %>
        </tbody>
    </table>

</body>

答案 3 :(得分:0)

可能的错误是......
1.您从会话中的servelt设置数组列表,而不是请求中的数组列表 2.您设置的数组为空 3.你重定向页面而不是转发它。

你也不应该在jsp中初始化listcategory。试试这个。

for(Category cx: ((ArrayList<Category>)request.getAttribute("servletName"))) {

out.println( cx.getId());

out.println(cx.getName());

out.println(cx.getMainCategoryId() );
}

答案 4 :(得分:0)

public class myActorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String name;
    private String user;
    private String pass;
    private String given_table;
    private String tid;
    private String firstname;
    private String lastname;
    private String action;

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

        response.setContentType("text/html");

        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        PrintWriter out = response.getWriter();
        name = request.getParameter("screenName");
        user = request.getParameter("username");
        pass = request.getParameter("password");
        tid = request.getParameter("tid");
        firstname = request.getParameter("firstname");
        lastname = request.getParameter("lastname");
        action = request.getParameter("action");
        given_table = request.getParameter("tableName");

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet JDBC</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello, " + name + " </h1>");
        out.println("<h1>Servlet JDBC</h1>");

        /////////////////////////
        // init connection object
        String sqlSelect = "SELECT * FROM `" + given_table + "`";
        String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
        String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
        String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

        //////////////////////////////////////////////////////////
        out.println(
                "<p>Reading Table Data...Pass to JSP File...Okay<p>");

        ArrayList<Actor> list = new ArrayList<Actor>();
        // connecting to database
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sqlSelect);
            // displaying records

            while (rs.next()) {
                Actor actor = new Actor();
                actor.setId(rs.getInt("id"));
                actor.setLastname(rs.getString("lastname"));
                actor.setFirstname(rs.getString("firstname"));
                list.add(actor);
            }
            request.setAttribute("actors", list);
            RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
            view.forward(request, response);

        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
        } catch (ClassNotFoundException e) {
            throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException e) {
            }
        }
        out.println("</body></html>");

        out.close();
    }

}

答案 5 :(得分:-2)

此处列出请求request.setAttribute("List",list);中设置的属性名称 和ArrayList list=new ArrayList();

<%

ArrayList<Category> a=(ArrayList<Category>)request.getAttribute("List");

out.print(a);

for(int i=0;i<a.size();i++)

{
    out.println(a.get(i));

}


%>