...

View Full Version : JSP scriptlet and javascript



otnj2ee
07-18-2009, 12:22 AM
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

ckeyrouz
07-18-2009, 02:48 AM
There are quite some errors here.
First you need to cast the object from the session to Test like this:


Test test = (Test) request.getSession().getAttribute("test");
then you need to import the the full package of the class Tess


<%@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:


<% String lastName = test.lastName;%>


in your javascript you can read java string values the same way you have done:


<script tyep="text/javascript">

var lastName = "<%=lastName%>";
</script>

You cannot access the inner fields of a java complex object in javascript.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum