For my application I am writing a POST request to send array of parameters from a checkbox list. Its working for get request but not working for post request. What is the error in my code.
My code on the client side for sending ajax request to the server.
$(".add").click(function(){
monitoring.length=0;
nonMonitoring.length=0;
$('.modal-body input:checked').each(function() {
monitoring.push($(this).val());
});
$('.addkeywords input:checked').each(function() {
nonMonitoring.push($(this).val());
});
// alert(monitoring[2]+ " " + nonMonitoring[2]);
var monitoringLength=monitoring.length;
var nonMonitoringLength=nonMonitoring.length;
$.ajax({
type : "POST",
url : '/rest/channelstats/my/rest/controller',
data : {
// monitoring : monitoring,
// nonMonitoring: nonMonitoring,
monitoringLength: monitoringLength,
nonMonitoringLength: nonMonitoringLength,
},
success : function(data) {
// var keywordsList=data
//console.log(keywordsList);
// htm = "" ;
}
});
})
My java code on the server side.
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestParam(value="monitoringLength",required=true)int monitoringLength,#RequestParam(value="nonMonitoringLength",required=true)int nonMonitoringLength){
System.out.println("MonitoringLength =>" +monitoringLength);
System.out.println("NonMonitoringLength=>" +nonMonitoringLength);
}
}
Its working for HTTP GET requests but not working for POST requests.How should I solve this problem?
According to your jquery post request, you should use DAO(Data Access Object) to parse the request data. So you should add class Request
public class Request {
private int monitoringLength;
private int nonMonitoringLength;
//getters and setters
}
And change controller to
#RequestMapping(value="/rest/channelstats/my/rest/controller",method = RequestMethod.POST)
public void monitorKeywords(#RequestBody Request request){
System.out.println("MonitoringLength =>"+request.getMonitoringLength());
System.out.println("NonMonitoringLength=>"+request.getNonMonitoringLength());
}
Related
In my ionic 5.0.0 application I'm using cordova's native HTTP to make the rest calls. Below is the code snippet of my logout function.
But when i execute this function i'm getting following error.
"advanced-http: \"data\" argument supports only following data types: String"
logout() {
this.setData("url", "/web/oauth/revoke-token");
let apiUrl = this.getBaseUrl() + this.getData("url");
const headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic Y2hyR3liUnBxQUR3X2VDemw5dzc0cHU4dXNnYTpKdmZ1azgyYnBUQlVnNDJ6NU1hZFhXOWJPeElh'
};
const params = {
'companyId': this.getData("COMPANY_ID"),
'token': this.getData("ACCESS_TOKEN"),
'client_id': this.getData("CLIENT_ID"),
'token_type_hint': 'access_token'
};
this.nativeHttp.post(apiUrl, params, headers).then(response => {
console.log("success response: "+response);
})
.catch(error => {
console.log("error response: "+error);
});
console.log("finished");
}
Here is my Spring controller which receives the params.
#RequestMapping(value = "/oauth/revoke-token", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<Object> logout(HttpServletRequest request) {
String clientId = request.getParameter(OAuth2Constants.CLIENT_ID);
String token = request.getParameter(OAuth2Constants.TOKEN);
String tokenTypeHint = request.getParameter(OAuth2Constants.TOKEN_TYPE_HINT);
String companyId = request.getParameter(WebConstants.COMPANY_ID_PARAMETER);
}
But unfortunately all params receives in the controller as null.
Can someone help me?
Finally I found a solution for the issue. Simply set the data serializer for http request as follows before doing the post call.
this.nativeHttp.setDataSerializer( "urlencoded" );
Situation:
I have a jsp within a jsp. I load another jsp into a div of the outer jsp using .html(). I want to redirect my url into an entirely new url mapping from a controller.
Sample controller:
#RequestMapping(value = { "/main/submit" }, method = RequestMethod.POST)
public String main(ModelMap model) {
System.out.println("In controller");
return "redirect:/anotherJSP";
}
#RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST)
public String anotherJSP(ModelMap model) {
System.out.println("In another");
return "anotherJSP";
}
Jsp within a jsp:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
},
error : function() {
alert("Error.");
}
});
Now, the problem is that the outer jsp stays, and the /anotherJSP url only gets loaded in the innerJSP. I wanted to leave the two jsps and go to the new request mapping URL. Is there anyway I can do it? Thanks a lot in advance!
You can't redirect a POST.
When you return redirect:/anotherJSP, the server sends a redirect instruction back to the web browser, and the browser then sends a new GET request for the given URL.
The GET request will be for the URL given, with any query parameters. This means that and POST payload (data) will be lost.
Change #RequestMapping(value = { "/anotherJSP" }, method = RequestMethod.POST) to #GetMapping("/anotherJSP") (assuming Spring 4.3 or later).
Since an ajax call is asynchronous the effect of return "redirect:/anotherJSP"; is not affecting the browser window, instead you should use window.location.href in your ajax call like this:
$.ajax({
type : "POST",
url : "/main/submit",
success : function(msg) {
console.log('redirect');
window.location.href = /anotherJSP;
},
error : function() {
alert("Error.");
}
});
i am attempting to call Spring controller method from JQuery ajax call, but its not navigate to corresponding view.
First i am verifying login details by calling authenticateLogin() Spring controller function from ajax call, after successful validate i need to forward the request to corresponding view page, i have tried with below code but its not navigate to another page.
Javascript function:
function authenticatePricingCalcLogin() {
var login = {
userName : $("#username").val(),
password : $("#password").val()
};
$.ajax({type: "POST",
url: CONTEXT_PATH+"authenticateLogin",
data:JSON.stringify(login),
contentType : 'application/json; charset=utf-8',
dataType : 'json',
success: function (response) {
if (response != null) {
if (response.errorMsg != null && response.errorMsg != "") { // Login Error
alert(response.errorMsg);
} else {
// Here i need to call spring controller method and to redirect to another page
// I have tried
$.ajax({type: "GET",
url: CONTEXT_PATH+"navigateMainPage",
data:JSON.stringify(loginDO),
contentType : 'application/json; charset=utf-8',
dataType : 'json'
});
}
}
}
});
}
AuthController.java
#RequestMapping(value = "/authenticateLogin", method = RequestMethod.POST)
public #ResponseBody LoginDO authenticateLogin(#RequestBody Login login){
return authService.authenticateLogin(loginDO);
}
#RequestMapping(value = "/navigateMainPage", method = RequestMethod.GET)
public String navigateMainPage(#ModelAttribute("loginDO") Login login,HttpServletRequest request, Model model) {
try {
// Need to set User Name in session variable
} catch (Exception e) {
}
return "auth/mainPage";
}
Please add / in your path
url: CONTEXT_PATH+"/authenticateLogin",
Hi friend I don't have Comment authority so just answering your question.just comment data part if it is GET Type request and remove it form java side #ModelAttribute("loginDO") Login login, Otherwise just make it POST and check any CSRF token is there or not for safe side.
I am using Jquerys Ajax method to talk to my web service. The code seems OK, but I just monitored HTTP traffic using HTTPFox firefox plugin and I noticed unexpected results. To begin with, I am setting the ContentType as application/json and my web service is also producing JSON data but HTTPFox indicates Content Type for my HTTP requests as application/vnd.sun.wadl+xml (NS_ERROR_DOM_BAD_URI).
The Request Method is GET as set in my Ajax request, but HTTPFox indicates my Request method as OPTIONS. And while the Request succeeds and data is returned, the onSuccess method of my Ajax request is not called. Instead, the onError method is called. HTTP Fox is able to capture the data from my web service as response. See the image for HTTP Fox.
Finally, all other request from other processes in my browser seem OK but my HTTP requests are flagged 'RED' by HTTP Fox. The request from other pages and processes seem OK.( GREEN or WHITE).
I have attached screenshot of HTTPFox highlighted on one of my Request. The flagged ones are also from my application.
Image:
I have also pasted the Ajax code I am using to make the HTTP Requests.
window.onload = function() {
var seq_no = getParameterByName("seq_no");
var mileage = getParameterByName("mileage");
document.getElementById("seq_no").value = seq_no;
document.getElementById("mileage").value = mileage;
var param = 'vehReg='+encodeURIComponent(document.getElementById('vehReg').value);
// alert(param);
loadVehicleInfo(param);
};
function loadVehicleInfo(params) {
$("#message").html('<p><font color="green">Loading...</font></p>');
$.ajax({
type: "GET",
url: "http://localhost:8080/stockcloud/rest/vehicles/info",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function(data,status) {
$("#message").empty();
$("#message").html('<p>'+getAsUriParameters(data)+'</p>');
},
error :
function(XMLHttpRequest, textStatus, errorThrown) {
$("#message").html("<p> <font color='red'>The following error occurred: " +textStatus+ ': '+errorThrown+ "</font>");
}
});
};
function getAsUriParameters (data) {
return Object.keys(data).map(function (k) {
if (_.isArray(data[k])) {
var keyE = encodeURIComponent(k + '[]');
return data[k].map(function (subData) {
return keyE + '=' + encodeURIComponent(subData);
}).join('&');
} else {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
}).join('&');
};
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Server side Code for the request:
#Path("/vehicles")
public class VehiclesService {
#GET
#Path("info")
#Produces("application/json")
public Response getVehicleInfo(#DefaultValue("__DEFAULT__") #QueryParam("vehReg") String vehReg) {
// Send SOAP Message to SOAP Server
ServerResponse resp = new ServerResponse();
if("__DEFAULT__".equals(vehReg)) {
resp.setError("Vehicle registration must be supplied as a query parameter: ?vehReg=<THE REG NO>");
resp.setResult(false);
Response.status(Response.Status.BAD_REQUEST).entity(resp).build();
}
try {
// actual code to return the car info and return XML string with the info.
connection.disconnect();
String xml = URLDecoder.decode(s.toString(),"UTF-8");
xml = xml.replace("<", "<").replace(">", ">").replace("<?xml version='1.0' standalone='yes' ?>", "");
System.out.println(xml);
resp.setVehicle(new VehicleParse().parse(xml));
resp.setResult(true);
} catch(Exception e) {
resp.setResult(false);
resp.setError(e.getMessage());
e.printStackTrace();
Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(resp).build();
}
return Response.status(Response.Status.OK).entity(resp).build();
}
}
Is there something I am not doing right?
Thanks.
I'm having a problem with Spring MVC and Ajax. I'm trying to send a javascript list to my Spring Controller, but I can't. I've to do a search and I need to send a list with some parameters.
You will have to convert to the list to json if you sending via ajax, this From the spring blog itself :
$("#account").submit(function() {
var account = $(this).serializeObject();
$.postJSON("account", account, function(data) {
$("#assignedId").val(data.id);
showPopup();
});
return false;
});
#RequestMapping(method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> create(#RequestBody Account account, HttpServletResponse response) {
Set<ConstraintViolation<Account>> failures = validator.validate(account);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
accounts.put(account.assignId(), account);
return Collections.singletonMap("id", account.getId());
}
}
You have to convert your list to JSON String , before using it as an AJAX parameter
This answer in SO might help
jquery ajax on client side
$.ajax({
type: "POST",
url: "submit",
data:JSON.stringify(detailsArr),
success: function(html){
alert( "Submitted");
}
});
and on server side
#RequestMapping(value = "/search", method=RequestMethod.POST)
public String yourMethod(#RequestBody String body){
//convert body to array using JSONLib, FlexJSON or Gson
}