Posting a JSON to a Spring Controller - java

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.

Related

Spring MVC Ajax call POST not working

I have a form which I convert into an object. I wanna pass that object onto the server, a GET ajax request works fine but the object is empty in the java method, then I do the very same request but a POST request and it says error 404. Not sure what I'm doing wrong or what is, followed many examples, but neither of them seem to work.
GET REQUEST
(Ajax call)
$.ajax({
type: "GET",
url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
contentType: 'application/json',
dataType: 'json',
data: { medicalHistoryDTO : medicalHistoryDTO },
success: function(data) {
console.log(data);
}
});
(Object medicalHistoryDTO)
(Java Method)
#RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.GET)
public #ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
System.out.println(medicalHistoryDTO);
return "WORKING FINE";
}
(Eclipse console)
COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE
MedicalHistoryDTO [list=null, medicalHistorySignature=null]
(Browser console)
POST REQUEST
(Ajax call)
$.ajax({
type: "POST",
url: "/pp/portal/" + businessId64 + "/saveMedicalQuestionnaire",
contentType: 'application/json',
dataType: 'json',
data: { medicalHistoryDTO : medicalHistoryDTO },
success: function(data) {
console.log(data);
}
});
(Java Method)
#RequestMapping(value="/*/saveMedicalQuestionnaire", method = RequestMethod.POST)
public #ResponseBody String postEditMedical(MedicalHistoryDTO medicalHistoryDTO)
{
System.out.println("COMMON CONTROLLER POSTEDITMEDICAL SAVE MEDICAL QUESTIONNAIRE");
System.out.println(medicalHistoryDTO);
return "WORKING FINE";
}
(Browser console)
Keep using POST and to recieve you need to use #RequestBody tag
public #ResponseBody String postEditMedical(#RequestBody MedicalHistoryDTO medicalHistoryDTO)
You can see a working example from my code to https://github.com/shakeelabbas1/webservice/blob/master/src/main/java/com/service/controller/ServiceRequestController.java
Update:
I also see data: { medicalHistoryDTO : medicalHistoryDTO }
Replace it with data: medicalHistoryDTO
try to specify path more strictly
#RequestMapping(value="/{id}/saveMedicalQuestionnair", , method = RequestMethod.POST)
public #ResponseBody
String postEditMedical(MedicalHistoryDTO medicalHistoryDTO, #PathVariable("id") int id)

Ajax response arrives empty from spring controller, even if it succeeded

I received empty data from spring controller, even if it returned data the ajax success function received it empty. I tried to return string directly from controller like this:
#ResponseBody
#RequestMapping(value = "/test", method = RequestMethod.POST)
public String test(#RequestParam("posImsi") String posImsi,#RequestParam("posMsisdn") String posMsisdn){
return "success";
}
and the ajax is:
$.ajax({
url : "test",
type : "POST",
data : formData,
beforeSend : function(){
$("#overlay").show();
},
success : function(ajaxResult){
console.log(ajaxResult);
},
complete : function(status) {
},
error : function(jqXHR, status, errorThrown) {
alert(jqXHR);
alert(status);
alert(errorThrown);
}
});
The problem is solved by using the XMLHttpRequest object to do ajax request, I really don't know what is the difference but here is what I used:
var x = new XMLHttpRequest();
x.open("POST","test",true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.send(formData);
x.onload = function () {
console.log(this.responseText);
};
for more information about XMLHttpRequest object: http://www.w3schools.com/xml/dom_http.asp

Spring MVC Ajax POST

I'm trying to post a JSON Object, with Ajax, to an Rest Spring MVC Controller, but I met some troubles.
Let's present you my code:
Controller
#RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody JsonResponse checkUsername(#RequestBody JsonUsername username) {
String usernameString = username.getUsername();
JsonResponse response = new JsonResponse();
response.setMessage(usernameString + "Available");
return response;
}
Ajax Function
function displayUsernamError(data) {
var json = "<h4>Eroare</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#usernameError').html(json);
}
function checkUsername(){
var username = document.getElementById("username");
var search = {
"username" : username.value
}
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "http://localhost:8080/skill-assessment/register/checkUsername.html",
data : JSON.stringify(search),
success : function(result) {
console.log("SUCCESS: ", data);
displayUsernamError(result);
},
error: function(e){
console.log("ERROR: ", e);
displayUsernamError(e);
},
done : function(e) {
console.log("DONE");
}
});
}
And finally the html form:
<form:form modelAttribute="user" method="POST" enctype="utf8">
<tr>
<td><label>Username</label></td>
<td><form:input path="name" id="username" /></td>
<td>
<p id="usernameError">
</p>
</td>
</tr>
<button type="button" onClick="checkUsername()">Register</button>
</form:form>
So, I'm calling the checkUsername method when I press click on the Register button, only for test.
The ajax function is called and this send the JSON to the controller. I used the debug and the controller seems to get the JSON Object.
The problem is with the controller Response, because in the error div from my html page, I get this error:
HTTP Status 406
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request \"accept\" headers.
Where is the problem? Who can give me an idea?
You need to specify the below code inside of the request mapping annotation
#RequestMapping(value = "/register/checkUsername.html", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
you no need to specify the produces attribute because #Responsebody will produce the content based on the request object content type[optional]. if you want other then it then only you have to mention it.
; charset=utf-8 is the default one in Ajax call. you no need mention it separately. try do these changes.
use #ResponseBody need object to json,
seems missing some jar file
(jackson-mapper-asl.jar and jackson-core-asl.jar)
try to import it
First check if your controller is returning a JSON. You can use any REST client and see what is the return header. If not then add the Jackson mapper bean.
Also, try setting the Accept header in the ajax call.
$.ajax({
headers: {
Accept : "application/json",
Content-Type: "application/json"
},
data: "data",
...
})
in .js(java script)
ajax function
var variable="test";
$.ajax({
url: baseUrl + "nameController/test1",
async: false,
data: {val: variable},
dataType: 'html',
success: function (dat) {
console.log(dat);
}
});
you create nameController.java
controller
#RequestMapping(value = "test1", method = RequestMethod.POST)
public #ResponseBody
String checkRoomStatusReservation(#RequestParam(value = "val", required = true) String parse) {
System.out.println("parse"+parse);
//value from parse=test
return parse;
}
you can try this

can not able to call spring controller using ajax

I am trying to call a spring controller using ajax, but can not able to go to the controller. I am getting Error 405 Request method 'POST' not supported error. I am keeping my code here please give suggestion to come over it
this is my ajax code calling controller from jsp page, here i am getting the anchor attribute value.
basic.jsp
function organizationData(anchor) {
var value = anchor.getAttribute('value');
$.ajax({
url : "manageOrganization",
method : "GET",
dataType: "json",
contentType: 'application/json',
data: {organizationId : value },
success : function(response) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
controller
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}
here i should get the string to the jsp as a ajax response, but i am getting the error message. Any body can help me.
Regards Sree
For json response you need to add #ResponseBody annotation to your controller method.
You need to use type:"GET" not method:"GET" try it like,
$.ajax({
url : "manageOrganization",
type : "GET", // its type not method
dataType: "json",
.....
Read jQuery.ajax()
Also check that you are returning a json or not.
Your controller is returning String which may be resolved into some other jsp file IF you have configured viewResolver in spring configuration file. Try adding #ResponseBody like this:
#RequestMapping(value="/manageOrganization", method = RequestMethod.GET)
public #ResponseBody
String organizationData(#RequestParam String organizationId) {
return organizationId+" associated";
}

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>

Categories

Resources