Spring Restful Array object as input - java

I am reading empty data in server side. Please help.
my java script code snip:
$.ajax({
type: "post",
url: "services/save",
data: items,
success: saveSuccess
});
JSON data:
[{"id":"SRMS12345","status":"backlog","text":"Make a new Dashboard","content":"New content","tags":"SRMS12345,05-Jul-16","color":"#ffcc66","resourceId":"A70729","className":""},{"id":"SRMS17147","status":"sit","text":"Prepare new release","content":"New content","tags":"SRMS17147,05-Apr-16","color":"#ff7878","resourceId":"A70729","className":""},{"id":"INC2311424","status":"pv","text":"One item added to the cart","content":"New content","tags":"INC2311424,06-Jun-16","color":"#96c443","resourceId":"C02153","className":""},{"id":"INC3215575","status":"uat","text":"Edit Item Price","content":"New content","tags":"INC3215575,02-Oct-16","color":"#96c443","resourceId":"A71787","className":""},{"id":"SRMS15645","status":"backlog","text":"Login 404 issue","content":"New content","tags":"SRMS15645,02-Aug-16","color":"#96c443","resourceId":0,"className":""}]
Rest Controller:
#RestController
public class Services {
#RequestMapping(value="/save", method=RequestMethod.POST)
public boolean saveTaskStatus(ArrayList<AssignmentVO> assignments) {
System.out.println(assignments);
return true;
}
}
Output:
[]

I think you are not telling Spring where is the data that you're sending.
You need to add #RequestBody to the assignments parameter, so Spring can know where the data is.
You can read this article. http://www.leveluplunch.com/java/tutorials/014-post-json-to-spring-rest-webservice/

I finally got it working. Thanks to reos.
I had to add the following to get it work
#ResponseBody to method Parameter (Thank you reos)
add ContentType and dataType to Ajax call
Add JSON.stringify to ajax call. Ajax call does not stringify automatically
Here is the code
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: "services/save",
data: JSON.stringify(items),
success: saveSuccess
});

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)

Parsing JSON server side in Java?

Client side I have:
keyList = ["560", "565", "566"]
I need to send it to server with POST request.
So, I decided to use JSON.
var jsonString= {keyList:JSON.stringify(keyList)};
$.ajax({
type: 'POST',
url: url,
data: {"keyList":jsonString},
dataType: "json"
});
Server side I done:
#RequestMapping(value = "/Controller/parsingJSON", method = RequestMethod.POST)
public void parsingJSON(#RequestParam("keyList") String keyList, HttpServletResponse response, HttpServletRequest request){
List<String> listRes= new ArrayList<String>(Arrays.asList(keyList.split(",")));
System.out.println(listRes);
}
listRes = [["560", "565", "566"]]
If I print the first element I get ["560"
I need the listRes was ["560", "565", "566"] and not [["560", "565", "566"]].
If you send JSON string as parameter to keyList, you should do it like this
$.ajax({
type: 'POST',
url: url,
data: {"keyList":JSON.stringify(keyList)},
dataType: "json"
});
On the server you will get a JSON string, and if you want to deserialize it to object you should manually parse this string.

Multiple ajax data to Spring MVC controller

I need to send data to Spring MVC controller by ajax. But controller doesn't work if I send more than one parameter.
Controller method:
#Timed
#RequestMapping(value = "saveee", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
With this ajax code all works perfectly:
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee',
data: JSON.stringify(fieldBean.data),
success: function(result) {
//TODO
}
})
But if I change data parameters, then controller doesn't get request even.
data: ({'fieldBean': JSON.stringify(fieldBean.data), 'id': id})
What I'm doing wrong?
That won't work. First lets clarify the difference between #RequestBody and #RequestParam.
The #RequestBody method parameter annotation should bind the json value in the HTTP request body to the java object by using a HttpMessageConverter. HttpMessageConverter is responsible for converting the HTTP request message to an assoicated java object. Source
And Use the #RequestParam annotation to bind request parameters to a method parameter in your controller. Source
Coming to you question...
With first ajax request you are sending JSON to your controller not request parameters, so #RequestBody is OK.
In the second ajax request also you are sending JSON but with two fields (fieldBean and id). Since #RequestBody annotated parameter is expected to hold the entire body of the request and bind to one object. You should modify the Java Object(ie TicketTemplateFieldBean) to hold id field also. This will work if you have only one argument in the controller.
Then, how to have second argument?
You cannot use two #RequestBody like :
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, #RequestBody Long id).
as it can bind to a single object only (the body can be consumed only once), You cannot pass multiple separate JSON objects to a Spring controller. Instead you must Wrap it in a Single Object.
So your solution is to pass it as Request parameter- #RequestParam, or as a path variable - #PathVariable. Since #RequestParam and #ModelAttribute only work when data is submitted as request parameters. You should change your code like this:
#Timed
#RequestMapping(value = "saveee", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, #RequestParam("id") Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
And change you request URL as follows:
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee?id=10',
data: JSON.stringify(fieldBean.data),
success: function(result) {
//TODO
}
})
You can use #PathVariable like this:
#Timed
#RequestMapping(value = "saveee/{id}", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestBody TicketTemplateFieldBean fieldBean, #PathVariable("id") Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
And change you request URL as follows:
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee/10',
data: JSON.stringify(fieldBean.data),
success: function(result) {
//TODO
}
})
To convert parameter to the method arguments you have to use #RequestParam, so the code should be modified like this:
Controller :
#Timed
#RequestMapping(value = "saveee", method = RequestMethod.POST)
#ResponseBody
public JsonResultBean saveTicketTemplate(#RequestParam TicketTemplateFieldBean fieldBean, #RequestParam Long id) throws IOException {
//TODO smth
return JsonResultBean.success();
}
You're not passing valid data to the controller. Try something like this.
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/organizer/api/saveee',
data: JSON.stringify({
fieldBean: JSON.stringify(fieldBean.data),
id: id
}),
success: function(result) {
//TODO
}
})

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

File Upload using ajax and jquery in spring

var urlUpload = "${root}manager/uploadFile.html";
var params = $('#topicForm').serialize();
$.ajax({
type: 'POST',
url: urlUpload,
data: params,
contentType: 'multipart/form-data',
processData: false,
success: function(data) {
alert("success");
}
});
#RequestMapping(value="/manager/uploadFile.html", method = RequestMethod.POST)
public String uploadFile(#ModelAttribute("topicForm") TopicForm topicForm,
#RequestParam("topicDoc") MultipartFile multipartFile ModelMap model) { ... }
I am getting the below exception
org.springframework.web.multipart.MultipartException: Could not parse
multipart servlet request; nested exception is
org.apache.commons.fileupload.FileUploadException: the request was
rejected because no multipart boundary was found.
The plugin is working fine thank you.
var urlUpload = "${root}manager/uploadFile.html?categoryId="+$("#category").val()+"&topicName="+$("#topicName").val();
$.ajaxFileUpload({
url:urlUpload,
secureuri:false,
fileElementId:'fileupload',
dataType: 'html',
success: function (data, status) {
alert("success");
}
});
The plugin is working fine, now i need to send few form fields to the controller along with the input file. in the above ajax call i appended the values to url. Is there any other solution for this?
The problem is that you're attempting to upload a URL-encoded serialization of the form, while claiming that it's multipart (see documentation of JQuery's serialize() function).
You need to use a plugin that will create the proper request. Here's one that I've used.
Alternatively, you can use HTML5 to upload files. I haven't done this.

Categories

Resources