How to get the data in Struts 1 from AngularJS POST
Asked Answered
E

3

5

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:

Parameter Value

Console Output:

System Out

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:

Object in Request

Object in Request With Exception

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:

Thrid Try with JSON

Endlong answered 5/4, 2014 at 14:6 Comment(2)
Can somebody help me on the above issue since it is very urgentEndlong
Waiting for your blogpost regarding issue!Faught
E
6

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);
       });
};
Endlong answered 18/8, 2014 at 8:9 Comment(0)
A
0

Angular does not POST form data, it transmits a JSON object to the server. For information on JSON itself, see JSON.org. There are also a wealth of libraries listed on that page (towards the bottom) that let you parse JSON in various languages, including Java. Not being a Java developer, I can't say that one of them is better than the other, but you should be able to get a good idea of suitability by reading the docs on each one.

Awestricken answered 7/4, 2014 at 16:46 Comment(2)
I'm using the JSON api to fetch the data where i'm getting an issue, Only when we use the content type application/x-www-form-urlencoded we will able to get the data on the server side. In my first try you can see i'm able to get the data which i posted. In the second try you see the object.However I don't really understand how to parse this Object in java and also how the value is organized in this object.Endlong
I have found the issue let me write a blog and post the same :)Endlong
L
0

It is not data that you should use params instead of data tag.

$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);
   });
};
Lesterlesya answered 31/3, 2016 at 6:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.