【问题标题】:How to submit form via POST with Angular 1.5.8 and Java Servlet?如何使用 Angular 1.5.8 和 Java Servlet 通过 POST 提交表单?
【发布时间】:2017-04-21 15:15:50
【问题描述】:

我阅读了一些教程和在线文档,但仍然无法弄清楚。 我想从 jsp 表单中传递一些参数。 这是我的 js 脚本:

var app = angular.module('myApp', []);
app.controller('FormController', FormController);

//add dependecies
FormController.$inject = ['$scope', '$http'];

function FormController($scope, $http) {
    $scope.blob = {};
    $scope.submitForm = function() {
        $http({
            method : 'POST',
            url : '/javaAngularJS',
            data : $scope.blob,
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        });
    };
}

这是我的表格:

<div class="site-body" ng-app="myApp">
    <form ng-controller="FormController" ng-submit="submitForm()">
    <p>Blob Key: <input type='input' name='blob-key' ng-model="blob.key"></p>
    <p>Ancestor: <input type='text' name='ancestor' ng-model="blob.ancestor"></p>
<input type="submit" class="btn btn-primary" value="Submit">
</div>

我的 web.xml 中添加了一个带有 Post 方法的 Servlet 类。我可以将 Angular 和 AJAX 调用与其他东西一起使用,但我坚持这一点。 如何在 Servlet 中正确检索表单参数?例如,我想使用 System.out.prinltn 打印参数。

【问题讨论】:

    标签: javascript java angularjs jsp servlets


    【解决方案1】:

    您可以使用httpParamSerializerJQLike 服务来序列化您的数据。

    (从{key: "asd", ancestor: "asd"}ancestor=asd&amp;key=asd

    FormController.$inject = ['$scope', '$http', '$httpParamSerializerJQLike'];
    
    function FormController($scope, $http, $httpParamSerializerJQLike) {
      $scope.blob = {};
      $scope.submitForm = function() {
        $http({
           method : 'POST',
           url : 'javaAngularJS', // use relative
           data: $httpParamSerializerJQLike($scope.blob),
           headers: {
             'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
           }
         });
       };
    }
    

    所以你可以得到参数:

    String key = request.getParameter("key");
    String ancestor = request.getParameter("ancestor");
    

    如果你想解析 JSON 格式的请求,那么你可以使用 Jackson、Gson 等库将 JSON 输入转换为 Java 对象,反之亦然。

    【讨论】:

      猜你喜欢
      • 2012-09-07
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 2015-02-14
      • 2016-05-25
      • 2012-07-17
      • 2011-10-14
      相关资源
      最近更新 更多