• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2333
  • Last Modified:

How to call java bean method from external javascript file ?

I am using java beans, jsp, javascript in my application.
I need to call java bean methods from javascript.
Can anyone help me in this  ?
Please show some example code, with one java method and how to call it from external javascript file.
0
Pradip Shenolkar
Asked:
Pradip Shenolkar
  • 27
  • 26
1 Solution
 
rrzCommented:
I don't have any code at this time. But, I do have some ideas for you.
Javascript can use AJAX to call a Servlet. The Servlet can call the javabean method and response to the AJAX call with the result returned from the bean.   You could write your own AJAX code but most people use a framework or a library.
Here are some links for basic AJAX.  
http://en.wikipedia.org/wiki/Ajax_(programming)
http://www.tizag.com/ajaxTutorial/   
Most  people use something like  jQuery.
http://jquery.com/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm   
But, in my opinion,  for your present project the best fit for you would be DWR.  
http://directwebremoting.org/dwr/index.html   
DWR is a java library that will do most of the work for you. It will do the AJAX in the background and has a Servlet to call your bean code.  Do some reading and let me know how you want to proceed.
0
 
Pradip ShenolkarAuthor Commented:
Is it possible to do it without using servlet  ?
Of-course every JSP is ultimately converted  into servlet before it can be actually used, but is it possible to do it without explicitly defining the servlet. (i.e. from jsp)
0
 
rrzCommented:
Is it possible to do it without using servlet  ?
Yes, it is possible. Are you using a host that disallows Servlets?    
AJAX could call a JSP.  But, DWR specifically uses a Servlet.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Pradip ShenolkarAuthor Commented:
Are you using a host that disallows Servlets?    

No I am not.
I have never worked on servlets, and due to project deadline I cannot afford to spend time in learning new things.
It would be better if I can do it without using servlets.
0
 
rrzCommented:
Do you know AJAX already?  
If yes, then use it to call a JSP.
If not, then DWR is the easiest way to go. The Servlet part is easy. Are you using Tomcat? What version?
0
 
Pradip ShenolkarAuthor Commented:
I know Ajax basics.
I am using tomcat version 8
0
 
rrzCommented:
I know AJAX basics as well.
So, the first step is to use it to send a request to a simple "hello"  JSP.   Which browsers are you targeting?
I am going to sleep now.
0
 
Pradip ShenolkarAuthor Commented:
Firefox latest version.
0
 
rrzCommented:
Ok, put some code together. I will be back in 10 hours.
0
 
Pradip ShenolkarAuthor Commented:
I might use Firefox as well as Chrome browser.
Because javascript debugger is more advanced in Chrome.
0
 
rrzCommented:
Here  is some demonstration code. My bean:
package rrz;
import java.util.Random;
public class IdBean implements java.io.Serializable
{
   private String randomId = null;
   public IdBean(){
      randomId = Integer.toString(new Random().nextInt());
   }
   public String getRandomId(){
	  return  randomId;
   }
   public void setRandomId(String notUsedForThis){
      this.randomId = Integer.toString(new Random().nextInt());
   }
}

Open in new window

 test6.jsp  
<jsp:useBean id="myBean" class="rrz.IdBean" />
Id is ${myBean.randomId} 

Open in new window

My html page:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<script language="Javascript">
function ajaxFunction(){
	var ajaxRequest; 
	try{
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
				alert("Error!!");
				return false;
			}
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
                if (ajaxRequest.status === 200) {
                } else {
                        alert('Error: ' + ajaxRequest.status); 
                       }
			    document.myForm.time.value = ajaxRequest.responseText;
	    }
	}
	ajaxRequest.open("GET", "test6.jsp", true);
	ajaxRequest.send(null); 
}
</script>
</head>
<body>
<form name='myForm' >
Enter a name and then click on id box.<br/>
Name: <input type='text' onchange="ajaxFunction();" name='username' /><br/>
Time: <input type='text' name='time' />
</form>
</body>
</html>

Open in new window

0
 
Pradip ShenolkarAuthor Commented:
You said :
Enter a name and then click on id box.
in html file.
Where is the id box ?
Where should I click ?
If I enter name and press Enter I get following  line in Time text box :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body>Id is -1862270475 </body></html>
0
 
rrzCommented:
I am sorry, I should have labeled the second text input element "Id" not time.
Since   ajaxFunction is called on the  onchange event it is necessary to take the focus off of  the "username" text input element.   Don't  press enter. That will submit the form.
0
 
rrzCommented:
I just pieced that example together from the links I posted yesterday.
0
 
rrzCommented:
What event do you want to use to trigger the AJAX call?
0
 
Pradip ShenolkarAuthor Commented:
I am getting "Error 404"

What I am doing is this :
1 ) run html file
2) Enter name in first text box.
3) Click in second text box

alert box apperars saying "Error 404"
0
 
rrzCommented:
alert box apperars saying "Error 404"
  Ok, your getting somewhere now. Status code 404 means that the  test6.jsp file can't be found.  Did you put the Ajax.html file and the test6.jsp file into the same root folder of your web app? If not, then please do so and browse to the html file.   I just patched this together from the examples I linked to yesterday. You should tell me more about your  requirements.
0
 
Pradip ShenolkarAuthor Commented:
I want to use onclick event.
What I want to do is :
1) I have few geometries from three.js
2) When user clicks on a geometry I want get some data related with that geometry and send it to Java Bean.
3) Whatever data Bean sends in response is used to render more geometries.

In simple terms I want to send data to bean class when "onclick" event occurs and use the response to proceed further.
the request and response should be in array form,
0
 
rrzCommented:
Did you get my example to work?
0
 
rrzCommented:
Where is three.js?  Give a link.
0
 
Pradip ShenolkarAuthor Commented:
K I fixed it
After entering name and clicking in second text box  I get following text in that text box :
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body>Id is -1000557381                                           </body></html>
0
 
Pradip ShenolkarAuthor Commented:
Where is three.js?  Give a link.

Three.js is javascript library to create 3D scenes:
http://threejs.org/
0
 
Pradip ShenolkarAuthor Commented:
You want full code of my js file ?
I am only using Cube geometry.
0
 
rrzCommented:
When user clicks on a geometry I want get some data related with that geometry
 
Please give some example of data. It is simple key and value Strings?  
After entering name and clicking in second text box  I get following text in that text box :

I can't understand that. All I get is
Id is 991805918
0
 
rrzCommented:
In your  test6.jsp file you should have just those two lines. Nothing else.
0
 
Pradip ShenolkarAuthor Commented:
I am trying.
Just hold on.
0
 
Pradip ShenolkarAuthor Commented:
Just tell me if you get following warning @  <script language="Javascript"> in html page.

 Attribute (language) is obsolete. Its use is discouraged in HTML5 documents.
0
 
rrzCommented:
What are using in your development?  Something must have generated the
"><title>Insert title here</title></  
part.
0
 
rrzCommented:
Attribute (language) is obsolete. Its use is discouraged in HTML5 documents
 
I didn't get that warning.
Did you try just
<script>
?
0
 
Pradip ShenolkarAuthor Commented:
I am using Eclipse Ide
0
 
Pradip ShenolkarAuthor Commented:
I fixed that warning.
This is my jsp page :
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<body>
<jsp:useBean id="myBean" class="mypkg.IdBean" />
Id is ${myBean.randomId}                                       
</body>
</html>

Open in new window

0
 
rrzCommented:
Eclipse is ok. But, sometimes it gets in the way.  It must have added that extra stuff to your JSP.  All you want is those two lines.
0
 
Pradip ShenolkarAuthor Commented:
For above jsp page the response is displayed as :

<html><body>Id is 171491123                                       </body></html>

Open in new window

0
 
Pradip ShenolkarAuthor Commented:
It is returning response including tags.
0
 
rrzCommented:
No,  take out the  <html> <body> tags. You are not asking your browser to render a page. You are using AJAX. It is like using the back door to get something out of the server.
0
 
rrzCommented:
Please give some example of data that you want to send to your bean.    It is simple key and value Strings?   How many?
0
 
Pradip ShenolkarAuthor Commented:
Ok done.
Now I get Only Id is -633809340  

Whats next ?
0
 
Pradip ShenolkarAuthor Commented:
I am sending data just give me 5 minutes
0
 
rrzCommented:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

Open in new window

   
I don't think you need that. But, if you must use it, then use text/plain  
<%@ page language="java" contentType="text/plain; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

Open in new window

You don't want to send HTML.
0
 
rrzCommented:
Ok done.  Now I get Only Id is -633809340  
Good.
0
 
Pradip ShenolkarAuthor Commented:
Here is the data :

 There are 4 arrays in javascript  :
   var products = ['Laptop', 'Lcd','Tv','Mobile','Mouse','Cooler'];
    var locations = ['India','USA','China','Australia'];
    var year = [2010,2011, 2012,2013,2014,];
    var sale =[10,11,12,13,14,15,16,17,18,23,34,32,45,56,32,34,54,56,43,23,12,78,9,55,12,32,34,43,45,65,67,78,54]; //

These values are displayed on cube geometries.
When user clicks on any on cube the data on that cube (i.e. one product name, one location name and one year) is sent to Java Bean class. [Note : sale value is not sent]

In response Bean send some data in array from :
example : If user selects cube with "India" "2014" "Mobile",  Bean will send cities from that country along with sale values.
0
 
rrzCommented:
Ok, in the first example above we did a simple GET request. To send some parameters, we have use a POST request. Look at  
http://www.javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml   
When user clicks on any on cube the data on that cube (i.e. one product name, one location name and one year) is
  So, that be something like(see  link)  
var parameters="product=Mobile&location=India&year=2014"
?
0
 
rrzCommented:
and we would have
var parameters="product=Mobile&location=India&year=2014";
mypostrequest.open("POST", "ajax.jsp",  true)
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
 mypostrequest.send(parameters)

Open in new window

In ajax.jsp, we use
request.getParameter("product");
and such to get the data.  I presume your bean method will accept the parameters.
Bean will send cities from that country along with sale values.
 In what format?  The common practice is send JSON back to the client.
0
 
rrzCommented:
It is bedtime in California. Tomorrow morning I could put together a  POST example.  Please show me what your bean returns. Is it two arrays or Lists or JSON or what?
0
 
Pradip ShenolkarAuthor Commented:
You can go to bed now, by tomorrow  I will give you details.
0
 
rrzCommented:
If there is an example of what you are doing at threejs.org  then point me to it. I not familiar with it.
0
 
Pradip ShenolkarAuthor Commented:
I TRUST YOU

I am sending you full code.

Check attachment 3Dtest.zip
[It contains other unwanted files also.]

Just focus on Cube2.html
run Cube2.html

When user clicks on any smaller cube the data on that cube is sent to Bean class.
And Bean will return either "cities from that country", or "months from that year" or "companies of that product".

Before generating this cube user selects on which parameter he wants to go further. (This is not there in code I provided)

Example :
1 ) user first selects Country ( this is per-requisite).

2)  then the control is transferred to the page which creates cube (cube made of many smaller cubes, as seen in Cube2.html) .
[Note : In original code this control is transferred to js file and not to html file]

3) now user clicks on any one smaller cube.

4)  Data from that cube is sent to bean (i.e. Product name, locations name, year), and bean in response sends cities from Country (since user has selected Country in step 1 above). Also bean will send sales data in those cities. One sale value for one city. [These values are retrieved from database, but for demonstration you can hardcode]
 If user has selected "Year" in step 1 then it would return Months from that Year along with sale value for that month.

5) then this data from response is used for creating more cubes.
3Dtest.zip
0
 
Pradip ShenolkarAuthor Commented:
 I presume your bean method will accept the parameters.
Yes bean method accept parameters
0
 
Pradip ShenolkarAuthor Commented:
If there is an example of what you are doing at threejs.org  then point me to it.

I am just using three js library in my application.
In the code which I had sent I have used it.

threejs.org is official website for examples.
0
 
Pradip ShenolkarAuthor Commented:
Among array, list, or json,  could you suggest me which one would be better to use in this situation, to send response back to client.
I haven't worked with JSON yet.
0
 
rrzCommented:
You sent your code to everybody on Experts-exchange.  Is there any private data in there?  
I took a look at your files. But, it would take me days to figure out what is going on with all that code.
I am not willing to spend that much of my time on your project.
I see that your project already contains jquery. A lot people use it. It has AJAX methods.    
I am not a jquery expert. So, I will just show you a post example using straight AJAX.
Maybe it will be a step closer to what you need for your project. I tested in FireFox and Chrome.
I didn't use a bean. All you really need is a utility class.
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<script language="Javascript">
function ajaxFunction(){
	var ajaxRequest; 
	var parameters="product=Mobile&location=India&year=2014 ";
	try{
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
				alert("Error!!");
				return false;
			}
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
                if (ajaxRequest.status === 200) {
                } else {
                        alert('Error: ' + ajaxRequest.status); 
                       }
			    //document.myForm.result.value = ajaxRequest.responseText;
				document.getElementById("result").value = ajaxRequest.responseText;
	    }
	}
	ajaxRequest.open("POST", "test7.jsp", true);
	ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	ajaxRequest.send(parameters); 
}
</script>
</head>
<body>
Click on Send button.<br/>
<input type='button' onclick="ajaxFunction();" value="Send" /><br/>
Result from server: <input type='text' id='result' size="100"/>
</body>
</html>

Open in new window

test7.jsp is just these 8 lines. You don't need to add anything.
<%@ page import="rrz.TestPost" %>
<%
String product = request.getParameter("product");
String location = request.getParameter("location");
String year = request.getParameter("year");
String serverResult = TestPost.getData(product, location, year);
%>
<%=serverResult%>

Open in new window

  TestPost.java
package rrz;
public class TestPost 
{
   public static String getData(String product, String location, String year){
        return "data for " + product + location + year + "from server.";
   }
}

Open in new window

0
 
Pradip ShenolkarAuthor Commented:
You sent your code to everybody on Experts-exchange.  Is there any private data in there?  
Ya I realized it later.
But I had removed private data before sending the files, but forgot to edit the comment on top.
Sorry if you got hurt.

I will try your code with Bean and let you know tomorrow (for you its evening).
0
 
Pradip ShenolkarAuthor Commented:
Thank you so much..
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 27
  • 26
Tackle projects and never again get stuck behind a technical roadblock.
Join Now