Bad request response 400 on ajax call spring controller - http-status-code-404

Here is my ajax request:
var segmentName = $('#segmentName').val();
if (segmentName.length == 0) {
alert('Segment Name Cannot be empty');
return;
}
var selectedValue = [];
$('#multiselect_to_1 :selected').each(function(i, selected){
selectedValue = $(selected).text();
});
$.ajax({
type : 'POST',
contentType: "application/json",
url : 'saveSegmentScheme.htm',
data :JSON.stringify({
"segmentName" : segmentName,
"selectedValue": selectedValue
}),
success : function(data) {
// alert("Data successfully inserted");
console.log(data);
},
Here is my controller method.
#RequestMapping(value = "/saveSegmentScheme.htm", method = RequestMethod.POST)
public String saveSegmentScheme(#ModelAttribute("analyzerBean") AnalyzerBean analyzerBean, BindingResult result,
#RequestParam("segmentName") String segmentName, #RequestParam("selectedValue") String selectedValue,
HttpServletRequest request, HttpServletResponse response) {
logger.debug("Entered and leaving from saveSegmentScheme()...");

Related

Request Body with Request Param

Can i send http post with also RequestBody and RequestParam??
I want to send some data in that way: data - is requestbody and params is RequestParam.
var Indata = {'cityName': object.cityName };
$http({method: 'POST', url: OBJECT_REST, data: object, params: Indata}).
then(function(response) {
alert("saved");
$rootScope.$broadcast('refreshUserGrid');
$rootScope.$broadcast('clearForm');
}, function(response) {
console.log(response.status);
});
and in PostMapping controller i want to get this data:
#PostMapping(consumes = MediaType.APPLICATION_JSON)
public ResponseEntity<?> saveSportObject(#RequestBody SportObject object, #RequestParam String cityName) {
It's possible to using requestBody with RequestParam in similar way to this one?

Calling method using $http Post in AngularJS

I am trying to call the method ProcessCriteria in AngularJS below but for some reason I am keep getting error message:
VM18010:1 POST http://example.com/api/TalentPool/ProcessCriteria 404
(Not Found)
Below is my Calling code:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: param
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
And my Server side method:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(string Item, string SolrLabel)
{
var itm = Item;
var solr = SolrLabel;
return Ok();
}
Any suggestions please?
ASP.net cannot match your request in its Route Table because you have 2 parameters in your action and the router doesn't understand it.
it expects a data object that your parameters warp to this.
First of all, make a Model like it:
public class Criteria
{
public string Item { get; set; }
public string SolrLabel { get; set; }
}
then change your action:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(Criteria criteria)
{
var itm = criteria.Item;
var solr = criteria.SolrLabel;
return Ok();
}
Update
and update your javaScript part with JSON.stringify:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(param)
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
You can create a class as said by in above answer and you can pass data in http post like this
var obj = {
url: url,
async: true,
method: 'POST',
headers: {
"content-type": "application/json; charset=utf-8",
}
};
if (typeof data != 'undefined' || typeof data != null) {
obj.data = data;
}
$http(obj).then(function(response){
},function(error){
});
I got i working, below is the code for others if they get stuck on it.
var pvarrData = new Array();
pvarrData[0] = JSON.stringify(item.Key);
pvarrData[1] = JSON.stringify(SolrLabel);
pvarrData[2] = JSON.stringify($localStorage.message);
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) {
// failed
console.log('facet post error occured!');
});

Angularjs Post method can not get the parameter in Spring MVC

I'm trying to use Angularjs to send a Post request to My Spring Mvc Controller to login User.But I can't get the Parameter from the request.
this is my Angular js code:
$scope.submit = function () {
$http({
url: serviceURL.LoginUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
phone: $scope.userName,
password: $scope.userPsw,
}
}).success(function (data) {
if (!data.state) {
alert(data.errorMsg);
} else {
alert('success');
}
console.log(data);
}).error(function (data) {
console.log('服务器错误!');
});
}
and this is the Spring MVC Controller code:
#RequestMapping(value = "/login", method = RequestMethod.POST)
#ResponseBody
public Object loginUser(Model model,User user, HttpSession session, HttpServletRequest request) {
String phone = request.getParameter("phone");
String password = request.getParameter("password");
System.out.println(phone+","+password);
System.out.println(user.getPhone()+","+user.getPassword());
UserDTO u = userService.loginUser(phone, password);
session.setAttribute("loginUser",u.getUser());
return u;
}
I have searched many resource,they said I should change the header and I have set the header:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
return true;
}
Actually,I can't request the login url,but after I setHeader,I can request the url,but the parameter is null.
Forgive my poor English, I am newbie in StackOverFlow.
I didn't konw is it have the same question in here ,but I can find the same question. Thank you for your view.
There are two points to fix. At first, data should be converted to a URL-encoded string. You can convert data object with $.param() method or set params property instad of data so it will look like this:
$scope.submit = function () {
$http({
url: serviceURL.LoginUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
phone: $scope.userName,
password: $scope.userPsw,
}
}).success(function (data) {
if (!data.state) {
alert(data.errorMsg);
} else {
alert('success');
}
console.log(data);
}).error(function (data) {
console.log('服务器错误!');
});
}
The second point is server-side controller method. Here you have to annotate method's arguments appropriately. Consider using #RequestParam annotation.
#RequestMapping(value = "/login", method = RequestMethod.POST)
#ResponseBody
public Object loginUser(
#RequestParam String phone,
#RequestParam String password,
HttpSession session,
HttpServletRequest request
) {
System.out.println(phone + ", " + password);
UserDTO u = userService.loginUser(phone, password);
session.setAttribute("loginUser", u.getUser());
return u;
}
<!--In your script-->
var app = angular.module("myApp", [])
.controller("myController", function($http){
var vm= this;
Posting = function(name)
{
var data = 'name=' + name;
var url="example.htm";
$http.post(url, data).then(function (response) {
vm.msg = response.data;
alert(vm.msg);
});
}
});
// Above is same as using GET, but here below is important
//Dont forget to add this config ortherwise http bad request 400 error
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=UTF-8';
}]);
//In spring controller same as of GET Method
#RequestMapping(value="example.htm", method = RequestMethod.POST)
#ModelAttribute("msg")
public String doingPost(#RequestParam(value="name") String name){
System.out.println(name);
return "successfully Posted";
}

Not able to get AngularJs fileData from HttpServletRequest at server side

AngularJS Client Side:
userTab.factory('someService', ['apiService','$rootScope', function(apiService, $rootScope){
return {
updateData : function (someObj){
return apiService.request({
apiMethod: 'user/v1/updateData',
httpMethod: 'POST',
fileData: JSON.stringify(someObj)
}).error(function(data, status) {
throw "updateData error: " + status;
});
}
}
}]);
Server Side Code:
Update.java
#Controller("user")
#RequestMapping(value = "/user/v1")
public interface Update
{
#ResponseBody
#ResponseStatus(HttpStatus.CREATED)
#RequestMapping(value = "/users/{username}/updateData", method = POST)
String updateData(HttpServletRequest request, HttpServletResponse response, #PathVariable("username") String username, #RequestBody UserUpdate userUpdate);
}
UpdateImpl.java
#Override
#Transactional
public String updateData(HttpServletRequest request, HttpServletResponse response, #PathVariable("username") String username,
#RequestBody UserUpdate userUpdate) {
String requestBody = ServletUtils.getRequestBody(request);
logger.info("RequestBody: "+requestBody);
return new String("true");
}
Response:
RequestBody: {}
So as you see that RequestBody is coming as blank as I haven't given anything in params within angularjs API call.
So how to get the fileData which is not in params here?
UPDATE:
My fileData is a normal json array just like this:
{
"todo" : "Dinner",
"user" : [
{
"name" : "username",
"password" : "passwordabc"
}
],
"notes : "some notes"
}
And I have created it in an angularjs as follows:
var object = {};
object.todo = "Dinner";
object.notes = "some notes";
userArray = [{
name: 'myname',
password: 'password'
}];
object.user = userArray
UPDATE:
apiService.js
'use strict';
apiModule.factory('apiService', ['$http', '$q', 'LoginService','XSSValidator', function($http, $q, loginService, XSSValidator) {
var basePath="https://somesite.com/userApi/";
var _httpMethod="POST";
var caching=false;
var latestRequest={};
$http.defaults.withCredentials = true;
return{
if(typeof bundle.fileData != "undefined"){
return $http({
cache: caching,
method: bundle.httpMethod,
headers:{"Content-Type":contentType},
url:basePath+bundle.apiMethod,
data:dataStr,
transformRequest: angular.identity,
transformResponse:bundle.transformResponse,
timeout: canceller.promise
}).success(function(data, status, headers, config) {
//check to see if request has been redirected to login page, suggesting user has been logged out
if(typeof data==='string' && data.substr(0,44)==='<html><head><title>Login Page</title></head>'){
window.location.href="/login" + window.location.search;
}
var req;
if(config.data !== ""){
var requestArr=config.url.split(config.data);
req=requestArr[0].split("?")[0];
}
else{
req=config.url;
}
if(config.data !== "" && !data.fault){
if(Object.prototype.toString.call(data) == "[object String]"){
var msg = XSSValidator.validate("Response ", data);
if (msg != null) {
return $q.reject({ message: msg });
}
}else if(config.headers["Content-Type"] == "application/x-www-form-urlencoded" || config.headers["Content-Type"] == "application/json"){
eval(data);
}
}
if(latestRequest[req]!==config.url){
//cancel promise
return $q.reject({ message: 'Rejecting this promise' });
}
}).error(function(data, status, headers, config) {
if(status===401){ //user has been logged out server-side. redirect to login pg
window.location.href="/login" + window.location.search;
}
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}

Spring Controller is not accepting the file sent by the angular controller

I'm posting some form data to the Spring controller and if it is successful, again I'm posting two files from Angular controller to Spring controller:
$http.post('userdetails', formData).success(function(response) {
if ($scope.items.length > 0) {
for (var i = 0; i < $scope.items.length; i++) {
$scope.uploadItem(response.id, $scope.items[i]);
}
}
});
This is my uploadItem function:
$scope.uploadItem = function(id, file) {
var data = new FormData();
data.append('id', id);
data.append('file', file);
$http.post('multipleSave', data, {
transformRequest: function(data, headersGetterFunction) {
return data;
},
headers: {
'Content-Type': undefined
}
}).success(function(data) {
$log.debug("Upload Successfull");
$log.debug("File upload: Success calling ");
alert(data);
alert("hi");
}).error(function(error) {
$log.debug("Upload failure");
alert(error);
});
};
This is my Spring Controller code
#RequestMapping(value="/multipleSave", method = RequestMethod.POST)
public void UploadFile(MultipartHttpServletRequest request, HttpServletResponse response) {
Iterator<String> itr=request.getFileNames();
MultipartFile file=request.getFile(itr.next());
String fileName=file.getOriginalFilename();
System.out.println(fileName);
}
Content in the MultipartHttpServletRequest request is empty.
You should have encryption type set to multipart/form-data in your request headers.
$http.post('multipleSave', data, {
transformRequest: function(data, headersGetterFunction) {
return data;
},
headers: {
'Content-Type': undefined,
enctype:'multipart/form-data'
}
})

Resources