DTO for Spring and AnjularJS - angularjs

I wand to process the request from AngularJS. So I have DTO-class:
public class LoginDTO {
private String login;
private RoleEnum role;
//setters and getters
}
Controller on backend:
#Controller
#RequestMapping("/EmployeeService/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET, value = "/userInfo")
#ResponseBody
public LoginDTO currentUserInfo(){
LoginDTO loginDTO = new LoginDTO(RoleEnum.ROLE_ADMIN, "test");
return loginDTO;
}
}
And controller on frontend:
app.controller("test", function($scope, $http){
var response = $http({
method: "get",
url: "/EmployeeService/user/userInfo"
});
response.success(function (data) {
alert("ok");
});
response.error(function(data){
alert("failed");
});
});
And at the frontend I see failed. If I change controller on backend:
#Controller
#RequestMapping("/EmployeeService/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET, value = "/userInfo")
#ResponseBody
public String currentUserInfo(){
return "test";
}
}
I see OK. How to use DTO class?
On brawser error the server responded with a status of 406 (Not Acceptable)
and
The resource identified by this request is only capable of generating responses with
characteristics not acceptable according to the request "accept" headers.

Let's add:
app.controller("test", function($scope, $http){
var response = $http({
method: "get",
url: "/EmployeeService/user/userInfo",
<!--ADD--!>
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json'
<!--END--!>
});
response.success(function (data) {
alert("ok");
});
response.error(function(data){
alert("failed");
});
});

Related

How to fix the issue-No action was found on the controller that matches the name on sending JSON object to ASP.NET WebAPI from AngularJS

I need to pass data entered in AngularJS front end to webAPI and retrieve another set of data to populate on a grid. I am trying to pass data as JSON object to webAPI method. In WebAPI method, the parameter I am passing for the JSON object as a Class object.
I am not able to enter to the particular webAPI method when I am using [HTTPPost] and getting error as-No action was found on the controller that matches the request.
But I am able to enter to other webAPI methods having [HTTPGet].
Can someone please advise how to fix the issue.Thanks !
WebAPI
using System.Web.Http;
using AttributeRouting.Web.Http;
namespace webAPITestProject.Controllers
{
[Route("api/Values")]
public class ValuesController : ApiController
{
retrieveEmployeeData empData = new retrieveEmployeeData();
retrieveProductDetails prodDetls = new retrieveProductDetails();
[Route("PostEmployeeData")]
[HttpPost]
public DataTable PostEmployeeData([FromBody] Employer empDetails)
{
DataTable dataTable = new DataTable { TableName = "MyTableName" };
dataTable = empData.getEmployeeData(empDetails);
return dataTable;
}
}
}
AngularJS-Controller
angular.module('Test.Employer')
.controller('EmployerController', ['$scope','headerValue', '$http',
function ($scope, headerValue, $http) {
var ipEmployerDetls = {
EmployerName: "cherokee",
Company: "ABC"
};
$http({
url: 'http://localhost:53583/api/Values/PostEmployeeData?empDetails='+'"'+JSON.stringify(ipEmployerDetls)+'"',
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
})();
Employer class
public class Employer
{
public string Company{get;set;}
public string EmployerName{get;set;}
}
you are POSTing data to an endpoint, you don't need to add anything in the URL.
$http({
url: 'http://localhost:53583/api/Values/PostEmployeeData',
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
I have cleaned up your call, the data you provide is sent in the body of the message and your controller expects it there as indicated by the [FromBody] tag

Pass Json data from angular JS to spring REST API and handling it

I'm learning AngularJS and Spring MVC. I'm stuck in a situation where I have an angularjs controller from which I do a REST API call to a spring service. I would like to know how to accept those JSON values inside the controller and map to the Model (getters and setters).
I'm doing some validations on the spring side before doing an insert in the database. I would also like to know how to return those error messages to angula JS and populate them on the screen.
This is my AngularJS controller:
var myapp = angular.module("app");
myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
$scope.addconfig = function() {
var dataobj = {
escfirstname : $scope.escfirstname ,esclastname:$scope.esclastname,escage:$scope.escage
}
$http({
url: "http://localhost:8080/services/AddConfig",
method: "POST",
data: dataobj,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
}
});
This is my Spring service:
#Controller
public class TestController {
#RequestMapping(value = "/AddConfig", method = RequestMethod.POST)
public #ResponseBody String PostService(#RequestBody Config person) {
System.out.println("came insidee");
return null;
}
}
I'm able to print the sysout. Now I would like to know how to proceed with this.
enter link description here
like this.
var myapp = angular.module("app");
myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
$scope.addconfig = function() {
var dataObject = {
escfirstname : $scope.escfirstname,
esclastname : $scope.esclastname,
escage : $scope.escage
};
$http({
method: 'POST',
url: 'http://localhost/jsonURL',
data: dataObject,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}).success(function(data, status, headers, config) {
if( data ) {
}
else {
}
}).error(function(data, status, headers, config) {
console.log(status);
});
}
});
#Controller
public class TestController {
#RequestMapping(value = "/AddConfig", method = RequestMethod.POST)
public #ResponseBody String PostService(#RequestBody Config person) {
// System.out.println("person" + person.);
return null;
}
}

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";
}

Parameters are not getting passed from angular to Web API in the POST call

Below is my angular and Web APi Code.In the post method null is getting passed instead of India
Angular Code:
HWApp.controller('TestCtrl', function ($scope, $http) {
$scope.SendData = function (Data)
{
$scope.whoo = Data;
console.log(Data);
$http({
url: "api/call/firstCall",
dataType: 'json',
method: 'POST',
data: "India",
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.whoo = response;
})
.error(function (error) {
alert(error);
});
}
}
);
Web Api Controller
public class CallController : ApiController
{
[HttpGet]
public string firstCallGet( )
{
return "Get";
}
[HttpPost]
public string firstCall([FromBody] string a)
{
return a;
}
}
Your data parameter should be JSON object.
data :{country : "India" }
Define a model class to automatically deserialze into.
Public class CountryViewModel{
Public string Country{get; set;}
}
Web Api controller should be as follows
public class CallController : ApiController
{
[HttpPost]
public string FirstCall( CountryViewModel in)
{
return in.Country;
}
}

How to make Spring REST service to accept multipart file data sent by the Angular Controller?

I'm trying to post a file from Angular controller to the backend. But Spring REST controller is receiving null.
JS
myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file", $scope.myFile);
alert("Hi");
$http({
method: 'POST',
url: 'upload',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
console.log('file is ' );
console.dir(data);
})
.error(function(data, status) {
});
}
}]);
Spring-REST Controller
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String upload(#RequestBody MultipartFile file) {
System.out.println(file);
}
I also tried with public #ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) but it's of no use. I have declared multipartResolver in the configuaration file too. Any Idea on this? I'm desperately looking for a solution.
Here is a piece of code that works for me:
Spring-REST Controller
#RequestMapping(value = "/api/users/{id}/image", method = RequestMethod.POST)
#ResponseBody
public boolean uploadUserImage( #PathVariable("id") Long id, #RequestParam("file") MultipartFile file ) {
return userService.saveUserImage(id, file);
}
and on the front-end you could do something like this
Angular Controller
//the image
$scope.uploadme;
$scope.uploadImage = function() {
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.uploadme);
fd.append('file', imgBlob);
$http.post(
'/upload',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function(response) {
console.log('success', response);
})
.error(function(response) {
console.log('error', response);
});
}
//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
Assuming that the http request is correct the problem must be at the Spring controller. I think you have to change upload(#RequestBody MultipartFile file) to upload(#RequestParam("file") MultipartFile file). So it will be like this:
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseBody
public void upload(#RequestParam("file") MultipartFile file) {
System.out.println(file);
}
Also in your function you have it return String but you are not returning one. So i assume you are doing something else and you removed the code in order to post the question and missed the return, otherwise it wouldn't even build.
Lastly you could check this answer that i gave to a similar problem.

Resources