如何从AngularJS后在Struts中的数据 [英] How to get the data in Struts from AngularJS post

查看:175
本文介绍了如何从AngularJS后在Struts中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用struts1.2与角张贴一些数据,并希望得到Java中的数据。

I’m using struts1.2 with Angular to post some data and want to get the data in java.

我能够从服务器中检索数据,并且能够在屏幕上显示它。

I’m able to retrieve the data from the server and able to display it in the screen.

现在我想用角一些数据上传到服务器,并试图从获得的request.getParameter在java中的数据。我做了三次尝试,但我不能。

Now I’m trying to post some data with Angular to the server and trying to get the data from request.getParameter in java. I made three tries but i couldn't.

下面我还提供以下文件,用我的三次尝试解释和截图。

Below I have also provided the following files, with explanation and screenshots of my three tries.

有人能帮助我在这个问题上。请让我知道的情况下,进一步的信息。

Could somebody help me on this issue. Kindly let me know in case further information.

提前感谢您的回答。

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

});

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;              

    }

}

/////

第一个尝试:当我和一个参数尝试过,我能够获得在Java中值的要求

First try: when I tried with single parameter in the request I’m able to get the value in java

在控制器: -

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

在Java中: -

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

参数值:屏幕截图

控制台输出

第二个尝试:

现在在参数cartValues​​。在Java当试图获得的request.getParameter的值(cartValues​​)中的值是越来越打印为[对象的对象]如该请求。但是,当试图解析使用JSON API在Java中有一个异常值

Now when I tried to get some bunch of values in java I couldn’t , here in this case I have passed $scope.item with the content type "application/x-www-form-urlencoded" in the parameter "cartValues". In java when tried to get the value from request.getParameter("cartValues") the value is getting printed as [object Object] as in the request. But when tried to parse the value using JSON api in java there is an exception

在控制器: -

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中值

In this case I passed only the $scope.item and removed the content type to pass it as JSON, but I don’t have a clear idea how to get the value in Java

在控制器: -

data: $scope.items

第三次尝试的屏幕截图

Screen shot of third try

推荐答案

使用第二次尝试,发布数据之前频转换范围JSON

Using the second try, before posting the data convert scope to json

这是可以做到无论是在两种方式无论是使用JSON API或角API

This can be done either in two ways either using JSON api or Angular api

我用angular.toJson(),我也用遁法接受特殊字符。

I used angular.toJson() and I also used escape method for accepting special characters.

使用的request.getParameter你可以在断绝端的价值。希望解决方案能够帮助大家。

Using request.getParameter you can get the value in the sever side. Hope solution helps everybody.

//第二个try

$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);
       });
};

这篇关于如何从AngularJS后在Struts中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆