简体   繁体   English

如何使用会话将ArrayList从一个jsp传递到另一个

[英]How to pass an ArrayList from one jsp to another using session

I'm trying to pass an ArrayList from handle.jsp to main.jsp, but it doesn't let me do it. 我正在尝试将一个ArrayList从handle.jsp传递给main.jsp,但它不允许我这样做。 It keeps saying "Type mismatch: cannot convert from Object to ArrayList". 它一直说“类型不匹配:无法从Object转换为ArrayList”。

main.jsp: main.jsp中:

<%@ page import="java.util.ArrayList" %>
<html>
<body>
    <h1>Hobby Manager</h1>
<%

        ArrayList<String> hobbies = session.getAttribute("hobbies");

        out.println(hobbies.size());

        out.println(session.getAttribute("hobbies"));
%>

    <h2>Add new hobby!</h2>

    <FORM action="handleAddHobby.jsp" method="get">
            What new hobby are you wishing to add? <INPUT TYPE=text name=hobbyName /> <br/>

            <INPUT TYPE=submit name=addHobby value="Add Hobby" />

    </FORM>

</body>
</html>

handle.jsp: handle.jsp:

<%@ page import="java.util.ArrayList" %>
<html>
<body>

<%
    ArrayList<String> hobbies = new ArrayList<String>();

    String hobbyName = request.getParameter("hobbyName");

    if(hobbyName == null){
            out.println("Please enter a hobby before clicking add! Dummy.<br/>");
    }   
    else{
            hobbies.add(hobbyName);

            for(int index = 0; index < hobbies.size(); index ++){
                    out.println(hobbies.get(index) + "<br/>");
            }   

            session.setAttribute("hobbies", hobbies);
    }   
%>

</body>
</html>

I have tried passing it as a string object, and passing it as an object alone but nothing seems to work. 我尝试将其作为字符串对象传递,并单独将其作为对象传递,但似乎没有任何效果。

the problem is here .. 问题在这里..

ArrayList<String> hobbies = session.getAttribute("hobbies");

Try typecasting it as getAttribute always returns Object. 尝试进行类型转换,因为getAttribute始终返回Object。

ArrayList<String> hobbies = (ArrayList<String>)session.getAttribute("hobbies");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM