简体   繁体   中英

How to access java.util.List session from javascript?

In java my code is,

List abcList;   
request.getSession().setAttribute("abc", abcList);

I want to access this list in javascript,

var myVariable='<%=(List)session.getAttribute("abc")%>';

I am not getting the list(abcList) value in javascript......

You need to serialize your list to Javascript object. There are libraries that do it for you: https://stackoverflow.com/questions/338586/a-better-java-json-library

You have to write code that prints out the list as a javascript array. This propably just results in

var myVariable='ArrayList@123455'

but what you need is

var myVariable = ["element1", "element2, ...]

use a json serialization library. those do the printing for you. Or write a json printer, it's actually pretty straight forward^^.

You can't do that. You will have to create the list by iterating over the Java List. You can try something like this...

var myVar = [];
<%
List list = (List)session.getAttribute("abc");
for(int i = 0; i < list.size(); ++i){
    out.println("myVar.push('" + list[i] + "');");
}
%>

What exactly want to achieve ? Remember javascript will be executed on client browser where as the java code will be on the server. So you should not reference a java variable from javascript. Instead using jsp tags you can get the list only at the loading time that to on the server.

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