Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Apr 2007
    Posts
    179
    Thanks
    17
    Thanked 0 Times in 0 Posts

    JSP scriptlet and javascript

    In a JSP, I try to pass a Java object to a javascript function, like this:

    <%
    Test test = request.getSession().getAttribute("test");
    //Test has a field of lasName, such as test.getLastName() will return "john"
    %>

    //This is for simplizing. In reality this js codes are in different file such as includeFile.js


    <script>
    var obj = <%= test%>;

    alert(obj.lastName);

    </script>

    But it does not work. Then I tried:

    var obj = "<%= test%>";

    <c:set var="t" value="<%=test%>"></c:set>

    var obj = "${t}";

    But none worked.

    What should I do to achieve the goal?


    Thanks

    Scott

  • #2
    Senior Coder ckeyrouz's Avatar
    Join Date
    Jun 2009
    Location
    Montreal, Canada
    Posts
    1,044
    Thanks
    5
    Thanked 179 Times in 179 Posts
    There are quite some errors here.
    First you need to cast the object from the session to Test like this:

    Code:
    Test test = (Test) request.getSession().getAttribute("test");
    then you need to import the the full package of the class Tess
    Code:
    <%@page import="a.b.c.*"%>
    After that you cannot pass a complex java object to javascript

    what you can do is pass the fields of the object one by one:
    Code:
    <% String lastName = test.lastName;%>
    in your javascript you can read java string values the same way you have done:

    Code:
    <script tyep="text/javascript">
    
      var lastName = "<%=lastName%>";
    </script>
    You cannot access the inner fields of a java complex object in javascript.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •