2014-04-05 21 views
5

Sto utilizzando Struts1.2 con Angular per pubblicare alcuni dati e voglio ottenere i dati in java.Come ottenere i dati in Struts da AngularJS post

Sono in grado di recuperare i dati dal server e in grado di visualizzarli sullo schermo.

Ora sto cercando di inviare alcuni dati con Angular al server e cercando di ottenere i dati da request.getParameter in java. Ho fatto tre tentativi ma non potevo.

Di seguito ho fornito anche i seguenti file, con spiegazione e schermate dei miei tre tentativi.

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;    

    } 

} 

/////

Prima prova: Quando ho provato con singolo parametro nella richiesta sono in grado di ottenere il valore in java

In Controller: -

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

In Java: -

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

Parametro Valore: Screen Shot

Parameter Value

Console uscita

System Out

secondo tentativo:

Ora, quando ho cercato di ottenere un po 'po' di valori in Java non potevo, qui, in questo caso ho passato $ scope.item con il tipo di contenuto "application/x-www-form-urlencoded" nel parametro "cartValues". In java quando si tenta di ottenere il valore da request.getParameter ("cartValues") il valore viene stampato come [oggetto oggetto] come nella richiesta.Ma quando ha cercato di analizzare il valore utilizzando JSON API java c'è un'eccezione

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 del mio secondo tentativo

Object in Request

Object in Request With Exception

terzo tentativo:

In questo caso ho passato solo il $ scope.item e rimosso il tipo di contenuto per passare come JSON, ma non hanno le idee chiare come ottenere il valore in Java

in controller: -

data: $scope.items 

Schermata di terzo tentativo

Thrid Try with JSON

+0

Qualcuno può aiutarmi sul problema di cui sopra in quanto è molto urgente – Arun

+0

In attesa del tuo post sul blog in merito! –

risposta

6

Utilizzando il secondo tentativo, prima di inviare i dati convertono portata a JSON

Questo può essere fatto sia in due modi: sia utilizzando JSON API o API angolare

ho usato angular.toJson() e ho anche metodo di escape usato per accettare caratteri speciali.

Utilizzando request.getParameter è possibile ottenere il valore nel lato sever. La soluzione di speranza aiuta tutti.

// Seconda Prova

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

angolare non pubblica i dati dei moduli, trasmette un oggetto JSON al server. Per informazioni sullo stesso JSON, vedere JSON.org. Ci sono anche molte librerie elencate in quella pagina (verso il basso) che ti permettono di analizzare JSON in varie lingue, incluso Java. Non essendo uno sviluppatore Java, non posso dire che uno di essi sia migliore dell'altro, ma dovresti essere in grado di ottenere una buona idea di idoneità leggendo i documenti su ognuno di essi.

+0

Sto usando l'API JSON per recuperare i dati in cui sto riscontrando un problema, Solo quando usiamo il tipo di contenuto application/x-www-form-urlencoded saremo in grado di ottenere i dati sul lato server. Nel mio primo tentativo puoi vedere che sono in grado di ottenere i dati che ho postato. Nel secondo tentativo si vede l'oggetto. Tuttavia non capisco veramente come analizzare questo oggetto in java e anche come il valore è organizzato in questo oggetto. – Arun

+0

Ho trovato il problema lasciatemi scrivere un blog e postare lo stesso :) – Arun

0

Non sono dati che si dovrebbe usare params invece di tag di dati.

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