Parsing JSON server side in Java? - 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.

Related

Axios. Spring MVC returns a 415 response

I am using Vue.js, axios and Spring.
On the page I have the following axios code
axios({
method: 'post',
url: '/user/info',
params: {
'_csrf' : document.getElementById('csrf_id').value,
'name' : 'job',
'age' : '25',
},
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
And on the server I have a receiving method like this
#Controller
#RequestMapping("/user")
public class UserInfo {
#ResponseBody
#PostMapping(value = "/info", consumes = "application/x-www-form-urlencoded", produces = "application/json" + ";charset=utf8")
public String info(#RequestParam(value = "name") String name, #RequestParam(value = "age") String age) {
System.out.println(name);
System.out.println(age);
return "ok";
}
}
Axios makes a request to the server, but the server returns a 415 response.
The request headers are missing the application/x-www-form-urlencoded content type. I suspect the problem lies precisely in this.
Tell me, what am I doing wrong?
HttpMethod Post is a method of writing and transmitting data in the request body.
In your case, you put data through params. If you execute code as you write, data will be sent such as /user/info?_csrf=value&name=job&age=25 and there will be no data in the request body.
To get the response you want, you can modify it as below.
axios({
method: 'post',
url: '/user/info',
data: '_csrf=csrf&name=job&age=25',
headers: {'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'}
});
change params keyword to data and write data like querystring.

Not able to receive parameters using Postmapping in Rest Controller

My Ajax code looks like this
$.ajax({
type : 'post',
url : url,
async : false,
data: {'txToClose': '1234,5678','sno':'0195'},
contentType : "application/x-www-form-urlencoded; charset=utf-8",
dataType : "json",
success : function(result,status,xhr){
console.log(result);
}
});
The txToClose value 1234,5678 will be coming from a textbox as comma separated string. The user will type them as comma separated.
Im trying to receive them in controller as
#PostMapping("/txToClose")
public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response) throws BBException
{
logger.info("Called txToClose controller");
ResultDto resultDto = new ResultDto();
String txToClose= request.getParameter("txToClose");
String sno= request.getParameter("sno");
logger.info("Transactions to close :"+txToClose+", Serial Num :"+sno);
}
Output is
Transactions to close :null, Serial Num :null
What am I missing here?
You're posting your data as request body, which of course using request.getParameter() will give you null. getParameter() was used to retrieve value from URL parameter.
I'm not quite experience with SpringMVC but try to change your method parameter into
public ResultDto txToClose(#RequestBody ResultDto resultDto ) throws BBException
{
logger.info("Called txToClose controller");
String txToClose= resultDto.getTxtToClose();
String sno= resultDto.getSno();
logger.info("Transactions to close :"+txToClose+", Serial Num :"+sno);
}
I assume your ResultDto is same as your JSON format.
remove the line
contentType : "text/plain; charset=utf-8",
or use default contentType
contentType : "application/x-www-form-urlencoded; charset=utf-8",
It should work.
I solved the issue by adding #RequestBody ObjectNode json in the signature.
public ResultDto txToClose(HttpServletRequest request, HttpServletResponse response,#RequestBody ObjectNode json) throws BBException
{
logger.info("Called txToClosecontroller");
ResultDto result = new ResultDto();
String txToClose= json.get("txToClose").asText();
}

Spring Restful Array object as input

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

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

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