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
Related
I am using spring mvc. I need to pass a json object from my jsp page to controller.
My ajax code:
function createJSON() {
jsonObj = [];
item = {};
$(".values").each(function() {
var code = $(this).attr('id');
item[code] = $('#' + code).val();
});
var content=JSON.stringify(item)
$.ajax({
type: 'POST',
contentType : 'application/json; charset=utf-8',
url: "/pms/season/submit",
data: content,
dataType: "json",
success : function(data) {
alert(response);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
My controller code:
#RequestMapping(value = "/submit", method = RequestMethod.POST)
public void saveNewUsers( #RequestParam ("json") String json) {
System.out.println( "json ::::"+json );
}
But it's not working.
#RequestParam("json") means that you are intending to include a request parameter called json in the URI, i.e. /submit?json=...
I think you intend to get the request body, i.e. #RequestBody.
I would then suggest that, unless you really need the raw JSON string, you would have the #RequestBody translated to a Java object for you:
public void saveNewUsers(#RequestBody MyDto myDto) {
...
}
where MyDto would have getters/setters and fields matching the JSON class.
You can over omit the #RequestBody annotation if you annotate the controller with #RestController, instead of #Controller.
If you definitely want the raw JSON string, then take a look at this previous question: Return literal JSON strings in spring mvc #ResponseBody
I am using Play 2.2.6 and need to get List<String> or String[] from controller to my jQuery Ajax call.
My controller looks like:
public static Result list(){
List<String> cname = new ArrayList<String>();
String[] arr= new String[]{"abc","abc2"};
return ok(index.render(arr));
}
Code for Index method:
public static Result index(){
String[] arr= new String[]{"abc","abc2"};
return ok(index.render(arr));
}
and my jQuery function looks like:
<script>
$(function() {
ajaxCall();
});
var ajaxCall = function() {
var ajaxCallBack = {
success : onSuccess,
error : onError
}
jsRoutes.controllers.Application.list().ajax(ajaxCallBack);
};
var onSuccess = function(data) {
console.log(data)
}
var onError = function(error) {
alert(error);
}
</script>
This script is in index.scala.html file and routes are:
GET / controllers.Application.index()
POST / controllers.Application.list()
GET /javascriptRoutes controllers.JavascriptRoute.javascriptRoutes
Ajax response works perfect for String type e.g. if I say
return ok("This is string");
Then I can see it in Ajax response but can't figure out why array or list throws below error:
Internal server error, for (GET) [/] ->
cannot find symbol [symbol: method ok(java.lang.String[])] [location: class controllers.Application]
Just to mention I defined this method as POST in routes.
Any suggestions?
The problem is that you are responding with a rendered index template and the exception is being thrown when trying to render that template. What you want to do is respond with the JSON data.
public static Result list(){
String[] arr= new String[]{"abc","abc2"};
return ok(Json.toJson(arr));
}
tested it locally in my browser with the following code
$.ajax({
method: "POST",
url: "/",
dataType: "script",
success : function(data) {
console.log(JSON.parse(data));
}
});
EDIT:
So you could do something like this:
List<ObjectNode> objectNodes = new ArrayList<>();
ObjectNode objectNode = Json.newObject();
objectNode.put("Latitude", "13.679389");
objectNode.put("Longitude", "-13.679389");
objectNodes.add(objectNode);
// create loop to add more nodes
return ok(Json.toJson(objectNodes));`
And in your ajax response you will now have a list of nodes with Longitude and Latitude values
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.
i have action below
#RequestMapping(value = "info_pure", method = RequestMethod.GET)
public ModelAndView GetInfo(String ser_name, String[] p_input_week_days, int p_input_month_day) {
ModelAndView mav = new ModelAndView(JspView.PureInfoAup);
String aaa = request.getParameter("p_input_week_days");
i send get request to this action via jquery ajax.
var myarray = ['Element 1', 'Element 2', 'Element 3'];
var dataobject = {
ser_name: p_ser_name.trim(), p_input_week_days: myarray, p_input_month_day: p_month_day
};
$.ajax({
url: '../info_pure',
data: dataobject,
type: 'GET',
success: function(data) { /// go forward
but when request send it give me an error. it says that my array parameter is null
here is my result on firebug
Use Spring MVC #RequestParam annotation.
#RequestMapping(value = "info_pure", method = RequestMethod.GET)
public ModelAndView GetInfo(#RequestParam("p_input_week_days[]") String[] days) {
String[] aaa = days;
More details: http://docs.spring.io/spring/docs/4.0.0.RC1/spring-framework-reference/html/mvc.html#mvc-ann-requestparam
I had solved this problem using Google Gson library.
Update your controller method like this
#RequestMapping(value = "info_pure", method = RequestMethod.GET)
public ModelAndView GetInfo(String ser_name, String p_input_week_days, int p_input_month_day) {
Gson gson=new Gson();
String[] weeks=gson.fromJson(p_input_week_days, String[].class);
// ....
Update your Ajax call like this
var myarray = ['Element 1', 'Element 2', 'Element 3'];
var dataobject = {
ser_name: p_ser_name.trim(), p_input_week_days: JSON.stringify(myarray), p_input_month_day: p_month_day
};
$.ajax({
url: '../info_pure',
data: dataobject,
type: 'GET',
success: function(data) { /// go forward
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.