Handling a List of Object in AJAX and Spring - ajax

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]
Open Output Image
* 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]

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;
}

Related

400 bad request,Is there any problem with the code in controller?

I'm trying to send data to controller by ajax,but met with problem Failed to load resource: the server responded with a status of 400 (Bad Request).I don't know which part of the problem
JS:
var info ={
"questions":{"q1":trim(q1), "q2":trim(q2),"q3":trim(q3),"q4":trim(q4),"q5":trim(q5),"q6":trim(q6),"q7":trim(q7),"q8":trim(q8)},
"answers":{"datetimepicker":datetimepicker,"sexual":sexual,"nation":nation, "province":province,"city":city, "sheng":sheng,"shi":shi,"xian":xian, "height":height,"weight":weight}
};
var info_str = JSON.stringify(info);
$.ajax({
type:'GET',
data:info_str,
contentType: "application/json; charset=utf-8",
dataType: "json",
url :'/yiban',
success :function(data) {
alert(data);
},
error :function(e) {
alert("error");
}
});
Java:
#RequestMapping(value = "/yiban", method = RequestMethod.GET)
public void yiban(HttpServletRequest request)
{
String jsonStr = request.getParameter("info_str");
JSONObject questions = JSONObject.fromObject(jsonStr).getJSONObject("questions");
JSONObject answers = JSONObject.fromObject(jsonStr).getJSONObject("answers");
String q1 = questions.getString("q1");
String ans = answers.getString("nation");
System.out.println(q1);
}
#RequestMapping(value = "/yiban", method = RequestMethod.POST)
public void yiban(HttpServletRequest request) throws IOException {
//GET method parameter is passed with url , json data can't go with url. json or xml is passed in request boy
// String jsonStr = request.getParameter("info_str");
ServletInputStream inputStream = request.getInputStream();
String jsonStr=StreamUtils.copyToString(inputStream, Charset.forName("UTF-8"));
JSONObject questions = JSONObject.fromObject(jsonStr).getJSONObject("questions");
JSONObject answers = JSONObject.fromObject(jsonStr).getJSONObject("answers");
String q1 = questions.getString("q1");
String ans = answers.getString("nation");
System.out.println(q1);
}
Above is my code which works in my project .
Firstly ,use POST to send json or xml!
and use request.getInputStream to receive json data!
Secondly you RequestMappingMethod returns nothing, your front web receive nothing !
What view you want to return to Front?

redirect to another jsp page

I m trying to redirect control to next jsp page. If the boolean value is true redirect to success jsp page else redirect to login page.
#RequestMapping(value = "/validate", method = RequestMethod.POST)
#ResponseBody
public ModelAndView(HttpServletRequest request, HttpServletResponse response, Model model) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
boolean validuser=employeeService.checkLogin(userName,password);
if(validuser == true)
{
model.setViewName("success");
return model;
}
model.setViewName("login");
return model;
}
This is my Ajax call.
$(document).ready(function() {
$("form").submit(function() {
var userName=$("#inputEmail").val();
var password=$("#inputPassword").val();
$.ajax({
type : "post",
url : "${pageContext.request.contextPath}/validate",
data : {userName:userName, password:password},
success:function(data){
alert(data);
},
error:function()
{
alert("Error ");
}
});
});
});
Control is not going to success block. Only the error alert is getting displayed.
public String validate(HttpServletRequest request, HttpServletResponse response, Model model) {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
boolean validuser=employeeService.checkLogin(userName,password);
if(validuser == true)
{
return "redirect:/success";
}
else{
return "redirect:/login";
}
}
I have tried it using this approach. Still its entering error block.
Add window.location.href = 'YOUR_REDIRECT_URL' in your success callback.
success:function(data){
alert(data);
window.location.href = 'YOUR_REDIRECT_URL'; // redirect
},
If it's an ajax call, you can't use the redirect: in the return url. On your controller, return "http://example.domain.com/success". Then in your success handler use window.location.href = 'redirect_url'

send data from ajax to spring controller

var form_data = {
itemid: globalSourceItem.substr(globalSourceItem.indexOf("-") + 1),
columnName: jqInputs[0].value,
displayName: jqInputs[1].value,
format: jqInputs[2].value,
KBE: jqInputs[3].value,
dgroup: jqInputs[4].value,
dupkey: jqInputs[5].value ,
measurement: jqInputs[6].value ,
times: new Date().getTime()
};
// console.log(form_data);
// console.log($("#tourl").html());
$.ajax({
url: $("#tourl").html(),
type: 'POST',
datatype: 'json',
data: form_data,
success: function(message) {
var j_obj = $.parseJSON(message);
// console.log(j_obj);return false;
if (j_obj.hasOwnProperty('success')) {
toastr.info('Item updated successfully');
setTimeout(function(){
window.location.reload();
},1000);
} else {
toastr.info('There was a problem.');
}
},
error: function(xhr, textStatus, errorThrown)
{
toastr.info('There seems to be a network problem. Please try again in some time.');
}
});
}
Hii friends , this code is working for php and i need to send the same data to the spring mvc through the ajax , can anyone please help me with the exact solution where to make changes as Iam struckup with the same doubt for like 2 weeks...
public class TestController {
#RequestMapping(value = "url", method = RequestMethod.POST)
public ModelAndView action(#RequestBody FormData formData) {
...
}
}
public class FormData {
private String itemid;
public String getItemid() {
return itemid;
}
public void setItemid(String itemid) {
this.itemid = itemid;
}
//...
}
Try sth like this. You should be able to map JSON Object to Java Object.
Maybe you could use annotation #ResponseBody and convert JSONObject to String:
#RequestMapping(value = "/ajax", method = RequestMethod.POST, produces="application/json")
#ResponseBody
public String ajax(#RequestBody ListDataDefinition listDataDefinition) {
System.out.println("id="+listDataDefinition.getItemid());
int i=SchemaDAOI.updateldd(listDataDefinition);
String message="success";
JSONObject obj = new JSONObject();
try {
obj.put("success", "success");
}
catch (JSONException e) {
e.printStackTrace();
}
if(i==1){
System.out.println("success");
}
else{
System.out.println("failure");
}
return obj.toString();
}
}
If you send String to View as ResponseBody and set produces as JSON it should be treated as pure JSON RQ.

Ajax function returning error calling Spring Controller

Trying to call Spring Controller from jsp code. We are getting a error message Error object [Object]. What's missing ?
JSP code
<script type="text/javascript">
function doAjaxPost() {
// get the form values
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
alert(firstName + " and " + lastName);
$.ajax({
type: "GET",
url: "/DriverController/AddUser",
data: "firstName=" + firstName + "&lastName=" + lastName,
success: function(response){
alert(data);
// we have the aresponse
$('#info').html(response);
$('#firstName').val('');
$('#lastName').val('');
}
,
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Controller Code
package net.codejava.spring;
public class DriverController {
private List<DriverPojoWrapper> userList = new ArrayList<DriverPojoWrapper>();
#RequestMapping(value="/AddUser",method=RequestMethod.GET)
public String showForm(){
System.out.println("Calling DriverController showform /AddUser GET");
return "AddUser";
}
#RequestMapping(value="/AddUser",method=RequestMethod.POST)
public #ResponseBody String addUser(#ModelAttribute(value="user") DriverPojoWrapper driver, BindingResult result ){
String returnText;
if(!result.hasErrors()){
userList.add(driver);
returnText = "User has been added to the list. Total number of users are " + userList.size();
}else{
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value="/ShowUsers.htm")
public String showUsers(ModelMap model){
model.addAttribute("Users", userList);
return "ShowUsers";
}
The servet-controller xml has
<context:component-scan base-package="net.codejava.spring" />

How to send boolean result to ajax call

I want to send Boolean result in ajax call.
Ajax call
function myMethod() {
$.ajax({
type : "GET",
url : myurl
dataType : "json",
contentType: "application/json",
crossDomain: true,
success : function(data) {
alert("success :"+data);
},
error : function(data) {
alert("Fialed to get the data");
}
});
}
Controller method from where I want to send Boolean result.
#RequestMapping(value = "/myMethod", method = RequestMethod.GET)
#ResponseBody
public boolean myMethod(empId) {
flag = false;
try {
if (empId != null)
newName = Employee.getName(empId);
else
newName = Employee.getName();
} catch (Exception e1) {
flag = true;
System.out.println("flag :" + flag);
e1.printStackTrace();
}
return flag;
}
i want to send the Boolean flag result to ajax call.
How do i send it. dont mind about the logic .. I just want to know how can i send boolean result to ajax call. Please help .
Ajax uses HTTP which is a text protocol and has no concept of booleans. However, you can return the strings "1" or "0" to represent your boolean values.
Then, in your "success" callback:
success : function ( data ) {
if ( data * 1 ) {
// true result
} else {
// false result
}
}
Without passing the Boolean value to the Ajax call, you can do some thing like this using a map. Using this map you can send anything rather than only limiting to Boolean values.
#RequestMapping(value = "/myMethod", method = RequestMethod.GET)
#ResponseBody
public Map<String, Object> myMethod(empId)
{
flag=false;
try {
if(empId != null)
newName = Employee.getName(empId);
else
newName = Employee.getName();
} catch (Exception e1) {
flag=true;
System.out.println("flag :"+flag);
e1.printStackTrace();
}
final Map<String, Object> map = new TreeMap<String, Object>();
map.put("flagdata", flag);
return map;
}
Then you can access this 'flagdata' object in the Ajax call.
Your Ajax code will be some thing like this.
$.ajax({
type : "GET",
url : myurl
dataType : "json",
contentType: "application/json",
crossDomain:true,
success : function(data) {
alert("success :"+data.flagdata);
},
error : function(data) {
alert("Fialed to get the data");
}
});
Hope it helps.!

Resources