Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing session variables in javascript inside jsp

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

like image 494
dantuch Avatar asked Aug 30 '11 09:08

dantuch


People also ask

Can session variables be accessed from Javascript?

You can't set session side session variables from Javascript . If you want to do this you need to create an AJAX POST to update this on the server though if the selection of a car is a major event it might just be easier to POST this. Save this answer.


1 Answers

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.

like image 74
BalusC Avatar answered Nov 08 '22 11:11

BalusC