Struts2 AngularJS CRUD Example - Update Operation

In my previous article on Struts2 and AngularJS CRUD example I covered CR(Create/Insert and Read/Fetch) part and in this article we're covering update operation in this integration.
For better understanding of this section please check previous article carefully because we'll go ahead with previous references.



Hope you'll be familiar with file structure now we'll dive in update operation. Here all works performed on Read section 2 where data shown in table with Edit button like given below:


Now  our first work is that when we click on edit button a modal will be open with their correspondence data relate to their id.

3.1 AngularJS code to read details of record to be edited

The following code will help put the details of record to be edited to our HTML form.
// retrieve record to fill out the form
$scope.readOne = function(id){
     
    // change modal title
    $('#modal-product-title').text("Edit Product");
     
    // show udpate product button
    $('#btn-update-product').show();
     
    // show create product button
    $('#btn-create-product').hide();
     
    // post id of product to be edited
    $http.post("readoneproducts", {
        'id' : id 
    })
    .success(function(data, status, headers, config){
         
        // put the values in form
        
        $scope.id = data['personData']["id"];
        $scope.name = data['personData']["name"];
        $scope.description = data['personData']["description"];
        $scope.price = data['personData']["price"];
         
        // show modal
        $('#modal-product-form').openModal();
    })
    .error(function(data, status, headers, config){
        Materialize.toast('Unable to retrieve record.', 4000);
    });
}
Now configure readoneproducts action in struts.xml

3.2 Struts.xml

<action name="readoneproducts" class="com.blogspot.geekonjava.json.ProductSingleFetch" >
            <result type="json" />
            
      </action>
Now write our logic code in ProductSingleFetch

3.3 ProductSingleFetch.java

package com.blogspot.geekonjava.json;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;

import com.blogspot.geekonjava.db.ProductDB;
import com.blogspot.geekonjava.gs.Product;
import com.opensymphony.xwork2.Action;

public class ProductSingleFetch implements Action {
	static HttpServletRequest request ;

	private Product personData = new Product();

    public String execute() throws IOException {

    	 request  =  ServletActionContext.getRequest();
			String filename = IOUtils.toString(request.getInputStream());
		Product	p = ProductDB.fileToString(filename);
		personData.setId(p.getId());
		personData.setName(p.getName());
		personData.setDescription(p.getDescription());
		personData.setPrice(p.getPrice());
            return SUCCESS;
    }
    
    
    public String updateProductData() throws IOException
    {
    	request  =  ServletActionContext.getRequest();
		String filename = IOUtils.toString(request.getInputStream());
		System.out.println("fileee1 "+filename);
	Product	p = ProductDB.jsonDataForUpdate(filename);
	
    	return "success";
    }
    

	public Product getPersonData() {
		return personData;
	}

	public void setPersonData(Product personData) {
		this.personData = personData;
	}
	
}

3.4 AngularJS code to update a record

The following code will be triggered when the “Save Changes” button in the modal was clicked. Put it inside the app.controller curly braces.
// update product record / save changes
$scope.updateProduct = function(){
    $http.post('updateproducts', {
        'id' : $scope.id,
        'name' : $scope.name, 
        'description' : $scope.description, 
        'price' : $scope.price
    })
    .success(function (data, status, headers, config){             
        // tell the user product record was updated
        Materialize.toast(data, 4000);
         
        // close modal
        $('#modal-product-form').closeModal();
         
        // clear modal content
        $scope.clearForm();
         
        // refresh the product list
        $scope.getAll();
    });
}
Now configure updateproducts action in struts.xml after section 3.2
<action name="updateproducts" class="com.blogspot.geekonjava.json.ProductSingleFetch" method="updateProductData">
            <result type="json" />
            
      </action>

3.5 Now add two function in ProductDB.java

jsonDataForUpdate

public static Product jsonDataForUpdate(String filename)
	{
		System.out.println("inside filetostring "+filename);
		 Product p = new Product();
		 JSONParser parser = new JSONParser(); 
			try { 
				
				Object obj = parser.parse(filename);
				System.out.println("object "+obj);
			JSONObject json = (JSONObject) obj; 
			
			int id = Integer.parseInt(String.valueOf(json.get("id"))); 
			String name= (String)json.get("name");
			String description = (String)json.get("description");
			int price = Integer.parseInt(String.valueOf(json.get("price")));
			p.setId(id);
			p.setName(name);
			p.setDescription(description);
			p.setPrice(price);
			update(p, id);
			System.out.println("id "+id);
			
			
			}
			catch (Exception ex) {  }
		return p;
	    
	}

update

public static void update(Product person, int id) {
	        Connection connection = null;
	        PreparedStatement preparedStatement = null;
	 
	        try {
	            connection = ConnectionConfiguration.getConnection();
	            preparedStatement = connection.prepareStatement("UPDATE products SET " +
	                    "name = ?, description = ?, price = ?  WHERE id = ?");
	 
	            preparedStatement.setString(1, person.getName());
	            preparedStatement.setString(2, person.getDescription());
	            preparedStatement.setInt(3, person.getPrice());
	            preparedStatement.setInt(4, id);
	            preparedStatement.executeUpdate();
	 
	            System.out.println("UPDATE person SET " +
	                    "first_name = ?, last_name = ? WHERE id = ?");
	 
	        } catch (Exception e) {
	            e.printStackTrace();
	        } finally {
	            if (preparedStatement != null) {
	                try {
	                    preparedStatement.close();
	                } catch (SQLException e) {
	                    e.printStackTrace();
	                }
	            }
	            if (connection != null) {
	                try {
	                    connection.close();
	                } catch (SQLException e) {
	                    e.printStackTrace();
	                }
	            }
	        }
	    }

Output should look like this

When you clicked an “Edit” button in the product list, you should see the modal with form data of record to be edited.

This section is for editing or updating module of Struts2 with AngularJS and hope you enjoy this tutorial. And if you want source code of this section. Please send me your request then i'll send that on your email id and contact us.
Please feel free to suggest and comment.

Comments

  1. please send me source code surendra88meena@gmail.com

    ReplyDelete

Post a Comment