1

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.

黄伟杰
  • 27
  • 1
  • 12
  • I find the same question in here .but i doesn't work http://stackoverflow.com/questions/11442632/how-can-i-post-data-as-form-data-instead-of-a-request-payload?rq=1 – 黄伟杰 Jul 31 '16 at 15:48
  • It can send message to the webservice,but Controller can't get the parameter ,but headers: { 'Content-Type': 'application/x-www-form-urlencoded' },can help me to send POST request – 黄伟杰 Jul 31 '16 at 16:00

2 Answers2

0

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;
}
Oleg Kurbatov
  • 1,376
  • 1
  • 19
  • 32
0
<!--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";
   }
elekson
  • 1
  • 1