Post two array as json through ajax to Spring Controller - ajax

My ajax method
$.ajax(
{
type: "POST",
contentType: 'application/json;charset=utf-8',
dataType:'json',
url: 'addrequisition',
data: JSON.stringify([{ ids: val, qty: valtxt }]),
success: function(result)
{
$("#result").html(result);
}
});
});
and my arrays are val and valtxt.
I want to read those arrays in a Spring Controller help me :)

First, you need to define a class in java like this:
class MyClass{
private String ids;
private String qty;
//Setters and Getters
}
Note that the members of class MUST be same as json data.
then in your controller you need to define action like this:
#RequestMapping(value = "/addrequisition", method = RequestMethod.POST)
public String addrequisition(#RequestBody MyClass myClass) {
String result = myClass.getIds() + myClass.getQty();
return result;
}

Related

Error ajax can not pass params to Spring Controller

var companyCode = [];
var data = {
'companyCode': companyCode, //array this may be problem
'actionUserGroup': usersession.userGroup,
'formType': 'IN',
'actionId': usersession.userId,
'submittedDate': [submitted_s,submitted_e] //array this may be problem
};
console.log(data);
$.ajax({
type : "POST",
data : JSON.stringify(data),
contentType: "application/json; charset=utf-8",
crossDomain: true,
cache: false,
url: appConfig.endPoint + 'search/myTask',
success: function(data){
console.log(data);
}
});
{this ajax side}
#RequestMapping(value = "/myTask", method = RequestMethod.POST)
public #ResponseBody JSONObject searchmyTask(Model model, HttpSession session,
#RequestParam (value="companyCode") String[] companyCode,
#RequestParam (value="actionUserGroup") String actionUserGroup,
#RequestParam (value="formType") String formType,
#RequestParam (value="actionId") String actionId,
#RequestParam (value="submittedDate") String[] submittedDates
) throws Exception {
/**
* if "userGroup" = 'ADMIN'
{this Spring Controller}
http://localhost:9091/gcbg/search/myTask 400 (Required String[] parameter 'companyCode' is not present) jquery.min.js:2 POST
{this one is error}
Please help me to figure out this problem. Thanks
i just did few changes to make it work, so if you modify the next options should work for yourself.
$.ajax({
method : "POST",
data : data,
crossDomain: true,
cache: false,
url: appConfig.endPoint + 'search/myTask',
success: function(data){
console.log(data);
}
});
And in your controller:
#RequestMapping(value = "/myTask", method = RequestMethod.POST)
public #ResponseBody JSONObject searchmyTask(Model model, HttpSession session,
#RequestParam (value="companyCode[]") String[] companyCode,
#RequestParam (value="actionUserGroup") String actionUserGroup,
#RequestParam (value="formType") String formType,
#RequestParam (value="actionId") String actionId,
#RequestParam (value="submittedDate[]") String[] submittedDates
) throws Exception {
Hope it helps

When cache false in set in ajax,it add some value in request what it is

I using a small code of Ajax and my code is working.There is no error in my code but when i set cache false in my ajax it add some value in request.I want to know What is the value and its purpose.
My code is
function validate() {
var user = $('#user').val();
var num = $('#num').val();
var mobile= $('#otp').val();
$.ajax({
type: "GET",
url: "/validateOtp",
data: {user: user , num: num , mobile: mobile},
dataType: 'text',
cache: false,
timeout: 600000,
success : function(response) {
alert( response );
},
error : function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
it generate request like this in browser
http://localhost:8080/validateOtp?user=1234&num=12345&otp=1234&_=1528862398631
you can see the value added by ajax &_=1528862398631
and My backend code is in Spring MVC
#Controller
#RequestMapping("/validateOtp")
public class ValidateOTPAjaxController {
private final Logger logger =
LogManager.getLogger(this.getClass().getSimpleName());
#Autowired
private OTPService otpService;
#RequestMapping(method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public String getAllDistrict(#RequestParam(value = "user") String user,
#RequestParam(value = "num") String num, #RequestParam(value = "mobile") String mobile) {
logger.debug(user);
logger.debug(num);
logger.debug(mobile);
return "OK";
}
By setting the cache property to false jQuery will append a timestamp to the URL, so the browser won't cache it (as the URL is unique for every request. See the documentation for details: http://api.jquery.com/jQuery.ajax/
And your controller should be like following:
#Controller
public class ValidateOTPAjaxController {
private final Logger logger =
LogManager.getLogger(this.getClass().getSimpleName());
#Autowired
private OTPService otpService;
#RequestMapping(value = "/validateOtp", method = RequestMethod.GET)
public String getAllDistrict(#RequestParam("user") String user,
#RequestParam("num") String num, #RequestParam("mobile") String mobile) {
logger.debug(user);
logger.debug(num);
logger.debug(mobile);
return "OK";
}
}

Throw custom exception from Spring controller and receive it in ajax-post error function

So, i need to add custom validation to my page, the problem is, i don't have any form, i collect and send data almost manually, here is my ajax post:
$.ajax({
type: "POST",
url: "/settings/propertyedit",
dataType: 'json',
contentType: 'application/json;charset=UTF-8',
data: {
propertyName : propName,
propertyValue : propVal,
Id : Id,
SettingId : SettingId,
},
beforeSend: function (xhr) {
xhr.setRequestHeader($.metaCsrfHeader, $.metaCsrfToken);
},
success: function (response) {
//Do some something good
},
error: function(response){
//do some something worning
}
});
And controller:
#Link(label = "property edit", family = "SettingsController", parent = "Settings")
#RequestMapping(value = "/settings/propertyedit", method = RequestMethod.POST)
#ResponseBody
public String atmpropertyedit(#RequestParam String propertyName,
#RequestParam String propertyValue,
#RequestParam Long Id,
#RequestParam Long SettingId) {
//Check if it is an error
//If correct i want to return some text in success function
//If error happens want to return some relevant text to error function
}
So, the point is, that validation is also custom, so i cant throw exception simply with try catch and if i am trying to do something like:
return new ResponseEntity<>(HttpStatus.NOT_EXTENDED);//Error type is for testing purposes
I will get 400 error even without triggering into my controller. At this point i just want some simple method to let know my ajax what has happened in my controller.
The controller can be as simple as this one, you can make it happen with custom response class which I named CommonResp and an Enum VALIDATION.
Controller - returns Response class.
#ResponseBody
public CommonResp atmpropertyedit(#RequestParam String propertyName,
#RequestParam String propertyValue,
#RequestParam Long Id,
#RequestParam Long SettingId) {
// error
if (!isValidPropertyName(propertyName)) return new CommonResp(VALIDATION.INVALID_PROPERTY_NAME);
// success
return new CommonResp(VALIDATION.OK);
}
}
CommonResp.java - will be the json response.
public class CommonResp implements Serializable {
private int code;
private String message;
public CommonResp() {
this(VALIDATION.OK);
}
private CommonResp(final int code, final String message){
this.code = code;
this.message = message;
}
public CommonResp(VALIDATION validation) {
this(validation.getCode(), validation.getMessage());
}
/* Getters and Setters */
}
VALIDATION.java
public enum VALIDATION {
OK(200, "OK"),
INVALID_PROPERTY_NAME(401, "PropertyName is not valid");
private int code;
private String message;
private VALIDATION(int code, String message) {
this.setCode(code);
this.message = message;
}
/* Getters and Setters */
}
Please let me know if there are any better implementations. (propably tons of, It's just that i don't know :P)

Return Object from controller to ajax

Code below succesfully send String from jsp via ajax to controller and returning some String.
How to send back (from controller to ajax) object which contains only getter and setter or Boolean?
ajax:
$.ajax({
type: 'get',
url : 'register/checkUsername',
data : {'typedText' : typedText},
success : function(data) {
$('#doesUsernameAvailable').text("ok " + data);
},
error: function(){
$('#doesUsernameAvailable').text('error');
}
});
controller:
#RequestMapping(value = "/checkUsername", method = RequestMethod.GET)
public #ResponseBody String checkUsername(String typedText,
HttpServletResponse response){
//some code with return Boolean or Object
return "text from controller";
}
Solution:
I does not post pom.xml. It was missing:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
And now few modification's.
ajax:
$.ajax({
type : 'get',
contentType : "application/json",
url : 'register/checkUsername',
data : {'typedText' : typedText},
dataType : 'json',
success : function(data) {
$('#doesUsernameAvailable').text("ok " + data.isAvailable);
},
error: function(){
$('#doesUsernameAvailable').text('error');
}
});
And now we can return Object from Controller via JSON.
Controller:
#Controller
#RequestMapping("/register")
public class RegisterController {
#RequestMapping(value = "/checkUsername", method = RequestMethod.GET)
public #ResponseBody CheckUsernameResponse checkUsername(
#RequestParam String typedText){
return new CheckUsernameResponse(true);
}
Object:
public class CheckUsernameResponse {
private Boolean isAvailable;
public CheckUsernameResponse(Boolean isAvailable) {
this.isAvailable = isAvailable;
}
Hope it help!

Spring 3 MVC - Advanced Data Binding - Form Request with List of Simple Objects

I've read through all of the Spring 3 Web docs: http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/spring-web.html but have been completely unable to find any interesting documentation on binding more complicated request data, for example, let's say I use jQuery to post to a controller like so:
$.ajax({
url: 'controllerMethod',
type: "POST",
data : {
people : [
{
name:"dave",
age:"15"
} ,
{
name:"pete",
age:"12"
} ,
{
name:"steve",
age:"24"
} ]
},
success: function(data) {
alert('done');
}
});
How can I accept that through the controller? Preferably without having to create a custom object, I'd rather just be able to use simple data-types, however if I need custom objects to make things simpler, I'm fine with that too.
To get you started:
#RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething() {
System.out.println( wantToSeeListOfPeople );
}
Don't worry about the response for this question, all I care about is handling the request, I know how to deal with the responses.
EDIT:
I've got more sample code, but I can't get it to work, what am I missing here?
select javascript:
var person = new Object();
person.name = "john smith";
person.age = 27;
var jsonPerson = JSON.stringify(person);
$.ajax({
url: "test/serialize",
type : "POST",
processData: false,
contentType : 'application/json',
data: jsonPerson,
success: function(data) {
alert('success with data : ' + data);
},
error : function(data) {
alert('an error occurred : ' + data);
}
});
controller method:
public static class Person {
public Person() {
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
String name;
Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
#RequestMapping(value = "/serialize")
#ResponseBody
public String doSerialize(#RequestBody Person body) {
System.out.println("body : " + body);
return body.toString();
}
this renders the following exception:
org.springframework.web.HttpMediaTypeNotSupportedException:
Content type 'application/json' not
supported
If the doSerialize() method takes a String as opposed to a Person, the request is successful, but the String is empty
Your jQuery ajax call produces the following application/x-www-form-urlencoded request body (in %-decoded form):
people[0][name]=dave&people[0][age]=15&people[1][name]=pete&people[1][age]=12&people[2][name]=steve&people[2][age]=24
Spring MVC can bind properties indexed with numbers to Lists and properties indexed with strings to Maps. You need the custom object here because #RequestParam doesn't support complex types. So, you have:
public class People {
private List<HashMap<String, String>> people;
... getters, setters ...
}
#RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething(People people) {
...
}
You can also serialize data into JSON before sending them and then use a #RequestBody, as Bozho suggests. You may find an example of this approach in the mvc-showcase sample.
if you have <mvc:annotation-driven> enabled then:
#RequestMapping("/controllerMethod", method=RequestMethod.POST)
public String doSomething(#RequestBody List<Person> people) {
System.out.println( wantToSeeListOfPeople );
}
(List<Person> might not be the structure you would like to obtain, it's just an example here)
You can try setting the Content-Type of $.ajax to be application/json, if it doesn't work immediately.
Have a look at Jackson's spring integration. It is incredible easy to use and powerful.
A question/answer on SO that can help guide on this:
Spring 3.0 making JSON response using jackson message converter

Resources