how to get JSON objects from servlet? - java

I am making a simple html servlet program where I need get JSON object from the servlet, and in html I am able to get the data, but how can i refer to each attribute?
Here is the servlet get method
PrintWriter out=response.getWriter();
StringBuffer emps = new StringBuffer("{employees:[");
emps.append("{fullname:\"Abhishek Raj Simon\"},{email:\"a#a.com\"}]");
emps.append("}");
out.println(emps);
JS to send
function getJson()
{
var url_action="/temp/jsontest";
var form=document.forms["mainForm"];
var splitOutput;
var client;
var dataString;
if (window.XMLHttpRequest){
client=new XMLHttpRequest();
} else {
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function(){
if(client.readyState==4&&client.status==200)
{
var res=client.responseText;
alert(res);
alert(client.responseText.employees.fullname); //DOES NOT WORK
alert(client.responseText.employees.email); //DOES NOT WORK
}
};
client.open("GET",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send();
and a simple form
<form>
<input type="button" value="get me some json" onclick="getJson();">
</form>
When i click on the button, i get only 1 alert displaying {employees:[{fullname:"Abhishek Raj Simon"},{email:"a#a.com"}]} How can i fetch Abhishek Raj Simon and a#a.com using fullname and email respectively?
Edited after reading post from Artem
my servlet
Gson gson = new Gson( );
List<Employee> employees = new ArrayList<Employee>();
Employee emp=new Employee();
emp.setFullname("Abhishek Raj Simon");
emp.setEmail("a#a.com");
employees.add(emp);
response.setContentType( "application/json");
out.println( gson.toJson( employees));
js part
var res=eval('(' + client.responseText + ')');
alert(res);
alert(res.employees.fullname);
alert(res.employees.email);

I think you should slightly change the JSON that you send form the servlet: {employees:[{fullname:"Abhishek Raj Simon", email:"a#a.com"}]} would work a bit better in that context.
I'd recommend jQuery as pap has also advised. The code would be:
$.getJSON('/temp/jsontest', function(data) {
var items = [];
for (employee in data.employees) {
items.push(employee.fullname + '<' + employee.email + '>');
}
alert('Employees: ' + items.join(', '));
});
In my opinion it is lot simpler and easier to understand than dealing with raw XHR. The jQuery $.getJSON will do GET for you, and then evaluate the JSON response so the function is presented with nice JSON representation of your data that is easy to manipulate.
EDIT:
After interesting discussion here is some more improvement you could introduce in order to replace the low-level code with proper JQuery-based implementation.
<script>
$(document).ready(function() {
$("#json-button").click(function() {
$.getJSON('/temp/jsontest', function(data) {
var items = [];
for (employee in data.employees) {
items.push(employee.fullname + '<' + employee.email + '>');
}
alert('Employees: ' + items.join(', '));
});
});
});
</script>
<form>
<input id="json-button" type="button" value="get me some json">
</form>

I would suggest you to use GSON library, which enables you to serialize Java object to json, to avoid writing it by yourself. If you do not want to use GSON, there are plenty of others libraries which uses same capabilities.
//inside your get method
Gson gson = new Gson( );
List<Employe> employees = new ArrayList<Employe>( );
// populate your list here
response.setContentType( "application/json");
response.getWriter( ).println( gson.toJson( employees));
//end
then in javascript you can do as it's already suggested in other answers here. And do pay attention to update response content type.

var res=client.responseText;
var temp = 'resObj=' + res;
eval(temp);
alert(resObj.employees.fullname);
JSON is just text, but in javascript syntax. You need to pass it through the "eval" method that will evaluate and execute the text as javascript.
My advice, though, is to use jQuery or some other javascript framework to avoid having to mess with all that boiler-plate javascript.

It's because you are receiving the JSON String but you're not converting it into a JSON Object. There's a eval() function that evaluates your JSON String and returns a JSON Object.
The following example should work (though untested).
if(client.readyState==4&&client.status==200)
{
var res=eval('(' + client.responseText; + ')');
alert(res);
alert(res.employees[0].fullname);
alert(res.employees[0].email);
}
WARNING: I suggest reading the security concerns when using eval(). Alternatively, go to JSON.org and download a Javascript JSON parser or use JQuery instead.

Related

struts2 ajax call response always shows null

I am trying to call the struts2 action class from my jsp using ajax. I can hit the action class and able to pass the parameters to action class. But the response that comes from action class to my ajax request is always null
All setters and getters are set correctly and they are working fine when I see in debug sysouts
Action Class
#Override
#Action(value = "/search",
results = { #Result(name = "success", type="json")})
public String execute() throws ParseException
{
this.setName(this.term+": "+this.pos);
System.out.println("Name: "+Name);
JSONObject json = (JSONObject)new JSONParser().parse(Name);
return ActionSupport.SUCCESS;
}
jsp
function Search()
{
var term = document.getElementById("term").value;
var pos = document.getElementById("pos").value;
var itr = document.getElementById("itr").value;
var pri = document.getElementById("pri").value;
var atb = document.getElementById("atb").value;
var jsonData = {};
jsonData.term = term;
jsonData.pos = pos;
jsonData.itr = itr;
jsonData.pri = pri;
jsonData.atb = atb;
$.ajax({
type: "POST",
url: "search",
dataType: "json",
data: jsonData,
success: function(response){
console.log(""+response);
alert('Name: '+response.Name);
//alert('Length: '+data[0].length);
/* $.each(data[0],function(index, value){
alert("value " +value);
});*/
},
error: function(response){
alert(response);
alert(response.length);
$.each(response,function(index, value){
alert("value " + value);
});
}
});
}
I can see the response always as null. I am not sure what is going wrong, but seems the coding part is correct. Am I doing some mistake in ajax call?
As clearly explained in this answer, you need to use the JSON plugin, that will serialize the entire action (or a single root object when needed). You don't need then to do the parsing yourself, just evaluate the name variable.
To send JSON from JSP to action instead you need to use the JSON Interceptor in your stack.
Ensure you have getters and setters for everything.
Your Name variable should be name, both in Java and in Javascript. Only the accessors / mutators should use the capitalized N (getName, setName).
If the error persists, check carefully console and logfiles for errors, with devMode set to true.
Since this comment has gone too far, I've turned it into an answer :)

How to pass Json Code in Java to Javascript

Im trying to pass a Collection of items converted into String with JsonArray to my Javascript but dont work.
This is the code of the class
InformeAmenazasAGR = manager.preparaInformeRiesgoActivos(idDimension, tipoActivo, idActivo, tipoActivoTexto, nombreActivo, recursos);
JSONArray JSonArray = new JSONArray();
JSonArray.put(InformeAmenazasAGR);
String texto = JSonArray.toString();
//Delete the first and last char.
texto = texto.substring(1, texto.length()-1);
request.setAttribute("InformeAmenazasAGR", texto);
return mapping.findForward( "informeActivosAGR" );
This returns one String like this:
[
["16","E.1","Errores de los usuarios","7","1128750","1015875"],
["20","E.5","Deficiencias en la organizaciĆ³n","7","752500","526750"],
]
My JSP with Javascript (im using ExtJS and follow I tried Passing a Java string to Javascript post but dont work)
var DatosAmenazas = new String("<%request.getAttribute("InformeAmenazasAGR");%>");
var amenazaStore = Ext.create('Ext.data.Store', {
model: 'Amenazas',
data: DatosAmenazas
});
What am i doing wrong?
Thank you in advance
EDIT: If i put the raw String that i save in request.setAttribute("InformeAmenazasAGR", texto); it works:
var amenazaStore = Ext.create('Ext.data.Store', {
model: 'Amenazas',
data: [
["16","E.1","Errores de los usuarios","7","1128750","1015875"],
["20","E.5","Deficiencias en la organizaciĆ³n","7","752500","526750"],
]
});
I think using the Java scriptlet inside javascript is not good practice,
instead you can use the $(InformeAmenazasAGR) to set the request attribute value to a hidden element and put the hidden element anywhere inside your html <body> like this,
<input type="hidden" id="jsonData" value="${InformeAmenazasAGR}">
then, get the hidden element value like,
var DatosAmenazas = new String($('#jsonData').val());
if you need the request attribute InformeAmenazasAGR to be converted into json data then instead of above you can change your above line as,
var DatosAmenazas = JSON.parse($('#jsonData').val());
FYI: Java scriptlets run on server side while javascript on client side

Getting Request parameters from Ajax Response

I am making ajax call to a java method for every 30 seconds.
I am setting few request parameters in the java method.
How can I get them from ajax response.
<script LANGUAGE="JavaScript1.2">
var tId = window.setTimeout(function () {
location.reload(true);
alert('<s:property value="#disableReload" />');
if('<s:property value="#disableReload" />' == "true"){
alert("clearing");
}else{
var url = 'moveETHAction_fetchExecutorData.action';
var form = document.getElementById('moveForm');
var params = Form.serialize(form) + '&ms=' + new Date().getTime();
form.action = "fetchExecutorData";
var myAjax = new Ajax.Request(url, {method: 'post', parameters: params, onComplete: showResponseAction} );
}
}, 30 * 1000);
function showResponseAction(originalRequest){
alert(originalRequest.responseText);
alert('<s:property value="#request[\'DISABLE_FLOW'\]" />');
document.getElementById('actionChange').innerHTML = originalRequest.responseText;
}
</script>
In Java method I am setting this parameter
request.setAttribute(GenericConstants.DISABLE_FLOW, false);
But I am not getting the updated value from the ajax
Any changes to the HttpServletRequest on the server side will not be visible on the client side. Moreover setAttribute method will not affect the incoming HTTP request string. It's additional store within HttpServletRequest to pass-around information on the server-side.
You need to add the information to the existing response, in a structured away (JSON is preferable for your client to convert into a javascript object right away and access the individual values within response). Hope this helps.

How to show value from database to jsp without refreshing the page using ajax

I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.

java equivalent of swfobject

looking for a javascript class like swfobject to embed java and have a simple fallback if the user doesn't have java or refuses the security prompt.
thanks,
Josh
You could build one pretty easily.
Have something like a div set up like this:
<div id="java-applet">
Message to user saying that they need Java here
</div>
Then add Java Plugin Detection (builder) to your JavaScript. Then if that returns true, then do something like:
document.getElementById("java-applet").innerHTML = "<applet>stuff here</applet>";
appletobject may work, but I have not used it.
Just embed the applet like you normally do and insert the fallback inside or insert a javascript snippet to remove the object: Besides param, you can add other elements, e.g. paragraphs with text or javascript calling some function to replace the object.
<script type="text/javascript">
function replace_object(x) {
$(x)...
}
</script>
<object x="y" id="some_applet">
<param name="y" value="z">
<p>java not available. some alternative here. <!-- option 1 --></p>
<script type="text/javascript">
replace_object('some_applet'); // option 2
</script>
</object>
This helps!
I got a very strange problem while using applet to do batch file downloading from the server side.
The Ajax request seems conflict with applet request, the applet file downloading interrupted with some socket exception.
The applet works fine under JRE5.0, it might be caused by our recent upgrade to JRE6.0.
<div id="java-applet"></div>
<script>
var t;
function startApplet() {
var attributes = {codebase:'<%=request.getContextPath()%>',
code:'<%=appletClass%>',
archive:'applet/SignedApplet.jar',
width:0,
height:0} ;
var parameters = {para1:'value1',
para2:'value2',
java_arguments:'-Xms64m -Xmx512m'
} ;
var version = '1.6' ;
var buildAppletTag = function() {
var tag = '<applet';
for (var attribute in attributes){
tag += (' ' + attribute + '="' + attributes[attribute] + '"');
}
tag += ">";
for (var parameter in parameters){
tag += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
tag += '</applet>';
return tag;
};
document.getElementById("java-applet").innerHTML = buildAppletTag(attributes, parameters, version);
clearTimeout(t);
}
t = setTimeout("startApplet()", 1000); // delayed
</script>

Categories

Resources