Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  54] [ 7]  / answers: 1 / hits: 60292  / 13 Years ago, tue, august 30, 2011, 12:00:00

I need to provide data for google APIs table... so I'll send it from servlet to JSP



but how can I access this data in googles javascript?



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>


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



EDIT: just to sum up - I would prefer normal JS for loop here... Generally I'd prefer to minimize java code, and maximize JS


More From » jsp

 Answers
27

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


(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:



<script>
var persons = ${personsJson};
// ...
</script>


This way it's available as a fullworthy JS object. You could feed it straight to the 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.


[#90352] Sunday, August 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaleyv

Total Points: 259
Total Questions: 99
Total Answers: 107

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;