从servlet中的angularjs获取参数

时间:2017-02-08 18:17:06

标签: java angularjs servlets

mainController

    $scope.strings = {
    str1 : null,
    str2 : null,
    str3 : null
};
$scope.strings.str1 = "str1";
$scope.strings.str2 = "str2";
$scope.strings.str3 = "str3";


$scope.login = function() {
    var xmlHttpReq = new XMLHttpRequest();
    xmlHttpReq.open('POST', "http://localhost:8080/WEB-war/FES", false);
    xmlHttpReq.setRequestHeader('Content-Type', 'application/json');

    xmlHttpReq.send(JSON.stringify($scope.strings));
    if (xmlHttpReq.status === 200) {
        console.log("From controller: " + xmlHttpReq.responseText)
    }

}

的servlet

 protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        System.out.println("inside do POST");
        Object obj = request.getAttribute("what to write here?");

 }

我需要从angularjs

访问scope.strings

我在控制器中发送了这个代码我相信>

xmlHttpReq.send(JSON.stringify($scope.strings));

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您应该开始使用角度的$http模块。

var url = "http://localhost:8080/WEB-war/FES";
var data = $scope.strings;

$http.post(url, data)
   .then(
       function(response){
         // success callback
       }, 
       function(response){
         // failure callback
       }
    );

Servlet应该具有类似

的东西
// example using the javax.json.stream package
JsonParser parser = Json.createParserFactory().createParser(request.getReader());

另见Angular http POST to Servlet