I am trying to send some json data from angular ng grid to spring mvc controller,but i am getting error as 400 (Bad request) The request sent by the client was syntactically incorrect. .
This is my Request Paylod:
[{"orderId":1,"orderTitle":"Xcel","orderDetail":"cash","orderType":"Xcel","orderPriority":"22.0","retailerId":0,"orderRefno":"9.900499743E9","customerName":"high","customerContactno":"pen drive","customerEmailId":"nutral","paymentType":"iffu#gmail.com","orderStatus":"pen drive","reciptDate":null,"bayNumber":"Xcel","deliveredDate":null,"deliveredBy":"Irfan","updatedOn":null,"pudoOutlet":null,"retailer":null,"outletId":0}]
here is my spring mvc controller:
#RequestMapping(value="/createorder",method=RequestMethod.POST,headers="Content-Type=application/json")
public #ResponseBody ModelAndView createOrder(#RequestBody Order order){
System.out.println("hiiiii"+order);
try{
orderDao.createOrder(order);
return new ModelAndView("product1.html");
}
catch(Exception e)
{
System.out.println(e);
}
return new ModelAndView("pr.html");
}
here is my angular controller from where i am posting:
$scope.save = function() {
console.log("hii inside save function");
console.log($scope.mySelections);
console.log("after myselection")
var d=$scope.mySelections;
console.log("hhhhh" +d);
$http({
method: 'POST',
url: './createorder',
headers: {'Content-Type': 'application/json'},
data:d
}).success(function (data)
{
$scope.status=data;
});
};
I am totally confused why i am getting this error ? Is it because i am sending some null values to spring mvc controller ? if yes how to solve this issue ?
Is Order an inner class? If so, try taking that class into its own file. Worked for me.
Related
Angularjs $http.post gives a 404 exception but all the other methods works fine with the same codes, i am trying to upload a file via spring boot
The same codes works fine in my other project i did about last year, and the same $http.post works when i send information without a file
service.js
function addCompanyDoc(file, id) {
var deferred = $q.defer();
var data = new FormData();
data.append('file', file);
var config = {
transformRequest: angular.identity,
transformResponse: angular.identity,
headers: {
'Content-Type': undefined
}
}
console.log('appService file ');
console.dir(file); //cheking if file is available
$http.post('http://localhost:8080/listed/welcome/company/doc/' + id,
data, config)
.then(function(response) {
deferred.resolve(response.data);
},
function(errResponse) {
alert(errResponse.data.errorMessage);
console.error('Error while uploading company doc', errResponse);
this.flag = 'failed';
deferred.reject(errResponse);
});
return deferred.promise;
}
spring boot
#RequestMapping("/welcome")
public class controllers{
#RequestMapping(value = "/company/doc/{id}", method =
RequestMethod.POST, consumes = {"multipart/form-data" })
#ResponseBody
public ResponseEntity<Void> saveCompanyDoc(#RequestParam("file")
MultipartFile file, #PathVariable final int id){
//....uploading to DB
}
}
angularjs sends a document to spring boot and spring uploads to the DB / sends to a folder.
Working fine :-) with angularjs 1.7 & spring boot 2.*
Thanks for all the comments the above code is correct,
I created a dummy table and controller to test the app.
And it gave the same 404 error and i recalled a few weeks back i added an "admin folder" to handle CMS and directed all the ROLES to the "folder" and it blocked all the users from doing data POSTING. SO i just had to fix my WebSecurityConfig class :-)
I´m trying user $http post in angular, where the rest service receive an object. The data is a Json where I need pass with parameter for method in service.
My angular code (it´s doesn´t work for me):
$http({
method:'POST',
url:request.url,
data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
If I comment the row data, the comunication with service it´s ok:
$http({
method:'POST',
url:request.url,
//data: JSON.stringify(objcsr);
headers: {'Content-Type':'application/json; charset=utf-8'}
}).then(function(objS){
alert('Success :- '+JSON.stringify(objS));
},function(objE){
debugger;
alert('error:- '+JSON.stringify(objE));
});
My method in service:
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}
I hope the object you are passing in data parameter is same as AuthenticationDTO class, its properties must be same. If that is fine then try running this.
$http.post('url',JSON.stringify(data),{headers: {'Content-Type':'application/json'}})
.success(function (data) {
alert('Success :- '+JSON.stringify(data));
});
As well I am assuming that you have included [HttpPost] attribute before your method. like this:
[HttpPost]
public UserAccessDTO Authenticate(AuthenticationDTO authentication)
{
.....
}
I am new to angularjs. I am trying to post a request from angularjs to spring controller. The request object is logged properly in angular but it reaches as null in controller.
I have been through the similar questions but they didn't worked out for me :
getting null using angular post
angularjs-spring-mvc-json-post-request
spring-angularjs-receiving-null-data-on-server
Controller.js :
$scope.addExpense = function (expense) {
console.log("Received"+expense.amount+expense.description);
var expenseDetail = {
description:expense.description,
amount:expense.amount,
created:'',
updated:'',
};
console.log("expense detail : "+JSON.stringify(expenseDetail));
$http({
method : 'POST',
dataType: 'json',
url : 'addExpense1',
data : JSON.stringify(expenseDetail),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
console.log(response.data);
}).error(function(response){
console.log("Error : "+response.data);
});
};
Controller method :
#RequestMapping(value = "addExpense1", method = RequestMethod.POST)
#ResponseBody
public List<ExpenseDetail> addExpense1(#RequestBody ExpenseDetailDTO expenseDetailDTO) {
LOG.info("Request to add description : " + expenseDetailDTO.getDescription());
if(expenseDetailDTO==null || expenseDetailDTO.getDescription()==null || expenseDetailDTO.getAmount()==null)
return null;
expenseService.addExpense(expenseDetailDTO);
List<ExpenseDetail> expenseDetails = expenseService.getAllForToday();
LOG.info("Expense Details fetched : " + expenseDetails.size());
return expenseDetails;
}
On controller following log is printed :
Request to add description : null
I am not getting error anywhere.
Kindly help me out.
i had similar issue in the past using spring webmvc.
https://github.com/sombriks/rango-vote-spring/blob/master/src/main/java/rango/vote/RangoVoteController.java
What solved in my case was the addition of jackson-databind dependency and the proper configuration:
https://github.com/sombriks/rango-vote-spring/blob/master/build.gradle#L54
https://github.com/sombriks/rango-vote-spring/blob/master/src/main/webapp/WEB-INF/applicationContext.xml#L29
If possible, prefer spring + jersey over spring webmvc since you could use jaxb to properly map your data objects:
http://pastebin.com/TVsrJJm7
http://pastebin.com/jE7z1u3k
http://pastebin.com/39QDBgQD
Hope it helps
How do i post a list of objects from javascript to Spring MVC Controller? I can post arrays, objects, but not a combination of the 2. This is my code below.
Javascript:
var utilData = getTableData();
// Sending data over to server
console.log(utilData);
$.ajax({
url: "saveUtilData2.html",
type: "POST",
contentType: "application/json",
dataType: "json",
data: {utilArray: utilData},
success: function(data){
alert("save was sucessful");
},
error: function(){
alert("Save wasn't successful");
}
});
Spring Controller (tried changing utilData to String[] and object[] ... both didnt work:
#RequestMapping(value="/saveUtilData2.html", method=RequestMethod.POST)
public ModelAndView saveUtilData2(#RequestParam("utilArray") String[] utilData, HttpServletRequest request)
{
System.out.println("Util Save Data method 2");
ModelAndView mv = new ModelAndView("util");
return mv;
}
Use #Requestbody instead of Requestparam
I am trying to send data from angular js to server.. Laravel5 is running on my server.. I can fetch data using this but can not send data.. My code is bellow
AngularJs Code:
var request = $http({
method: "get",
url: "http://www.myserver.com/json",
data: { email: $scope.email },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
request.success(function (data) {
alert(data.email);
});
Server code :
route is Route::get('json','JsonController#Json_login');
Controller code is
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Input;
class JsonController extends Controller
{
public function Json_login()
{
$email = Input::get('email');
$arr_Id_Status=array('email'=>$email);
echo json_encode($arr_Id_Status);
}
}
But it giving me null alert
Sounds like you should be using a POST rather than a GET request. You would need to create an appropriate POST route on your server but it's pretty much the same syntax on the client side, just change GET to POST.
var request = $http({
method: "POST",
url: "http://www.saadetera.com/json",
data: { email: $scope.email },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function (data) {
alert(data.email);
});
Not used Laravel for a while but it would be something like:
Route::post('json','JsonController#handleLoginRequest');
Ideally, sending data will require a POST method while fetching will be using a GET method. Let's make the complete flow assuming you want to call a controller called your_controller and use its your_method function :
This suits for Laravel 5
Laravel Controller :
use Illuminate\Http\Request;
public function your_method(Request $request)
{
$data = $request->input(my_data);
//Server side data processing here
//Returning Json or anything else here
return response()->json(your_answer_here);
}
Route :
Route::post('your_url', ['uses' => 'your_controller#your_method']);
AngularJS : Here is the chunk of code allowing data sending, it requires $http service. Let's assume your data is contained in the my_data object.
$http.post('your_url', my_data)
.then(you_callback_success, your_callback_fail);