File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JSP and the fly likes JSP and javascript Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » JSP
Bookmark "JSP and javascript" Watch "JSP and javascript" New topic

JSP and javascript

Raj Ohadi
Ranch Hand

Joined: Jun 30, 2006
Posts: 316
Is it possible that, in a JSP page, I include a javascript section like

<% import %>

<!-- some JSP and html portion -->

<input type="button" onClick="verify()"/>

function verify() {
var name = document.getElementbyID("name");
var street = ...

<% Contact contact = new Contact(name, street);
session.setAttribute("contact", contact);



What I want to do is --- I want to create a java object inside the javascript, and pass it to a new action page. On the new action page, it retrieves the object from session, then use this object's data to access database and finally get the results and display it. Basically I need to use the client side information (what user selects) and I want to somehow pass it to a struts action or servlet or JSP by passing the data in a session. But I don't know if this idea is valid -- can I create java object inside javascript ? and can I embed java code inside javascript ? If I can't how can I save a client side DOM info into session ? Note -- I don't want to submit the whole thing to server by using a submit button. I have separate buttons to handle that, this is just a verify button in the middle stage.
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2904

You can't pass/access Java object in JS. What you can do is either pass the data using query string OR POST them using FORM.

[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Chinna Eranna
Ranch Hand

Joined: Dec 08, 2009
Posts: 174

Javascript code gets executed at the client(browser).

And java code gets executed at Server. Server knows about session, request, response objects.

Hence you cannot do this.

- Chinna
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63843

As already pointed out, impossible. Please read this article to understand how JSP works and why that is not possible.

[Asking smart questions] [About Bear] [Books by Bear]
adil qureshi
Ranch Hand

Joined: Jul 11, 2008
Posts: 48
Store the data in some variables send this data to server using AJAX based request....
this wont submit the form either ....
..... here you can create your java object .... then store it in some session variable and then you can perform you data base logic .

SCJP 1.5,SCWCD 1.5
I agree. Here's the link:
subject: JSP and javascript
It's not a secret anymore!