I would like to make a call to a spring mvc rest service with an array of string in parameters. I have tried this:
.factory('CallRequest', function ($resource) {
return $resource('api/callRequesWithArray/:arrayOfString', {}, {
'query': {
method: 'GET', isArray:true,
transformResponse: function (data) {
data = angular.fromJson(data);
return data;
}
}
});
})
#RequestMapping(value = "/callRequesWithArray/{arrayOfString}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public void envoiBlToClient(#PathVariable ArrayList arrayOfString, HttpServletResponse response) throws Exception {
....
}
but it doesnt work, it puts a coma between each of my arraylist items, and then it s not well interpreted (not the way I would like...) and the request is rejected.
Is it possible to pass an array of string in a GET $resource call as a parameter?
Thanks.
Related
I have a Spring MVC Rest controller with one of the URL mappings being :
myhost:8080/helloworldexample/testnullresponse
Now, is it possible to return nothing at all when I call this URL
Nothing means: no body, no response, no status code simply nothing at all, almost like the server listening to the request did not do anything.
I would appreciate any help on this. I have tried the following options but nothing worked:
return new ResponseEntity<Void>(null);
AND
#RequestMapping(value = "/helloworldexample/testnullresponse", produces = "application/json; charset=UTF-8", method = RequestMethod.GET)
public void nullResponse(HttpServletRequest request) {
}
Actually your controller's method could return void.
Here is an example
#RequestMapping(value = "/helloworldexample/testnullresponse", method = RequestMethod.HEAD)
public void nullResponse(HttpServletResponse response) {
...
}
I am building a Spring rest service for uploading a file. There is a form that consists of various field and one field for uploading a file. On submitting that form, I am sending a multipart form request i.e. Content-Type as multipart/form-data.
So I tried with below
#RequestMapping(value = "/companies", method = RequestMethod.POST)
public void createCompany(#RequestBody CompanyDTO companyDTO, #RequestParam(value = "image", required = false) MultipartFile image){
.................
But, the above didn't work. So for time being,i sent JSON data as String and forming Company Object from that String in rest service like
#RequestMapping(value = "/companies", method = RequestMethod.POST)
public void createCompany(#RequestParam("companyJson") String companyJson, #RequestParam(value = "image",required = false) MultipartFile image) throws JsonParseException, JsonMappingException, IOException{
CompanyDTO companyDTO = new ObjectMapper().readValue(companyJson, CompanyDTO.class);
.............................
Can't I send JSON data with #RequestBody without passing JSON as String?
Appending the values to the URL what u have been doing now using #RequestParam.
#RequestParam annotation will not work for complex JSON Objects , it is specifi for Integer or String .
If it is a Http POST method , use of #RequestBody will make the Spring to map the incoming request to the POJO what u have created (condition: if the POJO maps the incoming JSON)
create FormData() and append your json and file
if (form.validate()) {
var file = $scope.file;
var fd = new FormData();
fd.append('jsondata', $scope.jsonData);
fd.append('file', file);
MyService.submitFormWithFile('doc/store.html', fd, '', (response){
console.log(response)
});
}
//Service called in above
MyService.submitFormWithFile = function(url, data, config, callback) {
$http({
method : 'POST',
url : url,
headers : {
'Content-Type' : undefined
},
data : data,
transformRequest : function(data, headersGetterFunction) {
return data;
}
}).success(function(response, status, header, config) {
if (status === 200) {
callback(response);
} else {
console.log("error")
}
}).error(function(response, status, header, config) {
console.log(response);
});
};
// in your java part using ObjectMapper
//it is like string
fd.append('jsondata', JSON.stringify($scope.jsonData));
#Autowired
private ObjectMapper mapper;
#RequestMapping(value = "/companies", method = RequestMethod.POST)
public void createCompany(#RequestParam String jsondata,
#RequestParam(required = true) MultipartFile file){
CompanyDto companyDto=mapper.readValue(jsondata, CompanyDTO.class);
......
}
Use below code snippet:
#RequestMapping(value= "/path", method=RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseObject methodName(MyData input, #RequestParam(required=false) MultipartFile file) {
// To Do
}
I have the page about.ftl which is invoked when I type localhost:8080/ui/about
and I have put the following block of code inside. Through SendToServlet() function I am trying to send the user info to my controller which is the OAuthController.java
function SendToServlet(){
$.ajax({
url: "localhost:8080/ui/about",
type: "POST",
data: JSON.stringify({ user:jsonObj}),
contentType: 'application/json',
success: function(result) {
alert(done);
},
error: function(xhRequest, ErrorText, thrownError) {
alert(JSON.stringify(jsonObj));
}
});
}
</script>
My Spring MVC Controller class code has the following implementation - all that it does is that it accepts the user's information and then sets up current user:
#Controller
#RequestMapping("/about")
public class OAuthController {
#RequestMapping(method = RequestMethod.POST)
#ResponseBody
public String post( #RequestBody String items, HttpServletRequest request, HttpServletResponse response)
{
String jsonResp = items;//sb.toString();
ArrayList<String> usercredentials = new ArrayList<String>();
usercredentials = parseJson(jsonResp);
UserMethods usermethods = new UserMethods();
usermethods.setCurrentUser (usercredentials);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
return "{\"success\":\"\"}";
}
public ArrayList<String> parseJson(String json){
}
}
My problem is that the controller is never invoked and actually I never see a Post request to be sent anywhere through Firebug. I've spent several days on it, but still no luck. Do you have any suggestions?
You need to bind value with your function. Your url localhost:8080/ui/about/post is just used to locate the controller but it will not execute any function because you didn't make a call to any function.
To call the function, you have to do like this :
#RequestMapping(method = RequestMethod.POST, value ="/anyValue")
public String anyFunctionName(anyParam){...}
Above function will bind to url localhost:8080/ui/about/anyValue.
Don't you need to call it like this?
url: "localhost:8080/ui/about/post",
but first do this:
#RequestMapping(method = RequestMethod.POST, value = "/post")
How about try to add .html?Application won't add it automatically.
script Array of int and I wish to pass into Spring Controller. but I keep getting
400 bad request.
if my js array is
array = [1,2,3,4]
array -> 400 bad request
JSON.Stringify(array) -> I will get [1,2,3,4]
$.ajax({//jquery ajax
data:{"images": array},
dataType:'json',
type:"post",
url:"hellomotto"
....
})
when I loop the string List.. the first element will be '[1'
#RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(#RequestParam("images") List<String> images){
sysout(images); -> I will get [1,2,3,4]
}
public void
May I know how can I do this properly? I have tried different combination
The following is a working example:
Javascript:
$('#btn_confirm').click(function (e) {
e.preventDefault(); // do not submit the form
// prepare the array
var data = table.rows('.selected').data();
var ids = [];
for(var i = 0; i < data.length; i++) {
ids.push(Number(data[i][0]));
}
$.ajax({
type: "POST",
url: "?confirm",
data: JSON.stringify(ids),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
Controller:
#RequestMapping(params = "confirm", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody int confirm(#RequestBody Long[] ids) {
// code to handle request
return ids.length;
}
#RequestParam is used to bind request parameters, so if you do something like
#RequestMapping(value = "/hellomotto", method = Request.POST)
public void hellomotto(#RequestParam("image") String image){
...
}
and you do post to /hellomotto?image=test, the image variable in hellomotto method will contain "test"
What you want to do is to parse Request body , so you should you should use #RequestBody annotation :
http://docs.spring.io/spring/docs/3.0.x/reference/mvc.html#mvc-ann-requestbody
it is using jackson labrary (so you will have to include it as your dependency) to parse json object into java object.
I think you wantAjax call,through ajax, you are sending List of Integers
so in spring your controller will be
#RequestMapping(value = "/hellomotto", method = Request.POST)
#ResponseBody
public void hellomotto(#RequestParam("images") List<Integer> images){
sysout(images); -> I will get [1,2,3,4]
}
*#ResponseBody is missing in Your Code
I'm having a problem with Spring MVC and Ajax. I'm trying to send a javascript list to my Spring Controller, but I can't. I've to do a search and I need to send a list with some parameters.
You will have to convert to the list to json if you sending via ajax, this From the spring blog itself :
$("#account").submit(function() {
var account = $(this).serializeObject();
$.postJSON("account", account, function(data) {
$("#assignedId").val(data.id);
showPopup();
});
return false;
});
#RequestMapping(method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> create(#RequestBody Account account, HttpServletResponse response) {
Set<ConstraintViolation<Account>> failures = validator.validate(account);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
accounts.put(account.assignId(), account);
return Collections.singletonMap("id", account.getId());
}
}
You have to convert your list to JSON String , before using it as an AJAX parameter
This answer in SO might help
jquery ajax on client side
$.ajax({
type: "POST",
url: "submit",
data:JSON.stringify(detailsArr),
success: function(html){
alert( "Submitted");
}
});
and on server side
#RequestMapping(value = "/search", method=RequestMethod.POST)
public String yourMethod(#RequestBody String body){
//convert body to array using JSONLib, FlexJSON or Gson
}