Issue
I am not able to parse a list of objects in AJAX, Whenever I try to parse the list, ERROR code 406 pops. But if I try to send a string it receives fine.
Controller Code
@RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
@ResponseBody
public List<State> liststates(HttpServletRequest request){
String country = request.getParameter("country");
List<State> states = adminService.getAllstates(Integer.parseInt(country));
System.out.println("The states we recieved is" +states);
String result ="hello Bhaskar "+ country;
return states;
}
JSP AJAX Code
var id = $('#select_country').val();
$.ajax({
url : "getstates",
data: {country : id},
dataType: 'application/json',
type: 'POST',
success : function(response) {
alert("Access Success "+ response);
$('#select_country').append("<option value='-1'>Select User</option>");
for ( var i = 0, len = response.length; i < len; ++i) {
var user = response[i];
$('#select_country').append("<option value=\"" + user.id + "\">" + user.state+ "</option>");
}
},
error : function(response) {
alert("Access Fail "+ response);
}
* Browser Output* Access Failed [object Object]
* Console Output*
The states we received is [in.complit.model.State@7dee7dc6, in.complit.model.State@54263ffc, in.complit.model.State@43e78960, in.complit.model.State@4ce669b5]
Solution
The Problem Solved by adding a try-catch block while calling the service class method in the Controller Class. The code after adding it is as shown below.
@RequestMapping(value = "getstates", method= RequestMethod.POST, produces="application/json")
@ResponseBody
public List<State> liststates(HttpServletRequest request){
//List<Country> listCountries = adminService.getAllcountries();
String country = request.getParameter("country");
List<State> states = new ArrayList<State>();
try {
states = adminService.getAllstates(Integer.parseInt(country));
}catch(Exception e) {
System.out.println(e);
}
System.out.println("The Country We Recieved "+ country);
System.out.println("The states we recieved is" +states);
return states;
}
Answered By - Bhaskar Ranjan
Answer Checked By - Marilyn (JavaFixing Volunteer)