Post JS Object Array to Spring MVC controller - javascript

I am trying to pass long array from jquery load to spring controller. How can i sent js object array t spring mvc controller.
Every time action occured the no data alert on script will called.
Script
var arr = [];//Array
$(document).ready(function() {
$(".rating").click(function() {
var idx = $(this).closest('td').index();
var userskill = {//Object
tech : $(this).closest('td').siblings('td.tech').text(),
skill : $('#listTable thead th').eq(idx).text(),
rValue : $(this).val()
}
add(userskill);
});
});
function add(userskill) {
arr.push(userskill);
$.ajax({
type : 'POST',
dataType : 'json',
url : '/SimplWebApp/saveUserRating',
data : ({
id : JSON.stringify(arr)
}),
success : function(responseData) {
if (responseData != null) {
alert(responseData);
} else {
alert("no data");
}
}
});
}
controller
#RequestMapping(value = "saveUserRating")
public #ResponseBody String saveUserRating(#RequestParam(value="id[]", required=false) String[] x) {
Gson gson = new Gson();
String data = gson.toJson(x);
return data;
}

The JSON array resides in the body of the request. You can use the #RequestBody annotation to obtain the array if you have Jackson on the classpath to deserialize the JSON.
saveUserRating(#RequestBody(required=false) String[] ids)
If you want to use the array as the response body simply return the array from the handler method. It will be serialized to JSON automatically.
#ResponseBody
public String[] saveUserRating(saveUserRating(#RequestBody(required=false) String[] ids)) {
return ids;
}

Related

Passing a list of strings in a Spring MVC controller using Jquery Ajax

i'm trying to pass a list of Strings to an MVC controller using JQuery Ajax, but i get the error No mapping for POST /myUrl/myContext/p
this is my jquery function:
$('#myButton').on('click', function(){
var strings = [];
$('#myForm input[type=checkbox]:checked').each(function(){
var string = $(this).closest('tr').find('#mySpan').text();
strings.push(string);
});
$.ajax({
url : 'myContext/p',
dataType : 'json',
type: 'POST',
data : {strings : strings},
success: function(response) {
//my success function
}
},
error: function(e) {
//my error function
}
}
});
})
this is my controller:
#PostMapping(value="/myContext/p")
public ResponseEntity<MyResponse> doPost(
#RequestParam(value="strings" ,required=true) List<String> strings)
throws Exception{
MyResponse response = new MyResponse();
//my Code
response.setData(strings);
return new ResponseEntity<MyResponse>(response, HttpStatus.OK);
}
I normally would use #RequestBody instead of #RequestParam for the strings parameter.
I fixed the issue with:
#PostMapping(value="/myContext/p", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<MyResponse> doPost( ArrayList<String> strings) throws Exception{
MyResponse response = new MyResponse();
//code
response.setData(strings);
return new ResponseEntity<RestResponse>(response, HttpStatus.OK);
}

How to pass map from localstorage to controller in spring boot?

I am trying to save checkbox values in localstorage using map. so that i can filter result using map. I am able to store map key-values in localstorage using javascript. but later when i retreive and pass map from localstorage to controller, I am getting map with null values.
this is my code
store map in localstorage
$(':checkbox[name=brand]').on('change', function() {
var assignedTo = $(':checkbox[name=brand]:checked').map(function() {
return this.id;
}).get();
localStorage.setItem('brands', JSON.stringify(assignedTo))
});
localstorage
passing to controller
$.ajax({
type : "POST",
url : "filter",
data : {
txtMaxAge : localStorage.getItem('txtMaxAge'),
brands : JSON.parse(localStorage.getItem("brands"))
}, // parameters
success : function(result) {
// alert('changed');
}
});
controller
#RequestMapping("/filter")
#ResponseBody
public String filter(
#RequestParam(value = "txtMaxAge", required = false) String txtMaxAge,
#RequestParam(value = "brands", required = false) Map<String, String> brands,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("max"+txtMaxAge);
System.out.println("printing map----");
for (Map.Entry<String,String> entry : brands.entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
return "send data";
}
I am getting this error
max10000000
printing map----
2018-12-15 13:37:59.142 WARN 13672 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver :
Resolved [java.lang.NullPointerException] to ModelAndView: reference to view with name 'error';
model is {errorTitle=Contact Your Administrator!!, errorDescription=java.lang.NullPointerException
What i am doing wrong here?
The problem is that brands is not map type,it is an array of strings. Change the type accordingly and it should work.
Try to change your controller code:
#RequestMapping(value = "/filter")
#ResponseBody
public String filter(
#RequestParam(value = "txtMaxAge", required = false) String txtMaxAge,
#RequestParam(value = "brands[]", required = false) String[] brands,
HttpServletRequest request, HttpServletResponse response) {
System.out.println("max " + txtMaxAge);
System.out.println("map " + brands);
return "send data";
}
if you really want brands in a Map ; here's my take on it.
Here my controller
#RequestMapping(value = "/filter", method = RequestMethod.POST)
public String submission(#RequestParam("brands")String brands) {
try {
JSONParser parser = new JSONParser();
JSONObject ob = (JSONObject)parser.parse(brands);
Map<String,String> mp = new HashMap<>();
mp.put(ob.keySet().toString(), ob.values().toString());
for(Map.Entry<String,String> entry : mp.entrySet()) {
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue().toString());
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "home";
}
Here's my ajax call,
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath}/Submit",
data: {
brands: localStorage.getItem("brands")
},
success : function() {
console.log('done');
}
});

Pass array to ajax request in $.ajax() to controller Spring mvc

I want to pass an array of strings as well as a string variable to the controller but it says parameter not present.
here is my javascript
function updateIssueHandler() {
var keyArray = [];
bootstrap_alert_hide('#form_errors');// cleans previous errors
$('input:checkbox[name=key_checkbox]:checked').each(function() {
keyArray.push($(this).val())
});
if (keyArray.length == 0) {
var errorMsg = document
.getElementById("js.i18nMessage.emptyUpdateTickets.id").value;
bootstrap_alert('#form_errors', errorMsg)
}
var labels = document.getElementById('labelsTextBox').value;
var b = {
"lab" : labels,
"keys": keyArray
};
//console.log(addl);
console.log(keyArray);
$.ajax({
url : '/jirabatchapp/JqlUpdate/',
data : b,
type : 'POST',
success : function(data) {
window.alert("done");
},
error : function(e) {
alert(JSON.stringify(e));
}
});
}
Controller:
#Controller
public class UpdateLabelController {
#RequestMapping(value = "/JqlUpdate", method = RequestMethod.POST)
public String updateIssue(#RequestParam(value = "lab") String a,#RequestParam(value = "keys") String k ) {
System.out.println(a);
System.out.println(k);
System.out.println("finally!");
return "success";
}
}
I get an error saying HTTP request error 400 Required string parameter lab not present.
What am i doing wrong? if I only pass labs, then it works, but if i want to pass both parameters it is throwing me this error.
change
var b = {
"lab" : labels
"keys": keyArray
};
to
var b = {
"lab" : labels,
"keys": keyArray
};
You have to pass a string as parameters
Just do this : data : JSON.stringify(b)
EDIT :
Try : data: $.param(b)

Why is my List<string> not returning from MVC Controller from $ajax call

I'm trying to create bespoke lists in my cshtml file using an ajax call
.ajax({
type: "GET",
cache: false,
url: "#Url.Action("getValidationLists")",
contentType: "application/json",
dataType: "json",
success: function (result) {
var list = result.list;
$.each(list, function (index, value) {
alert(value);
});
}
});
The Controller then collects the data puts it in a List and returns it to my cshtml file using json format. the controller method is below
[HttpGet]
[Authorize]
public JsonResult getValidationLists()
{
List<List<String>> validList = new List<List<String>>();
List<UIReferenceData> results = AddErrorsToModelState<List<UIReferenceData>>(_StaticDataServiceAgent.GetAllAssetTypes());
for (int i = 0; i < results.Count; i++)
{
List<String> resultList = new List<String>();
string id = results[i].ID.ToString();
string name = results[i].Name;
resultList.Add(id);
resultList.Add(name);
validList.Add(resultList);
}
return Json(new
{
validList = validList
}, JsonRequestBehavior.AllowGet);
}
I've tried several different versions but the returning code never gets as far as the alert(value); code.
What am i missing?
The property name is inconsistent with what you are returning from your action:
var list = result.list;
Should be:
var list = result.validList;
However you are returning a List<List<String>> rather than a List<String> too.
I think you need to address both of the above in order to fix.
The JSON response you are returning from your action method looks like this
{
"validList": [
["1", "SomeText"],
["2", "SomeText"],
["3", " SomeText"]
]
}
Your response has a validList property which is an array and each item in an array is again another array with 2 items.
This should work
success: function (result) {
$.each(result.validList, function (index, value) {
console.log(value[0]);
console.log(value[1]);
});
}

Get servlet value in javascript and assign that value to a textbox using ajax

I am having a servlet where I am getting value from properties file. I want to get the value from servlet in my javascript and set that value to a textbox using AJAX. I am totally new to Ajax so please provide me a solution by looking at my code.
SERVLET
#WebServlet("/PopulateProperties")
public class PopulateProperties extends HttpServlet {
private static final long serialVersionUID = 1L;
Properties prop = new Properties();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String serverName=request.getParameter("servernameDD");
List<Map<String,String>> returnObj = new ArrayList<Map<String,String>>();
String[] servers = getSearchAttr("servers");
if (servers != null && servers.length > 0) {
String[] lookfor = getSearchAttr("servers_lookfor");
for (String server : servers) {
Map<String,String> obj = new HashMap<String,String>();
if (lookfor != null) {
for (String look : lookfor) {
//System.out.println("looking for :"+look);
String value = prop.getProperty(server+"_"+look);
if(server.equalsIgnoreCase(serverName)){
if(look.equalsIgnoreCase("Links")){
String getlook=prop.getProperty(look);
String getlink=prop.getProperty(server+'_'+look,"Links");
System.out.println("Hello" +getlink);
System.out.println(getlook);
request.setAttribute("serverLink", getlink);
}
}
if (value != null) {
obj.put(look, value);
}
request.setAttribute("servers", server);
request.setAttribute("lookfor", look);
}
}
//System.out.println("Object :"+obj);
returnObj.add(obj);
}
}
response.sendRedirect("updateserverstatus.html");
}
private String[] getSearchAttr( String property){
String lookfor = prop.getProperty(property,"");
String[] ret = {lookfor};
if (lookfor.contains(",")) {
return lookfor.split(",");
} else {
//System.out.println("comma not present in "+property);
//System.out.println("webservice :"+lookfor);
return ret;
}
}
I tried the following Ajax request but I am getting "serverLink undefined error"
function OnSelectionChange(){
$.ajax({
type: "POST",
url: "/PopulateProperties",
data: "{Links: " + serverLink + "}",
success: function(result){
alert(result.d);
console.log(result);
}
});
}
You use a servlet to get data and forward. It is not a proper way to provide data with servlet. A better solution is:
In your servlet, you should just return the properties data in a json format. You can refer this
Then you get this data with ajax in your html page, and update the text of textarea.
It is better to crerate separate servlet just for this purpose. This will keep your code coherent.
Pass all the parameter which will be used to narrow down to the data you need to retrive.
For simplicity just return the value or you can return the data as a JSON key value pair.
If your textbox is like this. <input type="text" id="prop_txt">
then the ajax code will be
$.ajax({
type: "POST",
url: "/PopulateProperties",
data: "{A:(..a value..),
B:(..b value..),
....
....
(..all the parameters required..)
}",
success: function(result){
//alert(result.d);
console.log(result);
$('#prop_txt').val(result);
}
});
Hope this heplps.

Categories