尝试将列表从servlet传递给jsp但打印为null

时间:2014-06-11 18:19:04

标签: java jsp servlets

我正在尝试将ArrayList个对象从servlet传递到jsp文件,但是当我尝试打印它时,它什么都不打印。我使用了来自jsp的类似帖子的确切行...有人可以帮助我,因为我之前从未使用过jsp。 我们的想法是使用dom解析器遍历xml文件,然后将其元素打印到特定表单的html表中。我的java代码成功收集了所有元素,并将它们存储在一个列表中,我想在jsp中传递给表格中的格式...

SERVLET CODE (丢失的部分导致它很大):

import all the needed libraries

public class MyServlet extends HttpServlet {  

    private static xml_obj obj = null;
    public static ArrayList<xml_obj> objList = new ArrayList<xml_obj>();

    public static void main(String[] args){
        try {
            Start(); //starting the methods for the xml traversal and creates the list
            //System.out.println("AA"+objList.get(1).getName());
        }
        catch(Exception e) {
            e.getMessage();
        }
    }
    public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {  
        ArrayList list = getList();
        //System.out.println(objList.get(1).getName());
        request.setAttribute ("Xml_objList", objList );  
        RequestDispatcher view = request.getRequestDispatcher("DomNav.jsp");  
        view.forward (request,response);          
    }       
    static void Start(){

                /*..........code missing.............*/
            myDOMTreeProc dtp = new myDOMTreeProc();
            dtp.processLvl(ListOfCh, 0); //processLvl -> method in myDOMTreeProc

    }

    public static ArrayList<xml_obj> getList() {
          return objList;
       }
}


class myDOMTreeProc {
 /*........DOM XML TRAVERSE.......*/
}

class attribute {
private String Name;
private String Value;

 /*.............setters/getters.......*/

}

class xml_obj {
   public int Lvl;
   private String Name;
   private String Value;
   private String Parent;
   private ArrayList<attribute> attributes=null;
   /*.............setters/getters.......*/

}

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

<%@page import="java.util.*" %>
<!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>Expression Language Example</title>
</head>
<body>
<h1>TEST JSP</h1>
<% ArrayList list = (ArrayList) request.getAttribute("Xml_objList"); %>
 <c:forEach var="item" items="${Xml_objList}">
          ${item.Lvl}
    </c:forEach>
</body>
</html>

列表是正确的我测试了它。我认为问题是当我在jsp中传递它时。

1 个答案:

答案 0 :(得分:1)

关注Java Naming convention,一切都会正常。只需将int Lvl替换为int lvl;

即可

JSP:

<c:forEach var="item" items="${Xml_objList}">
      ${item.lvl}
</c:forEach>

您可以尝试${item.lvl}${item.getLvl()}

而不是${item['lvl']}