问题描述
我需要为google API表提供数据...所以我将它从servlet发送到JSP
I need to provide data for google APIs table... so I'll send it from servlet to JSP
但是如何在googles中访问这些数据javascript?
but how can I access this data in "googles" javascript?
我将提供另一个JS的样本 - 非常简单 - 只是为了让我学习如何制作主题
I'll provide sample of another JS - very simple one - just to let me learn how to make what topic says
<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>
它必须打印给定列表的元素......但是现在它只是一个内部警报的大字体它...重构它?我不喜欢在JSP中使用很多java,因为servlet应放在它的位置
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
编辑:只是为了总结 - 我更喜欢普通的JS这里循环...一般我更喜欢最小化java代码,并最大化JS
just to sum up - I would prefer "normal" JS for loop here... Generally I'd prefer to minimize java code, and maximize JS
推荐答案
将其转换为 servlet的。您可以使用进行此操作。假设您有一个列表< Person>
:
Convert it to JSON in doGet()
of a preprocessing servlet. You can use among others Google Gson for this. Assuming that you've a 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);
(请注意,我将其设为请求属性而非会话属性,您可以免费使用改变它,但我认为它不一定需要是会话属性,因为它不代表会话范围的数据)
将它分配给JS JSP中的变量如下:
Assign it to a JS variable in JSP as follows:
<script>
var persons = ${personsJson};
// ...
</script>
这种方式可以作为一个完整的JS对象使用。您可以直接将其提供给Google API。
This way it's available as a fullworthy JS object. You could feed it straight to the Google API.
现在调用servlet的URL而不是JSP。例如,当它映射到 / persons
的URL模式时,通过。
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.
这篇关于在jsp里面的javascript中访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!