How to read two json objects in spring boot controller - java

I am new to java, i am trying to pass two json objects from ajax call to controller class... but i am getting below exception
Resolved exception caused by Handler execution: org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public java.lang.String com.controllers.EmployeeController.saveData(java.lang.String,com.entities.EmployeeData,org.springframework.validation.BindingResult)
Jquery Code:
$("#saveData").submit(function(event) {
var data = [];
var formData = {};
var myJsonString;
var slab, lower;
$("table tbody tr").each(function(index) {
//alert(index);
slab = $(this).find('.slab').val();
lower = $(this).find('.lower').val();
if(slab != undefined && lower != undefined){
var form1 =new Object();
form1.slab=slab;
form1.lower=lower;
data.push(form1);
}
});
var form = this;
event.preventDefault();
$.each(this, function(i, v){
var input = $(v);
formData[input.attr("name")] = input.val();
});
var url = "/Portal/SaveData";
ajaxCall(url,formData,data);
});
function ajaxCall(url,formData,data){
//alert("AjaxPost!!!"+url);
// DO POST
$.ajax({
type : "POST",
contentType : "application/json",
url : url,
data : JSON.stringify({formData:formData,value:data}),
dataType : 'json',
beforeSend: beforeSendHandler,
success : function(response) {
alert("Success");
}else{
alert("else");
}
},
error : function(e) {
bootbox.alert({
size: "small",
title: "ALERT",
message: "There seems to be some problem while Proccessing record!"
})
}
});
}
Controller Method:
#RequestMapping(value = "/SaveData", method = RequestMethod.POST)
public #ResponseBody String saveData(#RequestBody String value,#Valid #RequestBody EmployeeData emp, BindingResult result) {
System.out.println(" Creating!!!");
//logic here
}
Where is the mistake in ajax call or in controller file?
there is any other way to pass multiple json objects to controller class file?

The #RequestBody annotation is expected to map to one and only one parameter in your method and to contain the entire contents of the incoming request.
You should map all your form data into a single JSON object, then handle that as a single JSON object in the backend as well.

Related

Ajax don't see Post Controller

I made ajax request, but it don't see Post Controller, which need to handle request. But if i change POST to GET - Get Controller handle ajax request.
My Post Controller:
#RestController
public class AddProductController extends AbstractController {
private static final long serialVersionUID = 5023867691534917359L;
private static final Logger LOGGER = LoggerFactory.getLogger(AddProductController.class);
#PostMapping("/ajax/json/product/add")
public ShoppingCart addProductToCart(HttpServletRequest req,
#RequestParam(name = "idProduct") String idProduct,
#RequestParam(name = "count") String count) {
ProductForm productForm = createProductForm(idProduct, count);
ShoppingCart shoppingCart = SessionUtil.getCurrentShoppingCart(req); // Get ShoppingCart
orderService.addProductToShoppingCart(productForm, shoppingCart); // Add product in Cart
return shoppingCart;
}
Ajax request:
var addProductToCart = function (){
var idProduct = $('#addProductPopup').attr('data-id-product');
var count = $('#addProductPopup .count').val();
var btn = $('#addToCart');
convertButtonToLoader(btn, 'btn-primary');
$.ajax({
url : '/ajax/json/product/add',
method : 'POST',
data: {
idProduct : idProduct,
count : count
},
success : function(data) {
$('#currentShoppingCart .total-count').text(data.totalCount);
$('#currentShoppingCart .total-cost').text(data.totalCost);
$('#currentShoppingCart').removeClass('hidden');
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
$('#addProductPopup').modal('hide');
},
error : function(xhr) {
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
if (xhr.status == 400) {
alert(xhr.responseJSON.message);
} else {
alert('Не сработала JS функция добавления в коризну');
}
}
});
};
Whats wrong with my PostController?
Jquery.ajax does not encode POST data for you automatically the way that it does for GET data. Jquery expects your data to be pre-formatted to append to the request body to be sent directly across the wire.
A solution is to use jQuery.param function to build a query string that process POST requests expect.
Change data object in you method to the format below, and hopefully, it will work.
data: jQuery.param({ idProduct : idProduct, count : count }),
contentType: 'application/x-www-form-urlencoded; charset=UTF-8'
Change your ajax like below. You do not need to send data because you are not expecting data in body in your post controller.
$.ajax({
url : '/ajax/json/product/add?idProduct='+idProduct+'&count='+count,
method : 'POST',
success : function(data) {
$('#currentShoppingCart .total-count').text(data.totalCount);
$('#currentShoppingCart .total-cost').text(data.totalCost);
$('#currentShoppingCart').removeClass('hidden');
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
$('#addProductPopup').modal('hide');
},
error : function(xhr) {
convertLoaderToButton(btn, 'btn-primary', addProductToCart);
if (xhr.status == 400) {
alert(xhr.responseJSON.message);
} else {
alert('Не сработала JS функция добавления в коризну');
}
}
});

I am trying to use jQuery with Spring MVC to get "bookid" from the databse but i am getting error alert every time

Hi there I am using jQuery with Spring MVC to get the book_id from the database but I am getting error alert every time
I have used jQuery ajax() method and defined all the parameters properly like url and in Controller i have used all proper annotations but failed to get the output.
$(document).ready(function () {
$("#bookId").keypress(function () {
var bookid = $(this).val();
alert($(this).val());
$.ajax({
url: "getBookQuantity.htm",
data: {
bookid : bookid
},
dataType: "json",
success: function (json) {
if (json !== null) {
alert(json);
}
},
error: function (e) {
alert("Some error occured while getting book id list");
}
});
});
});
Controller code:
#RequestMapping(value = "/getBookQuantity.htm")
#ResponseBody
public String getBookQuantity(#RequestParam(value = "bookid", defaultValue = "0") int bookid) {
System.out.println("bookid======="+bookid);
int quantity = this.bookService.checkBookQuantity(bookid);
String json = null;
Gson gson = new Gson();
json = gson.toJson(quantity);
return json;
}
Getting error alert every time

POSTing data return error instead of success

I am new to Spring MVC and I am trying to send my data to Spring-MVC Controller using AJAX, on button click. I have written this code (given below) but I am getting error instead of success. please tell what can be the issue?
AJAX:
function add() {
var name = $('#name').val();
$.ajax({
url : "/addUser",
data : name,
type : "POST",
async: false,
success : function(response) {
alert( response );
},
error : function() {
alert("error....");
}
});
}
JAVA
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(#ModelAttribute("UserTest") String name) {
//task
return name;
}

Return Json from Spring Controller After Uploading File via AngularJS

FrontEnd: jsp with AngularJS
BackEnd: Spring MVC/Java
I am uploading a file using ng-flow, angularJS. Source: https://github.com/flowjs/ng-flow
File upload is successful. I need to return a json from my Spring Controller. Any clues how to go about it?
P.S. can't find where to put in .success() function, if at all that is applicable.
Spring Controller:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
}
app.js code:
(function() {
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'upload',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
app.controller('PageController', function() {
//this.products = gems;
});
app.controller("TabController", function() {
this.tab = 1;
this.showOutput = false;
this.viewEvents = false;
this.isSet = function(checkTab) {
return this.tab === checkTab;
};
this.changeVal = function() {
this.viewEvents = true;
};
this.setTab = function(setTab) {
this.tab = setTab;
};
});
})();
What exactly should be returned from the spring controller? (String/#ResponseBody String etc)
How to collect that json in angular?
On your controller #ResponseBody should be added and the jo returned as String:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public #ResponseBody String uploadFileHandler(#RequestParam("file") MultipartFile file, Model model) {
//Upload file and process
JsonObject jo = Json.createObjectBuilder().add(path, folderPath.toString())
.add(aContentsAttrib, aContents)
.add(bContentsAttrib, bContents).build();
return jo.toString();
}
In AngularJS, you should do this for being able to post files and then retrieve the data back:
$http({url: '/url',
method: 'POST',
data: $scope.myFile,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success(data){
$scope.myData = data;
});
In your Spring controller you should just return an Object containing the properties you want to transfer to your angular service. This will be automatically (or by default) be converted to JSON. #RequestBody is not needed.
This return value will be available in the success callback, something like:
$http({
method: 'POST',
url: '...',
}).success(function (data) {
//data is your JSON response
})},
If you are using Spring 3 you can do this
#RequestMapping(value = "/getDealers", value = "/upload", method = RequestMethod.POST)
#ResponseBody
public String uploadFileHandler() {
}
#ResponseBody annotation directly writes the response to the response stream. You would not need a JSP. Just send the request for the controller from the browser & the controller method will write the response to the response stream.
You can parse the response using Jquery or any json library & display in the JSP
Check this out
An alternate way, which I just found out. Will be useful to extract from existing code, without any modification. It does introduce an extra global variable, outside your main angular app, and might not be highly recommended, but still, posting this.
var json = {};
var app = angular.module('app', ['flow'])
.config(['flowFactoryProvider', function (flowFactoryProvider) {
flowFactoryProvider.defaults = {
target: 'processxls',
permanentErrors: [404, 500, 501],
maxChunkRetries: 4,
chunkRetryInterval: 500,
simultaneousUploads: 4
};
flowFactoryProvider.on('catchAll', function (event) {
console.log('catchAll', arguments);
this.jsonResponse = arguments[2]; //Note this change
//json = this.jsonResponse;
console.log(this.jsonResponse);
json = angular.fromJson(this.jsonResponse);
});
// Can be used with different implementations of Flow.js
// flowFactoryProvider.factory = fustyFlowFactory;
}]);
'json' variable now has the json response received. You can use it for further use now.
P.S. in order to check for which value of 'i' arguments[i] gives you the json, see console.

Returning Hashmap From controller to JSP in Springmvc

I have two dropdownlists in Jsp One for state and other for country. As soon as i select country the statelist should be populated automatically with respective lists. But i am getting whole jsp page as response in ajax call.
My ajax Program:
$("select#country").change(function() {
var val=$("#country").val();
alert(val);
$.ajax({
url : 'getstates',
method : 'get',
contentType: 'application/json',
data :{
country : val
},
success: function (data) {
alert("Success Response"+ data);
},
error :function()
{
alert("error");
}
});
My controller program
#RequestMapping(value = "/getstates", method = RequestMethod.GET)
public ModelAndView showstates(#RequestParam(required = false, value = "")
String country,#Valid #ModelAttribute("employee")Login employee,
BindingResult result, Model model) {
HashMap<String,String> stateMap = new HashMap<String,String>();
//put your logic to add state on basis of country
if (country.equals("UnitedStates")) {
stateMap.put("Al","Alaska");
stateMap.put("Tl","Texas");
} else if (country.equals("UnitedKingdom")) {
stateMap.put("Be","Bedfordshire");
stateMap.put("Ber","Berkshire");
} else if (country.equals("India")) {
stateMap.put("Mh","Maharashtra");
stateMap.put("WB","West Bengal");
stateMap.put("KR","Karnataka");
stateMap.put("AP","Andhra Pradesh");
stateMap.put("TN","Tamil Nadu");
}
return new ModelAndView("LoginForm","state" ,stateMap);
}
I am using spring form. I need to get only Staemap as respone but i am getting whole jsp page as response.
I need to get only Staemap as respone but i am getting whole jsp page
as response.
Because you are returning the ModelAndView object with the view here,
return new ModelAndView("LoginForm","state" ,stateMap);
If you need to return the respone alone from the controller method.However you cant print the HashMap directly in the ajax response on your jsp. IMHO you can convert it to JSONArray
JSONArray jarray = JSONArray.fromObject(statemap);
Read ,
send array from controller to a view using JSON in MVC
Sending JSON response from spring controller
loop through json array jquery
#RequestMapping(value="LoadBaselineVersions")
#ResponseBody
public Map<Integer,String> loadBaseNames(#RequestParam(value="projectname") String name,HttpSession session){
return basenameService.getBaselineversions(name);
}
$("#projectname").bind(
'blur',
function() {
$.ajax({
type : 'post',
url : 'LoadBaselineVersions?projectname='
+ $("#projectname").val(),
dataType : 'json',
success : function(data) {
$("#baseversion").empty();
$.each(data, function(val, text) {
$("#baseversion").append(
$('<option></option>').val(text).html(
text));
});
}
});
});

Categories