Not able to get AngularJs fileData from HttpServletRequest at server side - angularjs

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.
});
}

Related

file not binding to angularjs service using FormData

I am trying to upload a file using angularjs and spring 3, I have written a service which is not binding the selected file. I don't know what mistake I have been doing, please help me to solve this problem. I am using commonsmultipart for uploading the files. following are the fileUploadService and controller codes.
MyApp.service('fileUploadService', function ($http, $q) {
this.uploadFileToUrl = function (file, uploadUrl, formData) {
//FormData, object of key/value pair for form fields and values
var fileFormData = new FormData();
fileFormData.append('fileUpload', file);
// console.log(formData);
fileFormData.append('name', formData.name);
fileFormData.append('email', formData.email);
fileFormData.append('password', formData.password);
fileFormData.append('mobile_no', formData.mobile_no);
fileFormData.append('register-submit', 'Register Now');
var deffered = $q.defer();
$http.post(uploadUrl, fileFormData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (response) {
deffered.resolve(response);
}).error(function (response) {
deffered.reject(response);
});
return deffered.promise;
}
});
Spring Controller:
#SuppressWarnings({ "unused", "static-access" })
#RequestMapping( value="/RegisterCandidate" , method = RequestMethod.POST)
private String RegisterCandidate(HttpServletRequest request,
HttpServletResponse response,
#RequestParam CommonsMultipartFile[] fileUpload ) throws Exception{
System.out.println("In method");
String email = request.getParameter("email");
System.out.println("email==============="+email);
String Password = request.getParameter("password");
String usr_name = request.getParameter("name");
String mobile_no = request.getParameter("mobile_no");
Date dateentry = new Date();
java.sql.Timestamp entry_date = new Timestamp(dateentry.getTime());
Users_Pojo usr = new Users_Pojo();
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
usr.setFilename(aFile.getOriginalFilename());
usr.setFile_data(aFile.getBytes());
System.out.println("aFile.getBytes()======"+aFile.getBytes());
System.out.println("aFile.getInputStream()======"+aFile.getInputStream());
System.out.println("aFile.getStorageDescription()======"+aFile.getStorageDescription());
System.out.println("aFile.getSize();======"+aFile.getSize());
System.out.println("aFile.getContentType();==="+aFile.getContentType());/* */
}
}
MD5CodeGenerator md5 = new MD5CodeGenerator();
usr.setUc_password(md5.convertToMD5(Password));
usr.setUc_name(email);
usr.setUc_contact_person(email);
usr.setUc_phone_no(BigInteger.valueOf(Long.parseLong(mobile_no)));
usr.setUc_email_id(email);
usr.setUc_type_id(1);
usr.setUc_active(1);
usr.setValid_from(null);
usr.setValid_to(null);
usr.setDesignation("jobseekar");
usr.setIp_address("164.100.19.79");
usr.setUser_location(1);
usr.setEntry_date(entry_date);
scm_service.save(usr, email);
return "success";
}

Bad request response 400 on ajax call spring controller

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()...");

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

callback data from servicenot returning back to controller angularjs

find my below code for delete function its deleting in backend and returning success message to service from that not returning to controller ,so was unable to print growl message.
This is my controller side code:
$scope.deleteBlogswithid = function(id) {
var loggedInUserId = $rootScope.loggedInUser.id;
if ($rootScope.loggedInUser != null) {
blogService.deleteBlog(id, loggedInUserId,function(data) {
if(data == 'success'){
$location.path("/home");
$growl.box('Blog has been deleted', {
class : 'danger',
sticky : false,
timeout : 5000
}).open();
}
})
} else {
$growl.box('Please login to delete the blog', {
class : 'danger',
sticky : false,
timeout : 5000
}).open();
}
}
service.js:
blogbeatsApp.service('blogService', function(httpService) {
this.deleteBlog = function(id,loggedInUserId,data, callback) {
var url = 'blog/delete/' +id + "/" + loggedInUserId;
httpService.postRequest(url,data, callback);
};
});
httpService.js:this is my httpservice
blogbeatsApp.service('httpService', function($http, $location, $rootScope){
this.postRequest = function(url, data, contentType, callback){
$http({
method : 'POST',
url : url,
data : data,
headers : {
'Content-Type' : contentType
}
}).success(function(data) {
callback(data);
}).error(function(data, status, headers, config) {
});
};
i am not getting success message to controller in function(data).please help
As I say in comments.
You does not pass parameter in correct order.
your callback is 3rd parameter of postRequest. Which is bind with function(url, data, contentType, callback) - contentType.
Since, its your 3rd parameter use this in your httpService as this.postRequest = function(url, data,callback, contentType)
callback must be 3rd parameter
change httpSerivce :
blogbeatsApp.service('httpService', function($http, $location, $rootScope){
this.postRequest = function(url, data, contentType, callback){
$http({
method : 'POST',
url : url,
data : data,
headers : {
'Content-Type' : contentType
}
}).success(function(data) {
callback(data);
}).error(function(data, status, headers, config) {
});
};
To :
blogbeatsApp.service('httpService', function($http, $location, $rootScope){
this.postRequest = function(url, data, callback, contentType){
// callback should be as 3rd parameter.
$http({
method : 'POST',
url : url,
data : data,
headers : {
'Content-Type' : contentType
}
}).success(function(data) {
callback(data);
}).error(function(data, status, headers, config) {
});
};

Post Data to WebApi from AngularJS

i want to Post a User to WebApi
Ive written this Controller :
public class AccountController : ApiController
{
public UserModel Get([FromUri]string username, [FromUri]string password)
{
var repository = new MongoRepository<User>();
User result = repository.Single(x => x.Username == username && x.Password == password);
UserModel user = result.ToUserModel();
if (result != null)
{
result.LastLogin = DateTime.Now;
user.LastLogin = DateTime.Now;
repository.Update(result);
}
return user;
}
public GenericResultModel Post(User user)
{
var repository = new MongoRepository<User>();
var existingUser = repository.Single(x => x.Username == user.Username || x.EmailAdress == user.EmailAdress);
if (existingUser == null)
{
if (repository.Add(user) != null)
{
return new GenericResultModel{Success = true, Errors = new List<string>()};
}
return new GenericResultModel(){Success = false, Errors = new List<string>(){"There was an Error adding the User !"}};
}
return new GenericResultModel(){Errors = new List<string>(){"The User already exists !"}, Success = false};
}
}
My RouteConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
And my AngularJS Controller
mod.controller('accountCtrl', function ($scope, $http, $window, $location) {
$scope.credentials = { username: '', password: '' };
$scope.Login = function () {
$http({
method: 'GET',
url: 'http://localhost:9239/Api/Account/Get?username=' + $scope.credentials.username + '&password=' + $scope.credentials.password,
/* data: JSON.stringify(credentials), */
headers: { 'Content-Type': 'application/json; charset=utf-8', 'dataType': 'json' }
}).
success(function (data, status, headers, config) {
$window.sessionStorage.setItem('loginToken', data.Id);
//$location.redirectTo('/Home');
}).
error(function (data, status) {
console.log("Request Failed");
});
};
$scope.registerModel = { username: '', password: '', passwordrepeat: '', email: '', emailrepeat: '' };
$scope.RegisterUser = function () {
$http.post('http://localhost:9239/Account/',$scope.registerModel);
};
});
When i login, everythign works fine.
But when i post a new User i get a 404 Not Found Error.
I tryied the [FromBody] Attribute but it didnt worked
When i debug my Code wont hit by the Service ...
Any Ideas ?
Assuming you didn't make any typos in the api url you POST to, the problem is not in your angular code.
HTTP 404 Not Found
The 404 or Not Found error message is a HTTP standard response code indicating
that the client was able to communicate with the server,
but the server could not find what was requested.
If you had tried to POST a user to http://localhost:9239/Account using, for example, the program curl, you would also have gotten this 404 code.
If you had opened your browser and surfed to http://localhost:9239/Account you would also have gotten this 404 code.
Basically what it means is that the url you are trying to POST to doesn't 'exist'. I've been in this situation myself because I simply typo'd the url. The only other explanation I can think of is that the server is running fine, but there is no implementation for /Account, e.g. calls to that url aren't handled.

Resources