I have the following controller:
#RequestMapping(value = { "/member/uploadExternalImage",
"/member/uploadExternalImage" }, method = RequestMethod.POST)
public String handleFileUpload(#RequestParam("url") String url,
Principal principal) throws IOException {
File file = restTemplate.getForObject("url", File.class);
file.toString();
return null;
}
And I have the following ajax:
$.ajax({
url: 'uploadExternalImage', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
// Form data
data: {url: files[0].link},
cache: false,
contentType: false,
processData: false
});
in spring log I see that
org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'url' is not present
if I change ajax method with GET:
$.ajax({
url: 'uploadExternalImage?url=123', //Server script to process data
type: 'POST',
success: function () {
},
complete:function(){
$.fancybox.hideLoading();
},
error: function (data) {
},
cache: false,
contentType: false,
processData: false
});
it works fine
How does to configure spring correctly?
Http POST is capable of being used for request parameters on request body. But you are trying to use it on a different way.
Try this:
$.ajax({
type: 'POST',
url: "uploadExternalImage?url=BLABLA",
data: text,
success: function (data) {
//
}
});
If you want it on request body then use #RequestBody
Related
here is my code,I am using angular and spring mvc . Please suggest me the way
vm.upload= function(state_cd){
fd= new FormData();
fd.append("mst.distCd", dist_cd);
call(fd);
});
}
function call(fd){
$http({
type: "POST",
url: "./WQF00069/update.app",
data: fd,
processData: false,
headers: { 'Content-Type': undefined},
transformRequest: angular.identity,
cache: false,
timeout: 600000,
}).success(function(data) {
Flash.create('info', ' Update Success Fully ', 'large-text');
}).error(function(response){
console.dir(response);
Flash.create('danger','There is a Problem.Contact With Administrator', 'large-text');
});
}
After send to my controller get get 415 error
I am sending a POST request:
var arr = { State: 'Moscow', Age: 25 };
var url = "/google/modifiedPolygon";
$.ajax({
url: url,
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function() {
alert("msg");
}
});
And handling from backend as:
#RequestMapping(value="/modifiedPolygon",method = RequestMethod.POST,consumes = "application/json")
public void modifiedPolygon(#RequestBody JSONObject data, HttpServletRequest request, ModelMap model) {
System.out.println(data);
}
But I am getting following error:
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read JSON: Unrecognized token 'State': was expecting
('true', 'false' or 'null')
It looks like State is a boolean type on the service side, But you are sending String value as State. So verify the datatype for State the service exepcting.
I have tried the following Java implementation and it seems working.
#RequestMapping(value="/modifiedPolygon",method = RequestMethod.POST,consumes = "application/json")
public ResponseEntity<JSONObject> modifiedPolygon(#RequestBody JSONObject data, HttpServletRequest request, ModelMap model) {
return new ResponseEntity<JSONObject>(data,HttpStatus.OK);
}
First test with POSTMAN or curl, if issue persists, try with this.
var arr = { state: 'Moscow', age: 25 };
var url = "/google/modifiedPolygon";
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function() {
alert("msg");
}
});
And please enable the CORS filters.
Here are the working snapshot.
Add this dependency to pom.xml
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
Please find the java code changes here
https://github.com/supun/Shopping/blob/master/src/main/java/com/shopping/controller/MainController.java
You can use like this,
var arr = { state: 'Moscow', age: 25 };
var url = "/google/modifiedPolygon";
$.ajax({
url: url,
type: 'POST',
data: { "dataValue": JSON.stringify(arr)},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function() {
alert("msg");
}
});
now, you can get "dataValue" in backEnd from body param.
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)
I have a Spring MVC controller that I am calling via JQuery.ajax.
The mapping in the controller is:
#RequestMapping(value = "/remove", method = RequestMethod.POST)
#ResponseBody
public void remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
}
The ajax call is:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
The POST call completes successfully with HTTP status 200. However, in the Firefox console the following is output:
no element found ... myscript.js:1
If I change my controller to return a boolean then this error disappears. However, according to this question having #ResponseBody on a method with void return type is valid.
Is there anything I can change to remove this message?
As described in the JQuery Bugs and in Firefox Bug, it is a Firefox problem that occurs when response entity body is null.
To fix it, you have to return such a ResponseEntity in your Controller method.
Try to add dataType: 'text' in your request:
$.ajax({
url: '/appserver/model/remove',
data: { value1: value1, value2: value2 },
type: 'POST',
traditional: true,
dataType: 'text',
success: function() {
// do something on success
},
error: function(jqXHR, textStatus, errorThrown) {
// do something on error
}
});
and modify your Controller to return a ResponseEntity with a String as first parameter
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public ResponseEntity<String> remove(#RequestParam("value1") String value1,
#RequestParam("value2") String value2)
{
// do stuff
return new ResponseEntity<String>("OK!!!",HttpStatus.NO_CONTENT);
}
I have the restful webservices call from the Jquery ajax and getting the response in json object.
Jquery HTML:
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
},
error: function (error, data) {
console.log(error);
}
});
}
});
And writing the response object for the restful webservices in java
#POST
#Path("api/{subsystem}")
#Produces("application/json")
public Response changeStatus(#PathParam("subsystem") String subsystem,
/*#FormParam("result")*/ String result) {
}
I got the response below and which is correct
changeStatus:88 - Reponse OutboundJaxrsResponse{status=200, reason=OK, hasEntity=true, closed=false, buffered=false}
Depending upon the reponse need to update the status whether the value is on/off in the label tag.
str = ' Status : ' + '' + onoffStat + '';
How can I achieve this in ajax and want to have the refreshing the div tag for every 2 seconds.
Please help me.
You will have to use Javascript polling. Try out something like this:
function ajaxPoll(){
$.ajax({
url: "mcrs/object/api/Lighting",
type: "POST",
traditional: true,
dataType: "json",
contentType: "application/x-www-form-urlencoded",
async: "false",
data:JSON.stringify(postdata),
success: function (ResData) {
tag.str = 'Status : ' + '' + ResData.status + '';
},
error: function (error, data) {
console.log(error);
}
});
}
});
}
setInterval(ajaxPoll, 2000);
Hope you sort it out :)