如何从AngularJS帖子中获取Struts中的数据

Aru*_*run 5 java json struts-1 angularjs

我正在使用带有Angular的Struts1.2来发布一些数据,并希望在java中获取数据.

我能够从服务器检索数据并能够在屏幕上显示它.

现在我试图用Angular将一些数据发布到服务器并尝试从request.getParameterjava中获取数据.我做了三次尝试,但我不能.

下面我还提供了以下文件,包括我的三次尝试的说明和截图.

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

});
Run Code Online (Sandbox Code Playgroud)

2. 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;              

    }

}
Run Code Online (Sandbox Code Playgroud)

/////

首先尝试:当我在请求中尝试使用单个参数时,我能够在java中获取值

在控制器: -

data: 'value=' + 'Parameter From Request' 
Run Code Online (Sandbox Code Playgroud)

在Java中: -

String value = request.getParameter("value");
 System.out.print("value ::"+ value);
Run Code Online (Sandbox Code Playgroud)

参数值:屏幕截图

参数值

控制台输出

系统输出

第二次尝试:

现在,当我试图在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'}
Run Code Online (Sandbox Code Playgroud)

在Java中: -

   String requestValue = request.getParameter("cartValues");        
   System.out.print("Requested Values ::"+ requestValue);
Run Code Online (Sandbox Code Playgroud)

我第二次尝试的截图

请求中的对象

请求中的对象具有异常

第三次尝试:

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

在控制器: -

data: $scope.items
Run Code Online (Sandbox Code Playgroud)

屏幕截图第三次尝试

Thrid尝试使用JSON

Aru*_*run 6

使用第二次尝试,在将数据转换范围发布到json之前

这可以通过两种方式使用JSON api或Angular api完成

我使用了angular.toJson(),我还使用了escape方法来接受特殊字符.

使用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);
       });
};
Run Code Online (Sandbox Code Playgroud)