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
Related
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";
}
}
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!
I am trying call a spring mvc controller from a form in my page, this my controller.
#RequestMapping(value = "/editor/create", method = RequestMethod.POST)
public ResourceDTO create(#RequestBody ResourceCreateDTO dto)
throws Exception {
ResourceDTO responseDTO = null;
//Add the resourceCreate and gets the responseDTO.
return responseDTO;
}
This my ajax call:
$.ajax({
type: "POST",
url: context + "/editor/create",
data: $("#createForm").serialize(),
cache: false,
success:function(result){
},
error:function(){
}
});
I'm getting this response: HTTP 415
This mi form call data (From developer view on Chrome):
resource-id:1006
resource-name:asdf
resource-description:asdfasdf
resource-folder:0
resource-folder-type:1000
resource-scene-width:
resource-scene-height:
I only have to use filled fields in this option. Not problem for empty fields.
Mi ResourceCreateDTO (serializable) have this fields:
private Integer resourceTypeId;
private Integer resourceId;
private String resourceName;
private String resourceDescription;
private Integer folderId;
private Integer resourceType;
private Integer sceneWidth;
private Integer sceneHeight;
/**GETTERS AND SETTERS**/
Just written some code for redirecting and forwarding from one action to another action in spring mvc.Also done some permutations with GET and POST.
My question is how things work when we redirect/forward from one action with #RequestMapping to another action having #RequestMapping and #ResponseBody.
Below is the code snippet for controller and jsp with ajax script.Comments are mentioned on the methods which are not working with response error.
#Controller
#RequestMapping(value = "/myMvc")
public class MyMvcController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model map, HttpServletRequest req) {
return "home";
}
#RequestMapping(value = "/action1", method = RequestMethod.POST)
public #ResponseBody String action1(Model map, HttpServletRequest req) {
return "Sending response body as POST";
}
#RequestMapping(value = "/action2", method = RequestMethod.GET)
public #ResponseBody String action2(Model map, HttpServletRequest req) {
return "sending response body as GET";
}
/*****action3 to action6 Redirect******/
//POST to GET
#RequestMapping(value = "/action3", method = RequestMethod.POST)
public String action3(Model map, HttpServletRequest req) {
return "redirect:/myMvc/action2";
}
//POST to POST
#RequestMapping(value = "/action4", method = RequestMethod.POST)
public String action4(Model map, HttpServletRequest req) {
//will not execute
//Request method 'GET' not supported
return "redirect:/myMvc/action1";
}
//GET to POST
#RequestMapping(value = "/action5", method = RequestMethod.GET)
public String action5(Model map, HttpServletRequest req) {
//will not execute
//Request method 'GET' not supported
return "redirect:/myMvc/action1";
}
//GET to GET
#RequestMapping(value = "/action6", method = RequestMethod.GET)
public String action6(Model map, HttpServletRequest req) {
return "redirect:/myMvc/action2";
}
/*****action7 to action10 Forward******/
//POST to GET
#RequestMapping(value = "/action7", method = RequestMethod.POST)
public String action7(Model map, HttpServletRequest req) {
//will not execute
//Request method 'POST' not supported
return "forward:/myMvc/action2";
}
//POST to POST
#RequestMapping(value = "/action8", method = RequestMethod.POST)
public String action8(Model map, HttpServletRequest req) {
return "forward:/myMvc/action1";
}
//GET to POST
#RequestMapping(value = "/action9", method = RequestMethod.GET)
public String action9(Model map, HttpServletRequest req) {
//will not execute
//Request method 'GET' not supported
return "forward:/myMvc/action1";
}
//GET to GET
#RequestMapping(value = "/action10", method = RequestMethod.GET)
public String action10(Model map, HttpServletRequest req) {
return "forward:/myMvc/action2";
}
}
home.jsp file
<button onclick="hitAction3()">hit action3</button><br><br>
<button onclick="hitAction4()">hit action4</button><br><br>
<button onclick="hitAction5()">hit action5</button><br><br>
<button onclick="hitAction6()">hit action6</button><br><br>
<button onclick="hitAction7()">hit action7</button><br><br>
<button onclick="hitAction8()">hit action8</button><br><br>
<button onclick="hitAction9()">hit action9</button><br><br>
<button onclick="hitAction10()">hit action10</button><br><br>
<script>
function hitAction3() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action3",
}).done(function(data) {alert(data);});
}
function hitAction4() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action4",
}).done(function(data) {alert(data);});
}
function hitAction5() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action5",
}).done(function(data) {alert(data);});
}
function hitAction6() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action6",
}).done(function(data) {alert(data);});
}
function hitAction7() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action7",
}).done(function(data) {alert(data);});
}
function hitAction8() {
$.ajax({
method:'POST',
url: "${pageContext.request.contextPath}/myMvc/action8",
}).done(function(data) {alert(data);});
}
function hitAction9() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action9",
}).done(function(data) {alert(data);});
}
function hitAction10() {
$.ajax({
method:'GET',
url: "${pageContext.request.contextPath}/myMvc/action10",
}).done(function(data) {alert(data);});
}
</script>
What I already know is :
In Redirect :A new request object is created.
In Forward :Same request object is forwarded to next action.
Please share some rules or information regarding this if I am missing.
A redirect will send an HTTP 302 response to the client with a Location header, so the client will perform a GET in any case.
If you want your "POST to POST" case to work, use a forward prefix.
Check out this SO question for more details on forward vs. redirect.
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;
}