Solved

How to call java bean method from external javascript file ?

Posted on 2015-02-19
53
1,349 Views
Last Modified: 2015-02-21
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
Comment
Question by:Pradip Shenolkar
  • 27
  • 26
53 Comments
 
LVL 27

Expert Comment

by:rrz
ID: 40620394
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
 

Author Comment

by:Pradip Shenolkar
ID: 40620401
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
 
LVL 27

Expert Comment

by:rrz
ID: 40620416
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
 

Author Comment

by:Pradip Shenolkar
ID: 40620513
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
 
LVL 27

Expert Comment

by:rrz
ID: 40620528
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
 

Author Comment

by:Pradip Shenolkar
ID: 40620535
I know Ajax basics.
I am using tomcat version 8
0
 
LVL 27

Expert Comment

by:rrz
ID: 40620546
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
 

Author Comment

by:Pradip Shenolkar
ID: 40620554
Firefox latest version.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40620558
Ok, put some code together. I will be back in 10 hours.
0
 

Author Comment

by:Pradip Shenolkar
ID: 40620583
I might use Firefox as well as Chrome browser.
Because javascript debugger is more advanced in Chrome.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40621684
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
 

Author Comment

by:Pradip Shenolkar
ID: 40622558
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622599
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622603
I just pieced that example together from the links I posted yesterday.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40622612
What event do you want to use to trigger the AJAX call?
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622616
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622620
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
 

Author Comment

by:Pradip Shenolkar
ID: 40622625
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622629
Did you get my example to work?
0
 
LVL 27

Expert Comment

by:rrz
ID: 40622632
Where is three.js?  Give a link.
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622633
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
 

Author Comment

by:Pradip Shenolkar
ID: 40622637
Where is three.js?  Give a link.

Three.js is javascript library to create 3D scenes:
http://threejs.org/
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622639
You want full code of my js file ?
I am only using Cube geometry.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40622640
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622644
In your  test6.jsp file you should have just those two lines. Nothing else.
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622645
I am trying.
Just hold on.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:Pradip Shenolkar
ID: 40622646
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622647
What are using in your development?  Something must have generated the
"><title>Insert title here</title></  
part.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40622649
Attribute (language) is obsolete. Its use is discouraged in HTML5 documents
 
I didn't get that warning.
Did you try just
<script>
?
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622651
I am using Eclipse Ide
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622653
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622654
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
 

Author Comment

by:Pradip Shenolkar
ID: 40622656
For above jsp page the response is displayed as :

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

Open in new window

0
 

Author Comment

by:Pradip Shenolkar
ID: 40622657
It is returning response including tags.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40622659
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622661
Please give some example of data that you want to send to your bean.    It is simple key and value Strings?   How many?
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622662
Ok done.
Now I get Only Id is -633809340  

Whats next ?
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622664
I am sending data just give me 5 minutes
0
 
LVL 27

Expert Comment

by:rrz
ID: 40622665
<%@ 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
 
LVL 27

Expert Comment

by:rrz
ID: 40622672
Ok done.  Now I get Only Id is -633809340  
Good.
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622676
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622682
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622687
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
 
LVL 27

Expert Comment

by:rrz
ID: 40622690
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
 

Author Comment

by:Pradip Shenolkar
ID: 40622692
You can go to bed now, by tomorrow  I will give you details.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40622697
If there is an example of what you are doing at threejs.org  then point me to it. I not familiar with it.
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622729
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
 

Author Comment

by:Pradip Shenolkar
ID: 40622770
 I presume your bean method will accept the parameters.
Yes bean method accept parameters
0
 

Author Comment

by:Pradip Shenolkar
ID: 40622774
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
 

Author Comment

by:Pradip Shenolkar
ID: 40623244
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
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
ID: 40623273
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
 

Author Comment

by:Pradip Shenolkar
ID: 40623304
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
 

Author Closing Comment

by:Pradip Shenolkar
ID: 40623733
Thank you so much..
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now