I'm new to developing web applications with Java. I'm trying to establish an AJAX call. This is some arbitrary code that I've created.
Servlet
Map<String, String> testJson = new HashMap<String, String>();
String Key = "someKey";
String Value = "someValue";
testJson.put(Key, Value);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(testJson));
}
jQuery
$(document).on("click","#register-user", function(){
$.ajax({
type: 'GET',
url: 'Register',
success: function(data){
alert($.parseJSON(data));
}
});
return false;
});
The callback function is working without any Json so the AJAX is fine. But when I try to send back a Java object that is encoded with Json I get an "Uncaught exception. Unexpected token o". What am I doing wrong?
Try this
Gson gson = new GsonBuilder().create();
String json = gson.toJson(testJson);
or try a little something like this
Type typeOfMap = new TypeToken<Map<String, String>>() {}.getType();
String json = gson.toJson(map, typeOfMap);
More examples of the above on this link
and then return the Stringed JSON
Related
I am planning to post entire form data in JSON format to Struts2 Action. Below are my code snippets. Correct me where I am going wrong or Help me so that I can get all values in the Action file correctly. All of my SOPs in Action file is displayed as null
var MyForm = $("#companyform").serializeArray();
var data = JSON.stringify(MyForm);
$.ajax({
type: 'POST',
url:'createcompany.action?jsonRequestdata='+data,
dataType: 'json',
success: function(data){
console.log(stringify(data));
}});
My form data is turned into [{"name":"tan","value":"rrr"},{"name":"pan","value":"adf"},{"name":"tod","value":"1"}]
Struts2 Action File:
String jsonRequestdata;
public String execute() throws Exception {
JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata);
JSONObject json = (JSONObject) jsonArr.get(0);
System.out.println("TAN=" + json.get("tan"));
System.out.println("PAN=" + json.get("pan"));
System.out.println("TOD=" + json.get("tod"));
return "success";
}
Present OUTPUT
TAN=null
PAN=null
TOD=null
To send data with the POST request you should use data property like this
$.ajax({
type: 'POST',
url:'createcompany.action'
data: 'jsonRequestdata='+data
dataType: 'json',
success: function(data){
console.log(JSON.stringify(data.jsonRequestdata));
}
});
To get the data in the action bean you need to use public setter
public void setJsonRequestdata(String data){ this.jsonRequestdata = data; }
To return data back to the success callback function use public getter
public String getJsonRequestdata(){ return this.jsonRequestdata; }
To return JSON from the action use result type json.
<result type="json"><param name="includeProperties">jsonRequestdata</param></result>
Note, if you add json interceptor to the action config you can use JSON data in the request. Using Content-Type: "application/json" with the request will trigger Struts2 to parse the request and deserialize it to the action bean automatically.
Since I am using name,value I must get it by using name. Below is the working code
JSONArray jsonArr = (JSONArray) new JSONParser().parse(jsonRequestdata);
for(int i=0;i<jsonArr.size();i++){
JSONObject json=(JSONObject) jsonArr.get(i);
System.out.println("name=" + json.get("name"));
System.out.println("value=" + json.get("value"));
}
I want to post JSON object from JavaScript to java serverlet.
I used the following javaScript code :
var a = {};
function SaveInfo(c)
{
document.getElementById("saveButton").className = "savebutton";
document.getElementById("cancelButton").className = "cancebutton";
var z= $(c).parent().parent().attr('id');
a[z] = c.value;
}
$("#saveButton").click(function(e){
if( document.getElementById("saveButton").className=="savebutton")
$.ajax({
url: "../../update",
type: 'POST',
dataType: 'json',
data: JSON.stringify(a),
contentType: 'application/json',
mimeType: 'application/json',
success: function (data) {
consol.log(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
});
and following java code :
public void doPost(HttpServletRequest req, HttpServletResponse res){
JSONObject jObj;
jObj = new JSONObject(req.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys();
while(it.hasNext())
{
String key = (String)it.next(); // get key
Object o = jObj.get(key); // get value
// store in session
}
}
JSON is successfully received.
Problem is there is no constructor for :
jObj = new JSONObject(req.getParameter("mydata"));
I want to read both values and keys passed via javascript.
For your purpose you can simply use a form, simply parse it like:
Map<String, String[]> map = request.getParameterMap();
for(Entry<String, String[]> e : map.entrySet()){
response.getWriter().write(e.getKey() + ":" + e.getValue()[0] + "\n");
}
Use json when you want to send an object or a complex data array etc.
Hope that completes your work.
Try the following:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(req.getParameter("mydata").toString());
What I am trying to do is initiate an ajax call from my frontend code by user interaction. This calls a Java Restful service that I have written. And this Java function calls another service.
I need that java service in the middle because I need to send the inputs to other service in the format of "MyModel".
The problem is, the AJAX call works but it cannot get the JSON object that I send. You see in the Java function below I create the "param1" : "asdasd" for the second time there. That's because it cannot get the JSON data from front-end. It should be dynamically created with the argument of sendInputs function.
By the way when I debug the value String input is like this: ""
Javascript AJAX call:
var paramData = {"param1" : "asdasd"};
$.ajax({
type : 'GET',
url : "/api/v2/proxy",
dataType : "json",
headers : {
"Service-End-Point" : "http://localhost:9000/service/myService/sendInputs"
},
statusCode : {
200 : function(data) {
}
},
contentType : "application/json",
data : JSON.stringify(paramData),
error : function(error) {
}
});
Java consume:
#GET
#Path("/sendInputs")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String sendInputs(String input) {
String result = null;
//define the service endpoint to be added the default URL
String serviceEndpoint = "otherService/tool/runTool";
List<MyModel> modelParameterList = new ArrayList<MyModel>();
MyModel inputParameter = null;
inputParameter = new MyModel("param1", "asdasd");
modelParameterList.add(inputParameter);
//convert the Java Map to a json string using Jackson ObjectMapper
String jsonStringOfInputParameters = toJSON(modelParameterList);
WebClient client = WebClient
.create("http://localhost:9000");
result = client.path(serviceEndpoint)
.query("tool", "myTool")
.query("input", jsonStringOfInputParameters)
.accept("application/json")
//tells cxf to convert the json to a string type upon return
.get(String.class);
// Return the json result as a string
return result;
}
your paramData variable is already a valid json. I do not think you need yo use JSON.Stringify() again.And what is this is the ajax call:
statusCode : {
200 : function(data) {
}
}
Status code is supposed to be coming from the server in response.
First, your ajax header should be like this:
headers: {
Accept: "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8"
},
url:
url: "http://localhost:9000/service/myService/sendInputs"
Second, you need to have MyModel with param1 field and Also setters and getters. And this can be your service method:
public String sendInputs(MyModel model)
{
//model.getParam1() will be "asdasd"
}
I'm facing difficulties understanding the logic here. Ok, so let's say I have a class
#RequestMapping(value="/GetPersons", method = RequestMethod.GET)
public void loadPersons(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException {
OutputStream out = response.getOutputStream();
List<Person> persons = personDAO.loadPersons();
Iterator iterator = persons.iterator();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
while (iterator.hasNext()) {
JSONObject object = new JSONObject();
object.put("name", person.GetName());
jsonArray.add(object);
}
jsonObject.put("data", jsonArray);
OutputStreamWriter writer = new OutputStreamWriter(out);
try {
writer.write(jsonObject.toString());
}finally {
writer.close();
}
}
And then I have a simple script in my index.jsp
function loadPersons(json) {
var obj = JSON.parse(json);
var Person = obj.data;
for (i = 0; i < myArr.length; i++) {
$('#myId).append('<li>Test</li>');
}
}
$.ajax({
url: "http://localhost:8080/Persons/getPersons",
success: function (data) {
loadPersons(data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
So my question is the following... What is the logic that goes on here? How is the JSONObject data passed to the $.ajax success and the function. The function takes an argument "data" but what is going to be passed? The whole getPersons method from the java or?
The point here is to dynamically populate a simple dropdown by calling json object with ajax.
In your loadPersons method, you use the JSONObject and JSONArray classes to build a Java representation of a JSON object that will look like this:
{
"data": [
{
"name": "whatever person.getName() evaluated to"
},
{
"name": "another person.getName() call"
}
]
}
This is the JSON data that is sent, as text, in the response from your servlet.
The jQuery ajax function does additional work with this response, finally turning it into a Javascript object, which is then passed to your success callback as the data parameter. This Javascript object looks similar:
{
data: [
{
name: "whatever person.getName() evaluated to"
},
{
name: "another person.getName() call"
}
]
}
And you could access the value of the first name with: data.data[0].name
In this specific case, you're writing the JSON string content directly in the response of the request. This is done in these lines:
//Obtain the output stream from the response
OutputStream out = response.getOutputStream();
//Wrap the output stream into a writer
OutputStreamWriter writer = new OutputStreamWriter(out);
try {
//write in the writer that will write on the HTTP response
writer.write(jsonObject.toString());
}finally {
//close writer and free resources
writer.close();
}
So, the response from the server will be a string that contains your data. This comes from these lines of code:
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
while (iterator.hasNext()) {
JSONObject object = new JSONObject();
object.put("name", person.GetName());
jsonArray.add(object);
}
jsonObject.put("data", jsonArray);
Then, the $.ajax from jquery will execute the callback function defined in success, where it receives the response from the server as the argument:
$.ajax({
//removed code for explanation purposes...
success: function (data) {
//data is the response from the server on a successful execution
//of the HTTP request to the server
//do something here with the response from the server
//in this case, call the loadPersons function
loadPersons(data);
}
});
In loadPersons function, you deserialize the data from the json string into a JavaScript json object, then create HTML from the json data there.
First click the link http://localhost:8080/Persons/getPersons on any browser,if your spring service is running currently,you will see JSON data in your browser. The same data is getting fetched by the AJAX call inside your index.jsp.
$.ajax({
url: "http://localhost:8080/Persons/getPersons",
success: function (data) {
loadPersons(data);
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
P.S - i think you will have to add below line also to this ajax call
dataType :'json'
In the ajax call, success and failure are callback function which are invoked when browser get the response from server,success is executed in case of (2XX) while failure is invoked in case of error response,success function takes an argument data,which is JSON,same as you would have seen in your previous step.
Then as you received data from server,it is in JSON format(I suppose),you will have to parse it to convert it to object,and then you are fetching the data and setting it to the html elements.
$('#myId).append('<li>Test</li>');
I'm unable to get data back from ajax request from java servlet using Json object..here is the code below we are using channel api in google app engine .we need to implement chat application.
displayFriendList = function() {
var txt = document.createElement("div");
txt.innerHTML = "<p> Logged in as <b>" + userid
+ "</b><p><hr />";
document.getElementById("friendlistdiv").appendChild(
txt);
var dataString ='userId='+userid;
$.ajax({
type : "POST",
url : "/OnlineUserServlet",
data : dataString,
success : function(html) {
alert(html.frndsList[0].friend);
}
});
};
Java Servlet Code:
while(friendList.hasNext()){
friend = friendList.next() ;
if(!friend.equals(user)){
Map<String, String> state = new HashMap<String, String>();
state.put("friend", friend);
state.put("type","updateFriendList");
state.put("message",user);
state1.add(state);
message = new JSONObject(state);
channelService.sendMessage(
new ChannelMessage(friend,message.toString()));
}
i++;
}
Map<String, String> statejason = new HashMap<String, String>();
statejason.put("friendsList", state1.toString());
//System.out.print("hello"+message.toString());
response.setContentType("text/plain");
response.getWriter().print(statejason.toString());
}
Your response type should be application/json.