将List设置为servlet中的属性并在JSP

时间:2016-03-21 15:25:40

标签: java arrays list jsp servlets

我试图在servlet中为属性设置一个整数列表,然后在重定向的JSP页面中检索列表。

我查看过以前的答案herehere以及其他答案,我的代码与我的答案相似。显然我做错了但我看不出问题。

请注意,在servlet中正确设置了“accomList”,因为我通过将列表输出到servlet中的控制台来测试它。它被设置为[1,2,3,4,21]。

“AccomSearch.java”Servlet

session.setAttribute("accomList",accomList);//set list as attribute
getServletConfig().getServletContext().getRequestDispatcher("/viewAccom.jsp").forward(request,response); // redirect to jsp page

^将“accomList”列表设置为属性并将用户重定向到jsp页面。

“viewAccom.jsp”JSP页面

 <%
           List<Integer> accomList = new ArrayList<>();
           accomList = (List<Integer>) request.getAttribute("accomList");
           if (accomList==null){
              out.println("accomList is null, Why is the list null?");
           }else{
              for (int i = 0; i < accomList.size(); i++) {
                   out.println(Integer.toString(accomList.get(i)));
               }
           }

        %>

^尝试检索“accomList”属性,将其强制转换为列表,然后显示它。

运行代码时,JSP页面中的“accomList”变量返回“Null”。所以字符串“accomList为null,为什么列表为空?”显示在浏览器中。这不是预期的。

我的猜测是我要么错误地设置或检索属性。提前感谢您提供的任何帮助。

另外,这是我的第一个stackOverflow问题,所以如果我在错误的区域发布了这个问题,或者格式错误等,请告诉我。

2 个答案:

答案 0 :(得分:0)

您必须在List中设置request而不是session

request.setAttribute("accomList",accomList);//set list as attribute

或者您将jsp代码更改为:

accomList = (List<Integer>) request.getSession().getAttribute("accomList");

因为目前您已将List设置为用户session

答案 1 :(得分:0)

您也可以使用请求对象代替会话,如下例所示。

-> student.java

 List<String> studentNameList=new ArrayList<>();
   studentNameList.add("Rohan");
   studentNameList.add("Arjun");
   request.setAttribute("studentNameList",studentNameList);

-> student.jsp

 List<String> studentNameList= (List<String>) request.getAttribute("studentNameList");
相关问题