如何从AngularJS POST获取Struts 1中的数据 [英] How to get the data in Struts 1 from AngularJS POST

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

问题描述

我正在将Struts1.2与AngularJS一起使用来发布一些数据,并希望使用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,status,headers,config)){$ scope.items =数据;}).error(函数(数据(状态,头,配置)){//alert(" Error ::" + data);});//第一次尝试$ scope.postData = function(){$ http({方法:"POST",网址:"/StrutsWithAngular/shopingCart.do",数据:值=" +来自请求的参数",标头:{'Content-Type':'application/x-www-form-urlencoded'}}).success(函数(数据(状态,标题,标头,配置)){alert("Success ::" + status);$ scope.items =数据;}).error(函数(数据(状态,标题,标头,配置)){alert("错误::" +数据);});};//第二次尝试$ scope.postData = function(){$ http({方法:"POST",网址:"/StrutsWithAngular/shopingCart.do",数据:"cartValues =" + {cartValues:$ scope.items},标头:{'Content-Type':'application/x-www-form-urlencoded'}}).success(函数(数据(状态,标题,标头,配置)){$ scope.items =数据;}).error(函数(数据(状态,标题,配置){//alert(" Error ::" + data);});};//第三次尝试$ scope.postData = function(){$ http({方法:"POST",网址:"/StrutsWithAngular/shopingCart.do",数据:$ scope.items}).success(函数(数据(状态,标题,标头,配置)){$ scope.items =数据;}).error(函数(数据(状态,标题,配置){//alert(" Error ::" + data);});};}); 

CartAction.java :

  package com.myapp.action;导入com.myapp.dto.ShopingCartDto;导入java.io.IOException;导入java.io.PrintWriter;导入java.util.ArrayList;导入java.util.List;导入javax.servlet.http.HttpServletRequest;导入javax.servlet.http.HttpServletResponse;导入net.sf.json.JSONArray;导入org.apache.struts.action.ActionForm;导入org.apache.struts.action.ActionForward;导入org.apache.struts.action.ActionMapping;公共类CartAction扩展了org.apache.struts.action.Action {private static final String SUCCESS ="success";/***这是从Struts框架调用的操作.** @param映射用于选择此实例的ActionMapping.* @param form此请求的可选ActionForm bean.* @param request我们正在处理的HTTP请求.* @param response我们正在处理的HTTP响应.* @抛出java.lang.Exception* @返回*/@Override公共ActionForward执行(ActionMapping映射,ActionForm表单,HttpServletRequest请求,HttpServletResponse响应)引发异常{System.out.print("Cart App");字符串值= request.getParameter("value");System.out.print("value ::" + value);字符串requestValue = request.getParameter("cartValues");System.out.print("Requested Values ::" + requestValue);if(requestValue!= null){System.out.println(请求的值::" + requestValue);JSONObject对象= JSONObject.fromObject(requestValue);System.out.println("Object Keys ::" + object.keys());迭代器iter = object.keys();System.out.println("Iter ::" + iter.toString());同时(iter.hasNext()){字符串键=(字符串)iter.next();System.out.println(键" +键);JSONArray数组= 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(标题1");shopingCartDtoOne.setQuantity("11");shopingCartDtoOne.setPrice("25");shopingCartDtoTwo.setSno(2);shopingCartDtoTwo.setTitle(标题2");shopingCartDtoTwo.setQuantity("12");shopingCartDtoTwo.setPrice("25");shopingCartDtoThree.setSno(3);shopingCartDtoThree.setTitle(标题3");shopingCartDtoThree.setQuantity("13");shopingCartDtoThree.setPrice("25");shopingCartDtos.add(shopingCartDtoOne);shopingCartDtos.add(shopingCartDtoTwo);shopingCartDtos.add(shopingCartDtoThree);ajaxResponse(响应,shopingCartDtos);返回null;}} 


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

在控制器中:

 数据:'value ='+'来自请求的参数' 

在Java中:

 字符串值= request.getParameter("value");System.out.print("value ::" + value); 

参数值:

控制台输出:

第二次尝试:

现在,当我尝试在Java中获取一堆值时,我无法实现,在这种情况下,我通过了$ scope.item,内容类型为 application/x-www-form-urlencoded 在参数 cartValues 中.在Java中,当尝试从 request.getParameter("cartValues")获取值时,该值将按照请求中的 [object Object] 打印.但是,当尝试使用Java中的JSON API解析值时,会出现异常

在控制器中:

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

在Java中:

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

第二次尝试的屏幕截图:

第三次尝试:

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

在控制器中:

 数据:$ scope.items 

第三次尝试的屏幕截图:

解决方案

使用第二次尝试,然后再发布数据,将 scope 转换为JSON.

这可以使用JSON API或AngularJS API两种方式完成

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

使用 request.getParameter(),您可以在服务器端获取该值.希望解决方案能帮助所有人.

第二次尝试:

 <代码> $ scope.postData = function(){var data = escape(angular.toJson($ scope.items));$ http({方法:"POST",网址:"/StrutsWithAngular/shopingCart.do",数据:"cartValues =" +数据,标头:{'Content-Type':'application/x-www-form-urlencoded'}}).success(函数(数据(状态,标题,标头,配置)){$ scope.items =数据;}).error(函数(数据(状态,标题,配置){//alert(" Error ::" + data);});}; 

I’m using Struts1.2 with AngularJS 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.

Now I’m trying to POST some data with AngularJS to the server and trying to get the data with 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.

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

}


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

In Controller:

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

In Java:

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

Parameter Value:

Console Output:

Second try:

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

In Controller:

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

In Java:

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

Screenshot of my second try:

Third try:

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

In Controller:

data: $scope.items

Screen shot of third try:

解决方案

Using the second try, before posting the data convert scope to JSON.

This can be done either in two ways either using JSON API or AngularJS API

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

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

Second 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 POST获取Struts 1中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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