【问题标题】:How to get the data in Struts 1 from AngularJS POST如何从 AngularJS POST 获取 Struts 1 中的数据
【发布时间】:2014-04-05 14:06:00
【问题描述】:

我正在使用 Struts1.2 和 AngularJS 来 POST 一些数据,并希望在 Java 中获取数据。

我能够从服务器检索数据并将其显示在屏幕上。

现在我正在尝试使用 AngularJS 将一些数据发布到服务器,并尝试使用 Java 中的request.getParameter() 获取数据。我试了三遍,还是不行。

下面我还提供了以下文件,以及我的三个尝试的解释和屏幕截图。

CartController.js:

var myApp = angular.module('cartApp',[]);

myApp.controller('CartController', function ($scope,$http) {

    $scope.bill = {};
   
    $scope.items = [];
    
    $http.post('/StrutsWithAngular/shopingCart.do')
        .success(function(data, status, headers, config) {
            
            $scope.items = data;
         })
        .error(function(data, status, headers, config) {
            //alert("Error :: "+data);
        });
    
    // First Try
    
    $scope.postData = function() {
        
         $http({
              method: 'POST',
              url: '/StrutsWithAngular/shopingCart.do',
              data: 'value=' + 'Parameter From Request' ,
              headers: {'Content-Type': 'application/x-www-form-urlencoded'}
           }).success(function(data, status, headers, config) {
            
            alert("Success :: "+status);
            
            $scope.items = data;
           }).error(function(data, status, headers, config) {
            
            alert("Error :: "+data);
           });
    };
    
    

// Second Try



$scope.postData = function() {
        
         $http({
              method: 'POST',
              url: '/StrutsWithAngular/shopingCart.do',
              data: 'cartValues=' + {cartValues : $scope.items} ,
              headers: {'Content-Type': 'application/x-www-form-urlencoded'}
           }).success(function(data, status, headers, config) {
                $scope.items = data;
           }).error(function(data, status, headers, config) {
            // alert("Error :: "+data);
           });
    };
    
// Third try
    
    $scope.postData = function() {
        
         $http({
              method: 'POST',
              url: '/StrutsWithAngular/shopingCart.do',
              data: $scope.items
           }).success(function(data, status, headers, config) {
                $scope.items = data;
           }).error(function(data, status, headers, config) {
            // alert("Error :: "+data);
           });
    };
        
});

CartAction.java:

package com.myapp.action;

import com.myapp.dto.ShopingCartDto;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CartAction extends org.apache.struts.action.Action {


    private static final String SUCCESS = "success";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        System.out.print("Cart App");
        
        String value = request.getParameter("value");
        System.out.print("value ::"+ value);
        
        String requestValue = request.getParameter("cartValues");        
        System.out.print("Requested Values ::"+ requestValue);
        
        if(requestValue!=null){
            
            System.out.println("Requested Values :: "+requestValue);

            JSONObject object = JSONObject.fromObject(requestValue);
            System.out.println("Object Keys ::" +object.keys());        
            Iterator iter = object.keys();
            System.out.println("Iter :: "+iter.toString());

            while (iter.hasNext()) 
            {
                    String key = (String) iter.next();
                    System.out.println("Keys " + key);
                    JSONArray array = object.getJSONArray(key);
                    for (int i = 0; i < array.size(); i++) {
                            JSONObject powertrainOperationJSON = JSONObject.fromObject(array.get(i));

                    }
           }            
           
         }

        
        List<Object> shopingCartDtos = new ArrayList<>();        
        
        ShopingCartDto shopingCartDtoOne = new ShopingCartDto();
        ShopingCartDto shopingCartDtoTwo = new ShopingCartDto();
        ShopingCartDto shopingCartDtoThree = new ShopingCartDto();
        
        shopingCartDtoOne.setSno(1);
        shopingCartDtoOne.setTitle("Title 1");
        shopingCartDtoOne.setQuantity("11");
        shopingCartDtoOne.setPrice("25");
        
        shopingCartDtoTwo.setSno(2);
        shopingCartDtoTwo.setTitle("Title 2");
        shopingCartDtoTwo.setQuantity("12");
        shopingCartDtoTwo.setPrice("25");
        
        shopingCartDtoThree.setSno(3);
        shopingCartDtoThree.setTitle("Title 3");
        shopingCartDtoThree.setQuantity("13");
        shopingCartDtoThree.setPrice("25");
                
        shopingCartDtos.add(shopingCartDtoOne);
        shopingCartDtos.add(shopingCartDtoTwo);
        shopingCartDtos.add(shopingCartDtoThree);
        
        ajaxResponse(response, shopingCartDtos);
                
        return null;              
        
    }

}

第一次尝试:当我尝试在请求中使用单个参数时,我能够在 Java 中获取值

在控制器中:

data: 'value=' + 'Parameter From Request' 

在 Java 中:

String value = request.getParameter("value");
 System.out.print("value ::"+ value);

参数值:

控制台输出:

第二次尝试:

现在,当我尝试在 java 中获取一些值时,我无法获得,在这种情况下,我在参数 cartValues 中传递了内容类型为 application/x-www-form-urlencoded 的 $scope.item。在 Java 中,当尝试从request.getParameter(“cartValues”) 获取值时,该值将打印为[object Object],如请求中所示。但是当尝试在 Java 中使用 JSON API 解析值时出现异常

在控制器中:

data: 'cartValues=' + {cartValues : $scope.items} ,
                              headers: {'Content-Type': 'application/x-www-form-urlencoded'}

在 Java 中:

   String requestValue = request.getParameter("cartValues");        
   System.out.print("Requested Values ::"+ requestValue);

我第二次尝试的屏幕截图:

第三次尝试:

在这种情况下,我只传递了 $scope.item 并删除了内容类型以将其作为 JSON 传递,但我不清楚如何在 Java 中获取值

在控制器中:

data: $scope.items

第三次尝试的截图:

【问题讨论】:

  • 有人可以帮我解决上述问题,因为它非常紧急
  • 等待您关于问题的博文!

标签: java angularjs json struts-1


【解决方案1】:

使用第二次尝试,在发布数据之前将 scope 转换为 JSON。

这可以通过 JSON API 或 AngularJS API 两种方式完成

我使用了angular.toJson(),也使用了转义方法来接受特殊字符。

使用request.getParameter() 可以获得服务器端的值。希望解决方案对大家有所帮助。

第二次尝试:

$scope.postData = function() {

     var data = escape(angular.toJson($scope.items));

     $http({
          method: 'POST',
          url: '/StrutsWithAngular/shopingCart.do',
          data: 'cartValues='+data,
          headers: {'Content-Type': 'application/x-www-form-urlencoded'}
       }).success(function(data, status, headers, config) {
            $scope.items = data;
       }).error(function(data, status, headers, config) {
        // alert("Error :: "+data);
       });
};

【讨论】:

    【解决方案2】:

    Angular 不会 POST 表单数据,它会将 JSON 对象传输到服务器。有关 JSON 本身的信息,请参阅JSON.org。该页面(靠近底部)还列出了大量库,可让您解析各种语言(包括 Java)的 JSON。作为一名 Java 开发人员,我不能说其中一个比另一个更好,但是您应该能够通过阅读每个文档的文档来很好地了解适用性。

    【讨论】:

    • 我正在使用 JSON api 来获取我遇到问题的数据,只有当我们使用内容类型 application/x-www-form-urlencoded 我们才能获取数据在服务器端。在我的第一次尝试中,您可以看到我能够获取我发布的数据。在第二次尝试中,您会看到该对象。但是我并不真正了解如何在 java 中解析此对象以及该值是如何在此对象中组织的。
    • 我发现了这个问题,让我写一个博客并发布相同的内容:)
    【解决方案3】:

    你应该使用params而不是数据标签而不是数据。

    $scope.postData = function() {
    
     var data = escape(angular.toJson($scope.items));
    
     $http({
          method: 'POST',
          url: '/StrutsWithAngular/shopingCart.do',
          params: 'cartValues='+data,
          headers: {'Content-Type': 'application/x-www-form-urlencoded'}
       }).success(function(data, status, headers, config) {
            $scope.items = data;
       }).error(function(data, status, headers, config) {
        // alert("Error :: "+data);
       });
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 2016-12-15
      相关资源
      最近更新 更多