accessing session variables in javascript inside jsp

前端 未结 3 1927
失恋的感觉
失恋的感觉 2020-12-30 13:56

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

3条回答
  •  伪装坚强ぢ
    2020-12-30 14:15

    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:

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

    
    

    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.

提交回复
热议问题