简体   繁体   中英

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. It keeps saying "Type mismatch: cannot convert from Object to ArrayList".

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:

<%@ 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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