Struts2 AngularJS Insert Operation Example

AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template language and lets you extend HTML’s syntax to express your application’s components clearly and succinctly. AngularJS’s data binding and dependency injection eliminate much of the code you would otherwise have to write.

Every Java developers may be want to use AngularJS but limited tutorials present . Due to this i created this tutorial series and in this tutorial we discuss about insert operation using Struts 2 and AngularJS.

We have to create a database, then a table with the following table structure

Run the following SQL code on your PhpMyAdmin. This is to create our database table name products. By the way, the database name we used in this tutorial was named struts2angularcrud.

CREATE TABLE IF NOT EXISTS `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(512) NOT NULL,
  `description` text NOT NULL,
  `price` int(11) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;

Struts2 AngularJS Insert Operation

I used jQuery and MaterializeCss for designing purpose in addition. You can use any thing for that.

<div class="container" ng-app="myApp" ng-controller="productsCtrl">
 <div class="row">
 <div class="col s12">
 <h4>Products</h4>
 
 <!-- floating button for creating product -->
<div class="fixed-action-btn" style="bottom:45px; right:24px;">
 <a class="waves-effect waves-light btn modal-trigger btn-floating btn-large red" href="#modal-product-form" ng-click="showCreateForm()"><i class="large material-icons">add</i></a>
</div>
 
 <!-- modal for for creating new product -->
<div id="modal-product-form" class="modal">
 <div class="modal-content">
 <h4 id="modal-product-title">Create New Product</h4>
 <div class="row">
 <div class="input-field col s12">
 <input ng-model="name" name="name" type="text" class="validate" id="form-name" placeholder="Type name here..." />
 <label for="name">Name</label>
 </div>
 
 <div class="input-field col s12">
 <textarea ng-model="description" name="description" type="text" class="validate materialize-textarea" placeholder="Type description here..."></textarea>
 <label for="description">Description</label>
 </div>
 
 
 <div class="input-field col s12">
 <input ng-model="price" type="text" name="price" class="validate" id="form-price" placeholder="Type price here..." />
 <label for="price">Price</label>
 </div>
 
 
 <div class="input-field col s12">
 <a id="btn-create-product" class="waves-effect waves-light btn margin-bottom-1em" ng-click="createProduct()"><i class="material-icons left">add</i>Create</a>
 
 <a class="modal-action modal-close waves-effect waves-light btn margin-bottom-1em"><i class="material-icons left">close</i>Close</a>
 </div>
 </div>
 </div>
</div>
 
 </div> <!-- end col s12 -->
 </div> <!-- end row -->
</div> <!-- end container -->

What was in above code?

  1. Line 1: You can see ng-app=”myApp” .The ngapp directive tells AngularJS that this is the root element of the AngularJS application. All AngularJS applications must have a root element. You can only have one ngapp directive in your HTML document. If more than one ngapp directive appears, the first appearance will be used. You can use any name instead of myApp.
  2. Line 6-9: It is code of floating button to open modal with form and AngularJS perform click function using ng-click directive. Here we use showCreateForm() we discuss about this function implementation below.
  3. Line 17,22,28: It is normal textfield of form but one thing is different which is ng-model. The ngModel directive binds an input , select , textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive. ngModel is responsible for: Binding the view into the model, which other directives such as input , textarea or select require.
  4. Line 34: It is for Create button with ng-click=”createProduct()” .

Lets discuss about AngularJS part:

In this project i made separate js file for AngularJS named : product.js

// angular js codes will be here
var app = angular.module('myApp', []);
app.controller('productsCtrl', function($scope, $http) {
    // more angular JS codes will be here
 
    
$scope.showCreateForm = function(){
    // clear form
    $scope.clearForm();
     
    // change modal title
    $('#modal-product-title').text("Create New Product");
     
     
    // show create product button
    $('#btn-create-product').show();
     
}


// create new product 
$scope.createProduct = function(){
         
    // fields in key-value pairs
    $http.post("addproduct.action", {
            'name' : $scope.name, 
            'description' : $scope.description, 
            'price' : $scope.price,
            
    
        }
    ).success(function (data, status, headers, config) {
        console.log(data);
        // tell the user new product was created
        Materialize.toast(data['maps']["status"], 4000);
         
        // close modal
        $('#modal-product-form').closeModal();
         
      
         
        
    });
}

   
});

What was in above code ?

  1. Line 2: You can initialized your Angular app.
  2. Line 3: After init the app you need to name the controller. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.
  3. Line 7-20: Here the implementation of click on floating button and perform showCreateForm() function click.
  4. Line 24-48: You can see we used $http services. The $http service is a core AngularJS service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object. In this service we call post method which first parameter for Java action(addproduct.action) and second parameter for form data.

Now lets move on Struts2 part

Project directory : Struts2 AngularJS Insert Operation
Project directory : Struts2 AngularJS Insert Operation

Firstly we create class named Product.java

package co.tellmehow.gs;


public class Product {
  
  
  private int id;
  private String name;
  private String description;
  private int price;
 
  //getter setter
  
  public Product(){}
  public Product(String name, String description, int price)
  {
    this.name=name;
    this.description=description;
    this.price=price;
  }
  
  

}

After that we define addproduct.action in struts.xml and your file will be:

<package name="default" extends="json-default">
      <!-- Insert products -->  
      <action name="addproduct" class="co.tellmehow.json.ProductAction" method="insertProductData">
            <result type="json" />
      </action>
 
</package>

And now create method insertProductData in ProductAction class

public String insertProductData()
  {
    JSONParser parser = new JSONParser();
    String jsondata = JSONConfigure.getAngularJSONFile();
    try { 
      Object obj = parser.parse(jsondata);
      JSONObject json = (JSONObject) obj; 
      String name = (String) json.get("name"); 
      String description = (String) json.get("description"); 
      int price = Integer.parseInt((String) json.get("price")); 
      
      
      Product p = new Product(name, description, price);
      
      // insert in database and get generated id
      int result = ProductDB.insertProducts(p);
      if(result!=0)
      {
        maps.put("status", "Insert data succesfully !!");
        
      }
      else
      {
        maps.put("status", "Some error occurred !!");
        
      }
      
      
      System.out.println(name);
    }
    catch (Exception ex) { maps.put("status", "Some error occurred !!"); }
    return Action.SUCCESS;
  }

Finally your insertion tutorial is finished.

Next tutorial will be on Read Operation soon. Please keep in touch and comment your queries or suggestions.

By Tell Me How

It is a technology blog and admin has excellent experience in programming from 5+ year. You can contact us at ceo.tellmehow@gmail.com

Share your thoughts

Leave a Reply

Loading Facebook Comments ...
Loading Disqus Comments ...