0

Here I'm using Angular with struts and I'm new to Angular.

I have a controller(Controller.js) where i'm using a post method to call the action class (CartAction).

I don't find any errors while calling the action /StrutsAngular/ControllerAction.do from post in controller.js.

But the action class is not executing, even the system.out.println is not executed. When i added the alert in success function i'm able to get the input page. When i have given the wrong path i got into error function.

I couldn't understand why the action is not called.

And I have another clarification, if in this case --> if the action is called where i can get the response data.

Earlier i have used jQuery and i have also provided the sample code which i used. How can we do it in a similar way using AngularJS

Kindly help me and let me know in case of further information.

Thanks in advance for the answers.

Controller.js

function Controller($scope,$http) {

 $http.post('/StrutsAngular/ControllerAction.do').
        success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        alert("Success :: "+data);
         }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert("Error :: "+data);
    });


}

Action Class

public class CartAction extends org.apache.struts.action.Action {


    /**
     * 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.println("Entering Shop Cart Action");

    List<Object> objectList= new ArrayList<>(); 

    CartDto cartDto = new ShopingCartDto();
        cartDto.setSno(1);
        cartDto.setTitle("Title One");

    objectList.add(cartDto);


        response.setHeader("cache-control","no-cache");
        response.setContentType("text/json");
        PrintWriter out = response.getWriter();

    JSONArray jsonArray = JSONArray.fromObject(objectList);
        out.println(jsonArray.toString());

        return null;
    }


}

Jquery

function onSubmit(){
 var url = "/StrutsAngular/ControllerAction.do";
 var formID = document.getElementById('formId');
 var forwardUrl = "/StrutsAngular/ControllerAction.do";

}

function doAjaxPost(formId,url,forwardUrl){

    var data = $("#"+formId+" :input").serializeArray();
    $.ajax({
    type: "POST",
    url: url,
    data: data,
    beforeSend: function(jqXHR, settings){

        var value = "Please Wait until progressing!";
        document.getElementById('progress').innerHTML=value;               
    },
    success: function(json){


     var message=json[0].message;


    },
    error: function(jqXHR, textStatus, errorThrown){

        if(jqXHR.status==500){
            document.getElementById('errorMessage').innerHTML=errorThrown;
        }

    },
    complete: function(jqXHR, textStatus){
        document.getElementById('progress').innerHTML="";

        if(jqXHR.status==500){

            var message = textStatus;
            document.getElementById('errorMessage').innerHTML=message;

        }

    }
});

}

JSP

<%-- 
    Document   : Cart
    Created on : 25 Mar, 2014, 5:14:42 PM
    Author     : Arun
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html ng-app>
    <head>
        <title>Cart</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">
        <script src="js/lib/angularjs-1.0.2/angular.js"></script>
        <script src="js/lib/controllers/controllers.js"></script>
        <link href="js/lib/bootstrap/css/bootstrap.css" rel="stylesheet">
    </head>
    <body ng-controller='Controller'>

       <div class="container">


           <form name="shoppingForm" id="formId">

                <table class="table table-striped table-hover">
                    <caption></caption>
                    <thead>
                       <tr>
                        <th>S No</th>
                        <th>Item</th>
                       </tr> 
                    </thead>

                    <tr ng-repeat='item in items | orderBy:title | filter:search' >
                         <td ><input ng-model='item.sno' class="form-control" size="3" placeholder="Quantity" maxlength="3" required></td>
                        <td ><input ng-model='item.title' class="form-control" size="10" maxlength="10" placeholder="Item Name" required></td>
                    </tr>
                </table>
                <div><button class="btn btn-lg btn-success btn-block">Submit</button></div>
           </form>

       </div>
    </body>
</html>
Arun
  • 1,010
  • 6
  • 18
  • 37

1 Answers1

1

Ok, you have a few issues going on and most of them appear to be a misunderstanding of how Angular works. There is a great SO post about "thinking in angular" from a jQuery background:

"Thinking in AngularJS" if I have a jQuery background?

To give you some specifics based on your code so far:

First, you need to create an app (angular.module) to which the ng-app attribute is assigned. For example:

 var myApp = angular.module('myApp',[]); // this creates a new angular module named "myApp";

 <html ng-app="myApp"> // this will bootstrap your myApp module at the html DOM element once the domIsReady event fires

Second, you need to define a controller using Angular, on a module, and pass a function. There is an experimental "Controller as" syntax for Angular but I'd suggest doing it the standard way before trying that.

myApp.controller('myCtrl', function ($scope,$http) {

 $http.post('/StrutsAngular/ControllerAction.do').
        success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        alert("Success :: "+data);
         }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        alert("Error :: "+data);
    });
});

<div ng-controller="myCtrl">

Lastly, the function passed to controller() will only be invoked once, and only after it's been used somewhere. So binding to the DIV, in this example, would result in a single $http.post right as the DOM is loaded. It won't do anything else. I'm assuming this is just you testing that it got there. For "real" code you would expose certain functions via the $scope and call them from your view:

myApp.controller('myCtrl', function ($scope,$http) {
   $scope.sendData = function() {
     $http.post(.....your other code....);
   }
});

<div ng-controller="myCtrl"><a ng-click="sendData()">send data</a></div>
Community
  • 1
  • 1
Matt Pileggi
  • 7,126
  • 4
  • 16
  • 18
  • Now I understood how to start with Angular thanks a lot, as advised i created the service and i tried in both ways on initial load and with the click, but still now i'm not able to call the Action class.. Kindly let me know in case of further information... – Arun Mar 30 '14 at 03:50
  • I found the issue in struts-config.xml, the problem in tag here validate should be no – Arun Apr 01 '14 at 10:23