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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21592201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:33:30  来源:igfitidea点击:

How to pass an ArrayList from one jsp to another using session

javajspsessionarraylist

提问by user3277671

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

我试图将一个 ArrayList 从 handle.jsp 传递到 main.jsp,但它不允许我这样做。它一直说“类型不匹配:无法从对象转换为 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:

句柄.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.

我试过将它作为一个字符串对象传递,并将它作为一个单独的对象传递,但似乎没有任何效果。

采纳答案by Aditya Peshave

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");