How to use spring mvc to receive array as a parameter? - javascript

Convert an array object to a json string using JSON.stringify
var array = [1, 2];
let json = JSON.stringify(array);
console.log(json);
axios.get('http://localhost/goods', json).then(function (res) {
if (res.code == 200) {
console.log("ok");
}
}
Parameters during transmission with Chrome browser console:
My goods controller class, for example:
#RequestMapping(value = "goods",method = RequestMethod.GET)
public String deleteByIds(#RequestBody Integer[] ids) {
goodsService.deleteByIds(ids);
return "ok";
}
Spring mvc can't receive an array.Or am I having a problem with writing axios code? How to solve it?

From your request,
axios.get('http://localhost/goods', json)
It's a get request. So it won't have a body.
You can try changing the get method to post or use #RequestParameter instead of #RequestBody.

Related

How to sent JavaScript Objects from the Client-Side and how to receive and parse them in Spring Boot Back-end?

I have came and left this problem numerous times while trying to make my web apps and have gotten fed up with no results, to the point that I have to ask here, so please excuse me if I come off as venting... I am quite aggravated.
I am trying to send data in the form of key-value pairs from my client(vanilla js) to my back end(spring boot java). I have tried numerous ways of doing it but can't seem to find the correct way/combination to achieve what I want done. My current non-working code is as follows.
Client-Side JS
var object = {
'id' : 1,
'username' : 'jumpthruhoops',
'password' : 'melodysteez'
};
Axios
.post('http://localhost:8080/gameSchedule', JSON.stringify(object))
.then((response) => {
console.log(response.data);
});
Back-End Spring Boot/Java
#CrossOrigin
#RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getSchedule(#RequestBody String user) {
System.out.println(user);
return "test";
}
The following code is what I currently have that has given me any type of results close to what I'm looking for. It gives me the following printed line...
%7B%22id%22%3A1%2C%22username%22%3A%22tdellard1%22%2C%22password%22%3A%22sisters3%22%7D=
...which I believe is a hex code for the string object I passed into the parameter. I'm not sure if this is from Spring Boot, or if this is what JSON.stringify does. Since the User Object is a test object and actual object that I plan on passing in, is way more complex, I don't want to figure out how to decode the hex code, unless I can't get anything else going and I completely have to.
Because it is more complicated, I don't want to use a lot of #RequestParams("name") String VaribleName like 40 times in the parameter of the method. This was also the only other way to get results but passing those variables into a url is maddening.
Some other things I have tried are #ModelAttribute and (#RequestBody User user), both return errors, one that seems to be reoccurring is
018-10-30 23:38:29.346 WARN 12688 --- [io-8080-exec-10] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]
So what I am pretty much asking is for guidance on what is the best way to send my data from Axios(form.serialize, JSON.stringify, JavaScript Object, etc.) and what corresponding method I need to use to obtain that data on my Spring Boot Back-End and make it manipulative so I can turn it into a POJO.
Just remove JSON.stringify(object) and put object.
Axios
.post('http://localhost:8080/gameSchedule', object)
.then((response) => {
console.log(response.data);
});
You can see an example on POST request here axios documentation
On Spring boot you have to create an entity like this:
#Entity
public class UserAccount implements Serializable {
#Id
private Long id;
#Column(unique = true, nullable = false)
#Size(max = 255)
private String userName;
#Column(nullable = false)
#NotNull
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
and change your code for here
#CrossOrigin
#RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public UserAccount getSchedule(#RequestBody UserAccount user) {
System.out.println(user.getUserName());
return user;
}
If you are sending an object you have to use object when receiving at back-end side and make sure that name of the field in request object and the field name of the class at back-end side must be same,
so it should be like this:
I am just making some changing in your code to access field:
var data = {
'id' : 1,
'username' : 'jumpthruhoops',
'password' : 'melodysteez'
};
// name of variable(data variable) doesn't matter but inside everything consider as a body
axios.post('http://localhost:8080/gameSchedule', JSON.stringify(object), {
headers: {
'Content-Type': 'application/json',
}
}
);
back-end side retrieve fields
//create one Student class to map fields with body
#CrossOrigin
#RequestMapping(value = "/gameSchedule", headers = "Accept=application/json", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String getSchedule(#RequestBody Student student) {
System.out.println(student.id);
System.out.println(student.username);
System.out.println(student.password);
return "test"
}

How to get the POST request parameters of a jQuery $.post from a spring mvc controller?

I need to load data from database dynamically on the page, without any page reload.
My code in JSP is like this:
<script>
$(document).ready(function() {
$("#ClassNext").click(function(event){
var data = {};
var classArray = [];
$.each($("input[name='classCheckbox']:checked"), function(){
classArray.push($(this).val());
});
console.log(classArray);
data["list"] = classArray;
data["var"] = "1";
console.log(data);
$.post('PopulateClassSample',data,function(responseJson){
if(responseJson!=null){
$.each(responseJson,function(key,value){
// do something
})
}
})
})
});
<script>
<c:forEach items="${classList}" var="Class">
<li>
<input class="classCheckbox" type="checkbox" name="classCheckbox" value="${Class.classStart}"></input>
<c:out value="${Class.showString}"/>
<button style="display: none;" id="${Class.classStart}">Edit</button>
</li>
</c:forEach>
<button id="ClassNext">Next</button>
Here I am posting a request to extract some information from the database through jQuery POST ($.post). I am expecting the response as a JSON object which contains the information from the database. The data variable is an object of two fields- one field contains an array of Strings, the other field contains a String. This data variable gets its required values correctly through javascript.
The method that catches this request in a controller:
#RequestMapping(value="/PopulateClassSample", method = RequestMethod.POST)
#ResponseBody
protected void SendResponse(#RequestParam("list") ArrayList<String> list, #RequestParam("start") String start, HttpServletResponse response) throws IOException
{
for(String s:list){
System.out.println(s);
}
System.out.println(start);
/*
ArrayList<AcademicClass> classList = new ArrayList<AcademicClass>();
DataAccess db = new DataAccess();
classList = db.getClassList();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(classList,new TypeToken<List<AcademicClass>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
*/
}
Inside the DataAccess class, I am doing all the database query and returning the result through its methods. I need HttpServletResponse object here, because I will return something to the jQuery code as a JSON object.
But I am getting errors like this in console:
jquery.min.js:4 POST http://localhost:8080/Mytuition/PopulateClassSample 400 ()
And the initial prints in the controller method doesn't gets executed.
I tried declaring a separate model class (which has two fields- an ArrayList of Strings and a String) and used the #ModelAttribute annotation. But then I get exceptions like this:
java.lang.NumberFormatException: For input string: ""
Is there any way to do it without #ModelAttribute annotation? And why isn't this working even if I am using the #ModelAttribute annotation?
Note: I will definitely return something to the JSP. That part is commented out only for testing purpose.
Your controller method its wrong. If you are doing an Ajax call to the server and need to retrieve the JSON response from the server you only need to do 2 things.
Define your method in the controller with #ResponseBody. Then Spring will translate your returning object to JSON format
Return some object to the view. You are returning "void"
Should be something like this
#RequestMapping(value="/PopulateClassSample", method = RequestMethod.POST)
#ResponseBody
protected List<AcademicClass> SendResponse(#RequestParam("list") ArrayList<String> list, #RequestParam("start") String start) throws IOException
{
/** DO your staff here and return the AcademicClass list */
System.out.println(start);
DataAccess db = new DataAccess();
return db.getClassList();
}

pass collection of objects through http post in angular js

I have pass a collection of objects through http post in angular js.
The code is as follows:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data.ContentId, { Selected: true }); // I could able to get all the selected objects here, No problem with it
var jsonData = angular.toJson(contents); //It is not able to convert to Json if there are more than 5 records
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent?jsonData=' + jsonData, {});
promise.success(function () {
window.location.reload();
});
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(string jsonData)
{
var contents = JsonConvert.DeserializeObject<List<ContentNodeInWorkFlow>>(jsonData);
foreach (var content in contents)
{
_contentService.PublishContent(content.ContentId, userId);
}
}
}
The above code works fine if there are 5 records or less. If there are more records, I could able to get all the selected record
objects in the variable 'contents'. But the problem is occuring when converting to Json for all those objects. I
have about 500 records to pass through. How can do I it?
There is no specific reason to convert to JSON data. I just need to extract the ids of all the selected items. I have modified the above code as below:
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var abc = [];
angular.forEach(contents, function(content)
{
abc.push(content.ContentId); // got all the ids in the array now
});
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,{contents : abc});
promise.success(function () {
window.location.reload();
});
}
I have just took an array and pushed all the content ids into it. I could able to see all the ids in the array now. I tried to pass the array as above.
How to retrieve those array in the code behind.
[ReferrerFilterAttribute]
[HttpPost]
[System.Web.Http.ActionName("CmsPublishApprovedContent")]
public void CmsPublishApprovedContent(int[] abc)
{}
I do not see any values obtained under int[] abc. What will be the datatype for the parameter in the method call above.
You need second argument of $http.post method. You have to send such data by POST requests, not in query of url. You can put some data into body of the post request.
You need this:
var postBodyWithHugeAmountOFData = {data: [1,2,3,4,5...500]};
$http.post(url, postBodyWithHugeAmountOFData).success(function () {});
Also, you must be ready to handle this request in your backend.
is there any specific reason u want to pass this data as a JSON?.
if u r using Web API in that case u can pass the object as it is but only make sure that collection in web API method contains all the property in javascript collection
Thank you for all your posts. It's working fine without converting to Json. The code is as below.
$scope.selectedContent = function () {
var contents = $filter('filter')($scope.data, { Selected: true });
var promise = $http.post('/webapi/cmsApi/CmsPublishApprovedContent' ,contents);
promise.success(function () {
window.location.reload();
});
}
and the signature would be
public void CmsPublishApprovedContent(List<ContentNodeInWorkFlow> abc)
{
}

WebForms GET Json requests (JsonRequestBehavior.AllowGet)

I have an old WebForms project that needs revisiting and I want to add some new features.
I want to load the data using $.getJSON(), this is very simple in ASP.NET MVC because you can return the data like this,
return Json(data, JsonRequestBehavior.AllowGet);
The Get doesn't work in WebForms,
// Http GET request
$.getJSON('Attributes.aspx/GetAttributes', { 'ProductId': '3' }, function (d) { alert(d); });
The Post works.
// Http POST
$.post('Attributes.aspx/GetAttributes', { 'ProductId': '3' }, function (d) { alert(d); });
Here is the WebForms WebMethod,
[WebMethod]
public static string GetAttributes(string ProductId)
{
List<QuoteAttribute> list = DAL.GetAttributes(ProductId);
var json = JsonConvert.SerializeObject(list);
return json;
}
I want to return json using the GET method.
Is there an JsonRequestBehavior.AllowGet for WebForms?
Any help is appreciated.
Thanks
Need to add "[ScriptMethod(UseHttpGet = true)]" before the method.This will allow GET method.
eg.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetAttributes(string ProductId)
{
List<QuoteAttribute> list = DAL.GetAttributes(ProductId);
var json = JsonConvert.SerializeObject(list);
return json;
}

how can pass array to java servlet

On my jsp, this is my code :
$('.save').on("click",function(){
var array = $.map($('table tr'), function (val, i) {
var obj = {}, inputs = $(val).find('td input:not(:hidden)');
obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
return val.value;
});
return obj;
});
var data = JSON.stringify(array);
$.post("Controller.html", data, function(response) {
/// i dont know what to put here,so i think this where i get trouble with
});
});
but still data is null when i check on servlet.
this is my servlet :
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data=request.getParameter("data");
if (data== null) {
System.out.println("null");
}
RequestDispatcher view = request.getRequestDispatcher("/page.jsp");
view.forward(request, response);
}
fiddle here
First you need to send the data, you can use an ajax post method:
$.post("yourservlet", data=JSON.stringify(array), function(response) {
// handle response from your servlet.
alert(response)
});
In servlet, you retrieve the data with the command:
String data=request.getParameter("data");
Then you need to parse the json, you can use a library like JSON simple:
Object obj = JSONValue.parse(data);
JSONArray array = (JSONArray) obj;
Or you can manually parse it. Based on your code, your json string will look like this:
data = "[{'orange':['1.00','5']},{'apple':['2.00','5']}]";
You can use split() method or StringTokenizer to separate each object, but you should write your own parser method, for this you can find many tutorials on google.
Javascript is in client-side. And java servlet is for server-side.
You must use ajax to make a call from client-side to your servlet.

Categories

Resources