how to call a java class method in javascript using ajax ? - java

i have a java class ::
package MyPackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.google.gson.Gson;
public class PopulateTextbox {
Gson gson = new Gson();
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
String temp1;
String temp;
List <String>rowValues = new ArrayList<String>();
List <Integer>rowValues1 = new ArrayList<Integer>();
String[] contactListNames;
Connection con=null;
Statement st=null;
ResultSet rs=null;
public String method(){
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:Practice_Database";
con = DriverManager.getConnection(db,"","");
st = con.createStatement();
String sql = "SELECT Emp_Name,ID,Email_Add FROM EmployeeSearch";
rs = st.executeQuery(sql);
while(rs.next()){
obj.put("ID", rs.getInt("ID"));
obj.put("Names",rs.getString("Emp_Name"));
obj.put("Email", rs.getString("Email_Add"));
arr.add(obj);
}
//obj.accumulate("ID",rowValues1);
//obj.accumulate("Names",rowValues);
temp1 = arr.toString();
System.out.println(temp1);
}catch(Exception e){System.out.println(e);}
/*finally{
try {
if(con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs!=null)rs.close();
} catch (SQLException e) {
e.printStackTrace();
}try {
if(st!=null)st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}*/
return temp1;
}
public static void main(String args[])
{
PopulateTextbox obj = new PopulateTextbox();
String temp1= obj.method();
}
}
This is returning me a Json array. Now i want to call method() of this class in JavaScript again and again to get new values as i update my database. I have a data grid which is working fine as the page loads for the first time with a set of values in this json array. But how to refresh data using Ajax. Or how to call the method() using Ajax so that data gets refreshed when i click on a button on the page. The code where i am calling this method in java-script is ::
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
i am getting problem in retrieving new set of values in temp1 through a Ajax call to the server . please help ? Thanks.

Create a blank JSP (for example, textBoxAjaxResp.jsp) and out put your JSON string from that JSP:
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
<%=temp1 %>
and hit that JSP using jQuery AJAX call.
$.get("mypath/textBoxAjaxResp.jsp", function (response) {
//do operation using the response
}, "json");

you can use Direct Web Remoting library to call java functions using javascript
But I would suggest to write servlet (tutorial is pretty old but good, you should use servlet 3.0 if possible) yourself (instead of using DWR which will have their servlet to write to the response stream also this is very simple requirement so you should write servlet yourself instead of using third party library) and write JSON response directly.

You might want to look at my answer here Updating contents of a jsp page without refreshing this uses a SpringMVC class which returns a text value from server side to client side using jquery ajax.

Related

kendo ui grid is not receiving json data from servlet

i have a netbeans web application named javaservlet.this project package has one servlet databaseconnection.java.here i have retrieved 6 rows from a database table employee which has 3 columns eid,ename,esalary and show it as json value
in "http://localhost:8084/javaservlet/databaseconnection" url.Now i want to show all 6 rows of data in kendo grid.In index.html page which is in WEB-INF folder i have tried to read json data from url.but it is not working.i have added three titles EmployeeSalary,EmployeeName,EmployeeId in kendo ui grid and three string fields.when i run the file only showing thevalue when database table has only one row but when table has more than one row kendo is not showing any data ..why is this happening.kindly help me to solve the problem.here is my code
databaseconnection.java
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.*;
#WebServlet(urlPatterns = {"/databaseconnection"})
public class databaseconnection extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
Connection connection = null;
Statement stmt = null;
JSONArray jArray = new JSONArray();
JSONObject jobj = new JSONObject();
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres", "root");
stmt = connection.createStatement();
// String sql = "INSERT INTO employee (eid,ename,esalary) " + "VALUES (7, 'Nadia', 35000)";
// stmt.executeUpdate(sql);
ResultSet result = stmt.executeQuery("Select eid,ename,esalary from employee");
while (result.next()) {
String eid = result.getString("eid");
String ename = result.getString("ename");
String esalary = result.getString("esalary");
jobj.put("eid", eid);
jobj.put("ename", ename);
jobj.put("esalary", esalary);
out.print(jobj);
out.flush();
// jArray.put(jobj);
// System.out.print(jobj);
}
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
} catch (ClassNotFoundException ex) {
Logger.getLogger(databaseconnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
Pls add the jsonobject into jsonarray inside the while loop.ex:
while (result.next()) {
String type_json = result.getString("eid");
String name_json = result.getString("ename");
String id_json = result.getString("esalary");
jobj.put("eid", type_json);
jobj.put("ename", name_json);
jobj.put("esalary", id_json);
**jArray.add(jobj);**
}
Sara5, I think you should declare array object of Json class like below
JSONArray allArray = new JSONArray();
then
while (result.next()) {
String type_json = result.getString("eid");
String name_json = result.getString("ename");
String id_json = result.getString("esalary");
jobj.put("eid", type_json);
jobj.put("ename", name_json);
jobj.put("esalary", id_json);
allArray.add(jobj);
}
then after this , we create a default JSON object to contain all array and number of JSON objects as below
JSONObject myObj = new JSONObject();
myObj.put("success", true);
myObj.put("data", allArray); // all JSON objects
myObj.put("total", total);// total number of JSON objects
response.setContentType("application/json");// don't forget this
PrintWriter writer = response.getWriter();
writer.println(myObj.toString());
Pls try to use the below libs
json-lib-2.2.2-jdk15
commons-lang 2.5
commons-beanutils 1.8.0
commons-collections 3.2.1
commons-logging 1.1.1
ezmorph 1.0.6
change your code like this..
response.setContentType("application/json");
while (result.next()) {
String type_json = result.getString("eid");
String name_json = result.getString("ename");
String id_json = result.getString("esalary");
jobj.put("eid", type_json);
jobj.put("ename", name_json);
jobj.put("esalary", id_json);
**jArray.add(jobj);**
}
String output = jArray.toString();
PrintWriter writer = response.getWriter();
writer.write(output);`enter code here`
writer.close();
return "success";
The above code snippet will write the json output to the respective jsp whose forward is "success".

Parsing JSON data in Java

I want to parse the some data from this page:
http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json
The data I want to parse is the titles however I am unsure how I can extract the data. This is what I have done so far:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test
{
public Test() { }
public static void main(String[] args)
{
URL url;
HttpURLConnection connection = null;
InputStream is = null;
JSONParser parser = new JSONParser();
try
{
url = new URL("http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
is = connection.getInputStream();
BufferedReader theReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String reply;
while ((reply = theReader.readLine()) != null)
{
System.out.println(reply);
Object obj = parser.parse(reply);
JSONObject jsonObject = (JSONObject) obj;
String title = (String) jsonObject.get("time");
System.out.println(title);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This just returns null. Can anybody tell me what I need to change? Thanks.
If you read the javadoc of JSONObject#get(String) which is actually HashMap.get(String), it states
Returns: the value to which the specified key is mapped, or null if
this map contains no mapping for the key
Your JSON does not contain a mapping for the key time.
Edit:
If you meant title instead of time, take this extract of the JSON
{"schedule":{"service":{"type":"radio","key":"radio1","title":"BBC Radio 1",...
You need to first get schedule as a JSONObject, then service as a JSONObject, and then title as a normal String value. Apply this differently depending on the type of JSON value.
use something like JSONGen to better understand your data structures, maybe even map your data to the generated objects using google-gson library

Is possible to call servlet from applet

I am not familiar with java and applets, so any one please let me know the possibilities for the following my questing.
I would like to call the Servlet from applet.. is this possible?
If the 1st one is possible can we store the Servlet output like XML data or string in the applet variable?
If the 2nd one is possible, then can get that that variable value using JavaScript or J Query?
If possible please give me the simple example.
Thanks in advance.
Yes you can. The servlet exposes a URL, which you can get with the help of the URLConnection class.
Again you can do this, see here on how you can use the URL connection.
You can do that too, create an applet to get the applet field, and look here on how you can invoke the method.
But all these sound awfully complicated. Why don't you tell us what you are trying to achieve, maybe there is a simpler way to do things.
One : yes you can call the servlet from applet making http calls
step 1 : make a http call to your servlet
step 2 : make your servlet return XML response
step 3 : parse xml response
using this program you can make a call to your servlet
package com.hussain;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class callServlet {
public static void main(String[] args)
{
String servletResponse = callServlet.sendRequest("http://gdata.youtube.com/feeds/base/videos?max-results=10&start-//index=1&alt=json&orderby=published&author=astrobixweb");
callServlet.parseFromXMLResponse(servletResponse);
}
public static String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void parseFromXMLResponse(String respo)
{
// parse your XML response here
}
}
Moving in the flow of your question,
You may call the servlet from your applet:
Construct the url that will hit your servlet.
Use java.net.URLConnection object to hold the connection from your appletURLConnection con = urlToServlet.openConnection()
'con.setDoOutput(true)' => Application intends to write data to the URL connection.
Use the input and output streams to communicate with the Servlet.
con.getInputStream() and con.getOutputStream()
[Note: Don't forget to close all the connections and streams]
Now, use the data you obtained from the InputStream, in what so ever form you want.
Its extreamly simple, use this code:
In Applet:
public String getYourString(){ return responseFromServlet;}
In Javascript:
var jsResp = document.name_of_your_applet.getYourString();
Hope, you've got your answers!

Cannot retrieve data from MySQL table which matches specific "uid"

I am trying to learn more about MySQL and using Java (on Android) to access and retrieve information from a database on my WAMS server. The way my app is setup is that it has an initial login screen which also grabs the "uid" of the username that's logging in (from a different table) and stores it.
Upon login (which is functional - I setup a toast notification that displays the retrieved username and uid of the user logging in), it goes to a new screen (dashboard.xml) which has a TextView field setup to display the retrieved data (from table posted below) associated with the stored "uid". Here is the table I am trying to pull data from:
http://db.tt/4izVQuGB
Now, I have setup a PHP file that queries my db for rows that are associated with a specific "uid". I have tested this file using an HTML form.
$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
mysql_select_db($dbdb)or die("database selection error");
//Retrieve the User ID
$uid = $_POST['uid'];
//Query
$query = mysql_query("SELECT * FROM node WHERE uid='$uid' AND type='goal'");
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
while($results=mysql_fetch_assoc($query)) {
//Store the returned data into a variable
$output = $results;
//encode the returned data in JSON format
echo json_encode($output);
}
mysql_close();
}
The result I get by testing the PHP file using uid value of 1 is:
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the
hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
Now, I have written some android code which sets up httppost and is supposed to retrieve the "titles" in my database table. I know it is wrong (obviously since it doesn't work) but I am confused as to what to do next.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Dashboard extends Activity implements OnClickListener {
// variable declarations
String uid = "1";
// create textview to display retrieved data
TextView display;
HttpClient httpclient;
HttpPost httppost;
HttpResponse httpresponse;
HttpEntity httpentity;
ArrayList<NameValuePair> resultArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
display = (TextView) findViewById(R.id.test);
// initialize HttpClient
httpclient = new DefaultHttpClient();
// initialize HttpPost
httppost = new HttpPost("http://192.168.1.112/android/fetch.php");
try {
// Create new List
List<NameValuePair> resultList = new ArrayList<NameValuePair>();
resultList.add(new BasicNameValuePair("uid", uid));
httppost.setEntity(new UrlEncodedFormEntity(resultList));
httpresponse = httpclient.execute(httppost);
httpentity = httpresponse.getEntity();
InputStream instream = entity.getContent();
try {
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
JSONObject jData = null;
for (int i = 0; i < jArray.length(); i++) {
jData = jArray.getJSONObject(i);
String goals = jData.getString("title");
display.setText(goals);
}
//} catch (JSONException e) {
//Toast.makeText(this, "No entries found", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
e.printStackTrace();
Notifications error = new Notifications();
error.userPassErrorDialog();
}
}
private static String streamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I get the following error when testing it in the Android emulator:
http://db.tt/2vg9MqYh
Any help or suggestions will be greatly appreciated.
In your Android app, you expect a JSONArray:
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
However, in your PHP file you only output multiple separate JSON objects instead of a real array. I think, you should collect all items from the database in an PHP array first and then encode and output it only once.
My PHP skills are a bit rusted, but I hope this one will work:
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
$output = array();
while($results = mysql_fetch_assoc($query)) {
// append row to output
$output[] = results
}
mysql_close(); // shouldn't that be outside the if block?
//encode the returned data in JSON format
echo json_encode($output);
}
I would expect the output then to be like this (maybe without indentation):
[
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
]
The problem lies in encoding and decoding of JSON. from your JSON response it looks like you are receiving JSON object from server also please try to validate you JSON response here. run your php file in browser, copy the entire response on the JSON validator and check the brackets that you are receiving the response in.
1. If your response starts with '[' it is and array and if it starts with '{' it is a JSON Object. while parsing JSON you have defined JSON array first but the server response is JSON object. While using JSON you have to be careful on server side for the format of response it will send and you have to be careful on the client side for the format of response you receive. I am posting example script for you.
-> Server side
if (mysql_num_rows($result)>0){
$response["data"] = array(); //this is an array
while($row= mysql_fetch_array($result))
{
$data = array(); //here I have created another temp array
$data["name"] = $row["name"];
$data["surname"] = $row["surname"];
array_push($response["data"], $data); //this makes an array of objects in the response
}}
}//endif
else{
echo "no input";
}}
mysql_close();
echo json_encode($response); //and finally I echo it as an JSON object
As this php script will return me one object of array of objects ( bit complex isn't it!!) below is the format of response
-> validated JSON response
{
"data": [
{
"name": "Setu",
"surname": "Desai",
}
]
}
and to decode this my client site script need to be the following
-> parsing JSON object
JSONObject snObject = new JSONObject(jsonString);
JSONArray snArray = snObject.getJSONArray("data");
for (int i = 0; i < snArray.length(); i++) {
JSONObject snObject2 = snArray.getJSONObject(i);
String surname = snObject2.getString("surname");
surnamearray.add(surname);
}
the simple way to understand is to validate you JSON response and identify the position of JSON array and objects and then start decoding.

Error Code #5fa01e33 in Java, Resulting from Access Google API Data

i'm having trouble with java programming. This java is calling Google API which provide me with GData access
I'm having trouble when it's querying some query, resulting #5fa01e33. This is my code:
package com.thegroovie;
import java.net.URL;
import javax.swing.JOptionPane;
import com.google.gdata.client.DocumentQuery;
import com.google.gdata.client.docs.DocsService;
import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.data.docs.DocumentListFeed;
public class GDataExample {
public static void main(String[] args) {
String username = JOptionPane.showInputDialog(null,"Input Username");
String password = JOptionPane.showInputDialog(null,"Input Password");
try{
DocsService service = new DocsService("Document List demo");
service.setProtocolVersion(DocsService.Versions.V3);
service.setUserCredentials(username, password);
URL documentListFeedUrl = new
URL("https://docs.google.com/feeds/default/private/full");
DocumentListFeed feed = service.getFeed(documentListFeedUrl, DocumentListFeed.class);
for(DocumentListEntry entry : feed.getEntries()){
System.out.println(entry.getTitle().getPlainText());
}
System.out.println("*******************************");
String input_query = JOptionPane.showInputDialog(null,"Search : ");
DocumentQuery query = new DocumentQuery(documentListFeedUrl);
query.setFullTextQuery(input_query);
DocumentListFeed feeds = service.getFeed(query, DocumentListFeed.class);
System.out.print(feeds);
}
catch (Exception ex){
System.err.println("Exception "+ ex.getMessage());
}
}
}
How to resolve this?
Thank you
This does not look like as an error code. Rather you print the DocumentListFeed object which type doesn't have an overridden toString method. You can access the feed's contents with the appropriate accessor methods described in the docs.

Categories