Javascript 在jsp中访问javascript中的会话变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7241442/
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
accessing session variables in javascript inside jsp
提问by dantuch
I need to provide data for google APIs table... so I'll send it from servlet to JSP
我需要为 google APIs 表提供数据......所以我将它从 servlet 发送到 JSP
but how can I access this data in "googles" javascript?
但是如何在“谷歌”javascript 中访问这些数据?
I'll provide sample of another JS - very simple one - just to let me learn how to make what topic says
我将提供另一个 JS 的示例 - 非常简单的一个 - 只是为了让我学习如何制作主题所说的内容
<script>
function showTable()
{
<%
Object obj = session.getAttribute("list");
List<String> list = new ArrayList<String>();
int size = 0;
if (obj != null) {
list = (ArrayList<String>) obj;
size = (Integer) session.getAttribute("size");
}
for (int i = 0 ; i < size ; i++) {
String value = list.get(i);
%>
alert('<%= i %> = <%= value %> ');
<%
}
%>
}
</script>
It has to print elements of given list... but now it's just a big scriplet with alert inside of it... for to refactor it? I don't like having to much java in JSPs, because servlet is where it should be placed
它必须打印给定列表的元素......但现在它只是一个内部带有警报的大脚本......重构它?我不喜欢在 JSP 中使用太多 java,因为 servlet 是它应该放置的地方
EDIT: just to sum up - I would prefer "normal" JS for loop here... Generally I'd prefer to minimize java code, and maximize JS
编辑:总结一下 - 我更喜欢这里的“普通”JS for 循环......通常我更喜欢最小化 Java 代码,并最大化 JS
回答by BalusC
Convert it to JSONin doGet()of a preprocessing servlet. You can use among others Google Gsonfor this. Assuming that you've a List<Person>:
将其转换为JSON在doGet()预处理的servlet。为此,您可以使用Google Gson。假设你有一个List<Person>:
List<Person> persons = createItSomehow();
String personsJson = new Gson().toJson(persons);
request.setAttribute("personsJson", personsJson);
request.getRequestDispatcher("/WEB-INF/persons.jsp").forward(request, response);
(note that I made it a request attribute instead of session attribute, you're free to change it, but I believe it doesn't necessarily need to be a session attribute as it does not represent sessionwide data)
(请注意,我将其设为请求属性而不是会话属性,您可以自由更改它,但我相信它不一定需要是会话属性,因为它不代表会话范围的数据)
Assign it to a JS variable in JSP as follows:
将其分配给 JSP 中的一个 JS 变量,如下所示:
<script>
var persons = ${personsJson};
// ...
</script>
This way it's available as a fullworthy JS object. You could feed it straight to the Google API.
这样它就可以作为一个完整的 JS 对象使用。您可以将其直接提供给 Google API。
Now invoke the URL of the servlet instead of the JSP. For example, when it's mapped on an URL pattern of /persons, invoke it by http://localhost:8080/contextname/persons.
现在调用 servlet 的 URL 而不是 JSP。例如,当它映射到 的 URL 模式时/persons,通过http://localhost:8080/contextname/persons调用它。
回答by JB Nizet
JavaScript is executed at client side, and scriptlets, EL, and JSP tags at server side. From the point of view of the server-side code, JavaScript is just generated text, just like HTML markup.
JavaScript 在客户端执行,scriptlet、EL 和 JSP 标签在服务器端执行。从服务器端代码的角度来看,JavaScript 只是生成的文本,就像 HTML 标记一样。
So, if you want to have a JavaScript loop which loops over a JavaScript array in the generated HTML page, you need to generate the JavaScript code which initializes the array, and the JavaScript loop.
因此,如果您想要在生成的 HTML 页面中循环遍历 JavaScript 数组的 JavaScript 循环,则需要生成初始化数组的 JavaScript 代码和 JavaScript 循环。
Here's the JSP code
这是JSP代码
var theArray = [<c:forEach items="${sessionScope.list}" var="item" varStatus="loopStatus">'${item}' <c:if ${!loopStatus.last}>, </c:if></c:forEach>];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
This JSP code will generate the following JavaScript code, assuming the list in the session attribute contains "banana", "apple" and "orange":
此 JSP 代码将生成以下 JavaScript 代码,假设 session 属性中的列表包含“banana”、“apple”和“orange”:
var theArray = ['banana', 'apple', 'orange', ];
for (var i = 0; i < theArray.length; i++) {
alert(theArray[i]);
}
Make sure, though, to properly escape the values of the list in order to generate valid JavaScript code. For example, if one of the values was "I'm cool", the generated JavaScript would be
但是,请确保正确转义列表的值以生成有效的 JavaScript 代码。例如,如果其中一个值为"I'm cool",则生成的 JavaScript 将是
var theArray = ['I'm cool', 'apple', 'orange', ];
which is not valid anymore. Use commons-lang StringEscapeUtils.escapeEcmaScriptto escape the values.
这不再有效。使用 commons-lang StringEscapeUtils.escapeEcmaScript来转义值。
回答by Naved
since the ArrayList is having objects of Strings you can simply use split() method on the value of the array list. Something like as below;
由于 ArrayList 具有字符串对象,因此您可以简单地对数组列表的值使用 split() 方法。像下面这样;
function showTable() {
<%
Object obj = session.getAttribute("list");
List list = null;
if (obj != null) {
list = (ArrayList<String>) obj;
} else list = new ArrayList<String>(); %>
var jsList = <%=list.toString()%>
//remove [] from content
jsList = jsList.replace("[","");
jsList = jsList.replace("]","");
//split the contentsvar splitContent = jsList.split(","); //an array of element
//split the contentsvar splitContent = jsList.split(","); //an array of element
for(var i=0;i<splitContent.length;++i) {
alert(splitContent[i]);
}
}
}
I hope this will help you solve this.
我希望这会帮助你解决这个问题。

