Read json web service spring mvc - java

I have a spring mvc Web service like this:
#Controller
#RequestMapping("/hello")
public class helloWs {
#RequestMapping(value= "/getObj", method = RequestMethod.GET)
public
#ResponseBody
User prueba(#RequestBody User user) {
user.setEmail("sample_email#sample.com");
user.setName("sample_name");
user.setDeleted(true);
return user;
}
}
The jquery call to this Web service is:
function hellowsfunction() {
$.ajax({
type: "GET",
url:"http://localhost:8080/ehCS-ui/rest/hello/getUser",
dataType: "json",
success: function(msg) {
$('#lblResult').html('<p> Name: ' + msg.name + '</p>');
$('#lblResult').append('<p>email : ' + msg.email+ '</p>');
$('#lblResult').append('<p> deleted: ' + msg.setDeleted+ '</p>');
alert('Success: ' + response);
},
error: function (e) {
$("#lblResult").removeClass("loading");
alert('failed:'+e);
console.log(e);
}
});
}
And the result should be in a div like this.
<div id ="lblResult" style="color:blue;">result here</div>
But my javascript console show me this error all the time, and I don't know what is wrong.
Error. [object Object]
The web service is ok, but it seems that Jquery doesn't read the json obectj:
This is a user object that web service returns on the bowser.
{"version":null,"deleted":true,"insertDate":null,"updateDate":null,"owner":null,"userId":null,"name":"sample_name","surname1":null,"surname2":null,"login":null,"collegiateNumber":null,"nif":null,"email":"sample_email#sample.com","surname2Required":null,"telefonNumber":null,"birthDate":null,"inactive":false,"inactiveReason":null,"inactiveDate":null,"position":null,"professionals":null,"applications":null,"areas":null,"sexType":null,"locale":null,"password":null,"id":null}
Please help me. thanks a lot

It looks like you need to change:
$('#lblResult').append('<p> deleted: ' + msg.setDeleted+ '</p>');
to
$('#lblResult').append('<p> deleted: ' + msg.deleted+ '</p>');

Related

Posting a JSON to a Spring Controller

I'm learning to pass a JSON object through ajax to a Spring Controller.
Found an article, that seems to explain how its done: http://hmkcode.com/spring-mvc-json-json-to-java/
From that point i added a #RequestMapping to the Controller:
#RequestMapping(value = "/get-user-list", method = RequestMethod.POST)
public #ResponseBody String testPost(#RequestBody ResourceNumberJson resourceNumberDtoJson) {
System.out.println(">>>>>>>>>>>>>>>>>>>>>> I AM CALLED");
return "111";
}
Then i'm forming my ajax post:
var json = {
"login" : "login",
"resource_number" : "111",
"identifier" : "1111",
"registrator_number" : "11111111111111"
};
console.log(JSON.stringify(json));
$.ajax({
type : "POST",
url : "/get-user-list",
dataType : "text",
data : JSON.stringify(json),
contentType : 'application/json; charset=utf-8',
mimeType: 'application/json',
success: function(data) {
alert(data.id + " " + data.name);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
which is runned from "get-user-list" page.
When i'm trying to run this, i recieve a HTTP 415 error. Spring 4, Jackson 2.4
Cant understand what i'm doing wrong.
HTTP 415 means, that the media type is not supported.
Try changing your #RequestMapping annotation to
#RequestMapping(value = "/get-user-list",
method = RequestMethod.POST,
consumes="application/json")
You should also consider testing your REST-service with a client like RESTClient, Postman or even cURL to make sure it is working correctly before you start implementing the jQuery client.

How to pass json string from jsp page to Spring mvc controller?

I need to pass a json string from my jsp page to spring mvc controller.My JSON String and its passing using ajax call is shown below
var datejson = '{'
+'"startmonth" : smonth,'
+'"startday" : sday,'
+'"endmonth" : emonth,'
+'"endday" : eday'
+'}';
alert("json created");
//var jsonfile={json:JSON.stringify(datejson)};
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
dataType: 'json',
url: "/pms/season/json/",
data: JSON.stringify(datejson),
success: function(data) {
alert(data.startmonth + " " + data.endmonth);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
Every time my error function alerts.So how to pass it?
The code to recieve json in Controller class is shown below
#RequestMapping(value = "json", method = RequestMethod.POST)
public void validationDate( #RequestParam ("json") String datejson)
{
//System.out.println("JSON TEST");
System.out.println("JSON CONTENTS ARE::::::"+ datejson );
}
I am new to jquery.Any help will be highly appreciable...

Get response text from a JSONP request in Ext / Java Application

I am trying to connect a Java REST service to a ExtJs JSONP request but even though the java method executes I haven't been able to get a response test. This is what I am trying:
Java Code:
#Path("/hello")
public class Hello {
#GET
#Produces("text/javascript") // have also tried application/json
public String sayJsonHello(#QueryParam("_dc") String dcIdentifier, #QueryParam("callback") String callback) {
System.out.println(callback);
callback += "({\"success\":true, \"msj\":" + "\"" + "Exitoooo!" + "\" });";
System.out.println(callback);
return callback;
}
}
ExtJs code:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
params: {
},
callback: function (response) {
console.log(response); //true
console.log(response.result); //undefined
console.log(response.responseText); //undefined
console.log(response.success); // undefined
if (response.success === true) {
Ext.Msg.alert('Link Shortened', response.msj, Ext.emptyFn);
} else { // entering here :( why ?
Ext.Msg.alert('Error', response.msj, Ext.emptyFn);
}
}
});
response is printting true, everything else undefined :(
callback looks like this Ext.data.JsonP.callback1({"success":true, "msj":"exito"})
Any ideas what could be wrong?
Ok this worked out for me:
Ext.data.JsonP.request({
url: "http://10.1.50.66:7001/Simulador/webresources/hello",
callbackKey: 'callback1',
params: {
},
success : function(response) {
console.log("Spiffing, everything worked");
// success property
console.log(response.success);
// result property
console.log(response.result);
console.log(response.msj);
},
failure: function(response) {
console.log(response);
Ext.Msg.alert('Error', 'Please try again.', Ext.emptyFn);
}
});

Ajax json POST and Spring MVC Controller

I have ajax json POST method like this
$.ajax({
type: 'POST',
url: "localhost:8080/webeditor/spring/json/",
data: JSON.stringify(contents),
dataType: "json"
});
Controller to handle post request
JSONPObject json;
BindingResult result = new BeanPropertyBindingResult( json , "MyPresentation" );
#RequestMapping(value="json/", method = RequestMethod.POST)
public void savePresentationInJSON(Presentations presentation,BindingResult result) {
//do some action
}
but I getting this error
XMLHttpRequest cannot load localhost:8080/webeditor/spring/json/. Cross origin requests are only supported for HTTP.
I'm not sure how to correct above error.
My final work version
var jsonfile={json:JSON.stringify(contents)};
$.ajax({
type: 'POST',
url: "/webeditor/spring/json/",
data: jsonfile,
dataType: "json"
});
AJAX, and
#RequestMapping(value = "/json/", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json)
{
System.out.println( json );
}
Passing JSON with Spring is fairly straight forward. Consider the following jQuery function:
function processUrlData(data, callback) {
$.ajax({
type: "GET",
url: "getCannedMessageAsJson.html",
data: data,
dataType: "json",
success: function(responseData, textStatus) {
processResponse(responseData, callback);
},
error : function(responseData) {
consoleDebug(" in ajax, error: " + responseData.responseText);
}
});
}
Now use the following String #Controller method...
#RequestMapping(value = "/getCannedMessageAsJson.html", method = RequestMethod.POST)
public ResponseEntity<String> getCannedMessageAsJson(String network, String status, Model model) {
int messageId = service.getIpoeCannedMessageId(network, status);
String message = service.getIpoeCannedMessage(network, status);
message = message.replaceAll("\"", """);
message = message.replaceAll("\n", "");
String json = "{\"messageId\": \"" + messageId
+ "\", \"message\": \"" + message + "\"}";
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<String>(json, responseHeaders, HttpStatus.CREATED);
}
In my case the request is so simple that I'm just hardwiring the json formatting in the controller method, but you could just as easily use a library like Jackson to produce the json string.
Also as others have stated, verify that the "value" in the #RequestMapping is a unique, legitimate filename. With the json method I show above you don't have to have a corresponding jsp page (in fact it won't use one).
In the URL : url: "localhost:8080/webeditor/spring/json/"
webeditor must be war name or service name so in ur #RequestMapping(value="/webeditor/spring/json/" i think u should not have 'webeditor' it must be only /spring/json
normally 404 means the for the URL requst is wrong or no such service is running for that URL
Looks like jQuery so why not try
$.getJSON('webeditor/spring/json', JSON.stringify(contents, function(data) {//do callbackstuff});
If you wanted to request cross domain the way to do it is like :-
cbFn = function(data) {
// do callback stuff.
}
var ca = document.createElement('script');
ca.type = 'text/javascript';
ca.async = true;
ca.src = server + '/webeditor/spring/json.jsonp?callback=cbFn';
var s = document.getElementsByTagName('head')[0];
s.parentNode.insertBefore(ca, s);
and also add the servlet mapping
<servlet-mapping>
<servlet-name>yourSevletName</servlet-name>
<url-pattern>*.jsonp</url-pattern>
</servlet-mapping>
Your application should have a context root, which would precede the rest of your URL path. And you should also have a servlet-mapping defined in web.xml which defines which requests get directed to your Spring controllers. So if the context root of your application is "myapp" and your servlet-mapping is going to *.html, then your ajax call would look like this:
$.ajax({
type: 'POST',
url: "/myapp/webeditor/spring/json.html",
data: JSON.stringify(contents),
dataType: "json",
success: function(response) {
// Success Action
}
});
In yr jsp include the tag library like so
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
Then create a full url using spring
<c:url var="yourFullUrl" value="/webeditor/spring/json/" />
then create javascript variable based on this so you can use in Ajax
<script>
var yourUrl= '<c:out value="${yourFullUrl}"/>';
</script>
No use the javascriptvariable representing the url :
<script>
$.ajax({
type: 'POST',
url: yourUrl,
data: JSON.stringify(contents),
dataType: "json"
});
</script>

Access Jersey based RESTful service using jQuery

I am trying to access RESTful service, created on Java and deployed with help of Jersey using jQuery.
If I access it using browser I will get the result, but from jQuery, I am getting an error and can not see any results on the page.
Page with the script is hosting on local Apache server and the Service is running separately using Jersey/Grizzly on the same machine.
I can see that service is sending the response and it has 200 code, but I keep getting error from .ajax, without any details and
Any suggestions what is wrong?
Service:
#Path("/helloworld")
public class HelloWorldResource {
#GET
#Produces
public String test(){
System.out.println("Sending response");
return "test";
}
}
Main:
public static void main(String[] args) throws IOException {
final String baseUri = "http://localhost:9998/";
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages",
"resources");
System.out.println("Starting grizly");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format(
"Jersey app started with WADL available at %sapplication.wadl\n"
+ "Try out %shelloworld\nHit enter to stop it...", baseUri, baseUri));
System.in.read();
threadSelector.stopEndpoint();
System.exit(0);
}
JavaScript:
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
DataType: "text",
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
After a couple of days of research and experiments I discovered that the problem was in the headers of the response. To be able to use the response from the service, I added custom header field:
"Access-Control-Allow-Origin: *"
New service looks like this:
#Path("/helloworld")
public class HelloWorldResource {
#GET
#Produces
public Response test(){
return Response.ok("test").header("Access-Control-Allow-Origin", "*").build();
}
}
you have to set crossDomain to true to make cross domain requests
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
dataType:'html',
type:'GET',
crossDomain:true,
cache:false,
async:false,
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
UPDATE
if your service required the authentication may be you can do it like this
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
dataType:'html',
type:'GET',
crossDomain:true,
cache:false,
async:false,
xhrFields: {
withCredentials: true
},
username:'yourUsername', //not sure about the username and password options but you can try with or without them
password:'thePass',
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
also use jquery 1.5.1 or higher because the crossDomain and some other options are not available in the earlier versions. For reference see this link http://api.jquery.com/jQuery.ajax/
if you are using a javascript function to replace a typical form submission then pay attention to the fact that you should return false; at the end of your javascript function!
you can check a similar issue here http://forum.jquery.com/topic/jquery-newbie-3-9-2011
actually it is nota a matter of jersey but a matter of javascript

Categories

Resources