Java serverlet parse JSON data - java

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());

Related

Retrieve a given string by Ajax - struts 2 [duplicate]

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"));
}

How is the data passed from JSON to AJAX?

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>');

Returning Hashmap From controller to JSP in Springmvc

I have two dropdownlists in Jsp One for state and other for country. As soon as i select country the statelist should be populated automatically with respective lists. But i am getting whole jsp page as response in ajax call.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My controller program
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public ModelAndView showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, Model model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
if (country.equals("UnitedStates")) {
stateMap.put("Al","Alaska");
stateMap.put("Tl","Texas");
} else if (country.equals("UnitedKingdom")) {
stateMap.put("Be","Bedfordshire");
stateMap.put("Ber","Berkshire");
} else if (country.equals("India")) {
stateMap.put("Mh","Maharashtra");
stateMap.put("WB","West Bengal");
stateMap.put("KR","Karnataka");
stateMap.put("AP","Andhra Pradesh");
stateMap.put("TN","Tamil Nadu");
}
return new ModelAndView("LoginForm","state" ,stateMap);
}
I am using spring form. I need to get only Staemap as respone but i am getting whole jsp page as response.
I need to get only Staemap as respone but i am getting whole jsp page
as response.
Because you are returning the ModelAndView object with the view here,
return new ModelAndView("LoginForm","state" ,stateMap);
If you need to return the respone alone from the controller method.However you cant print the HashMap directly in the ajax response on your jsp. IMHO you can convert it to JSONArray
JSONArray jarray = JSONArray.fromObject(statemap);
Read ,
send array from controller to a view using JSON in MVC
Sending JSON response from spring controller
loop through json array jquery
#RequestMapping(value="LoadBaselineVersions")
#ResponseBody
public Map<Integer,String> loadBaseNames(#RequestParam(value="projectname") String name,HttpSession session){
return basenameService.getBaselineversions(name);
}
$("#projectname").bind(
'blur',
function() {
$.ajax({
type : 'post',
url : 'LoadBaselineVersions?projectname='
+ $("#projectname").val(),
dataType : 'json',
success : function(data) {
$("#baseversion").empty();
$.each(data, function(val, text) {
$("#baseversion").append(
$('<option></option>').val(text).html(
text));
});
}
});
});

get json array from servlet using ajax

I have to json array in my servlet.
I want to fetch json array value and print in to jsp page using ajax.
below is code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
jsp
I got error msg here.
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
error : function() {
alert("Error");
},
success : function(data) {
alert(data);
}
});
See, if you want to pass that from servlet to jsp you need not to make a request (ajax), since servlet and jsp both exists at server side.You just set that json array as a request attribute or session attribute and get it in jsp and display(with loop).NO need of ajax there.
If You need to fetch the data with synchronous call:
In servlet
PrintWriter out = response.getWriter();
out.println(htags);
I won't clutter SO with another full example,see this SO post:How to send JSON array from server to client, i.e. (java to AJAX/Javascript)?
Try this
servlet code
JSONArray htags = new JSONArray();
htags.add("#abc");
htags.add("#xyz");
htags.add("#emc");
htags.add("#netapp");
//top trends
JSONArray trends = new JSONArray();
trends.add("pass");
trends.add("horiz");
trends.add("software");
trends.add("banana");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String jsons = "["+htags+","+trends+"]"; //Put both objects in an array of 2 elements
out.print(jsons);
and on you jsp page
$.ajax({
url : "SerlvetToJsp",
dataType : 'json',
contentType:"application/json",
error : function() {
alert("Error");
},
success : function(data) {
var data1=data[0],
var data2=data[2],
alert(data1[0]);
}
});
Servlet can use this to send json array or json object to client.
JSONArray jsonArray = [{:}, {:}];
response.getWriter.write(jsonArray.toString());
In JSP page, this method call the request JSON to Servlet and catch the json array or json object with annonymous function(JSON.parse is used to convert string to json object or json array) method.
$("button").click(function(){
$.get("ServletToJSP",function(data,status){
alert("Data: " + JSON.parse(data) + "\nStatus: " + status);
});
});
in servlet:
String uri = request.getRequestURI();
if (uri.equalsIgnoreCase(uri)) {
response.setContentType("application/json");
/* get the json array */
response.getWriter().write(array.toJSONString());
}
jquery:
$('#buttonid').on('click', function() {
var url="your url";
$.ajax({
type : 'POST',
url : url,
data : null,
error : function(xhr, status, error) {
alert("error");
},
success : function(data) {
alert("success");
$.each(data, function(key, val) {
console.log(val);
}
});
});

Servlet+jQuery/Ajax - Unexpted token o

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

Categories