LINK
As for the user interface, rather than Bootstrap, we'll use materialize CSS – a modern responsive front-end framework based mostly additionally on Google’s Material design.FILE STRUCTURE
Knowing the file structure can offer us an outline of what Struts2 files can we need to create and wherever the assets should be placed.DATABASE STRUCTURE AND CONNECTION
We have to make a database, then a table with the subsequent table structure, and a Struts2 file that we'll use for database connection.1.1 create the database table
Run the subsequent SQL code on your PhpMyAdmin or any Database you want. this can be to create our database table. By the way, the database name we used in this tutorial was named “strutsangularcrud”.-- -- Table structure for table `products` -- 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, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;
Now dive to some coding part in file structure you can see i made three package(com.blogspot.geekonjava.db, com.blogspot.geekonjava.gs, com.blogspot.geekonjava.json) as per name convention you can understand easily that what purpose of which package.
- com.blogspot.geekonjava.db
This package for all database connectivity part and in this example i
made two java file first for database configuration and other for
product database part.
Note : So put the mysql-connector.jar in you WEB-INF/lib
Info : Don't panic to find extra libraries download the project and you'll get everything.
ConnectionConfiguration.java
package com.blogspot.geekonjava.db; import java.sql.Connection; import java.sql.DriverManager; public class ConnectionConfiguration { public static final String URL = "jdbc:mysql://localhost:3306/strutsangularcrud"; /** * In my case username is "root" * */ public static final String USERNAME = "root"; /** * In my case password is "1234" * */ public static final String PASSWORD = ""; public static Connection getConnection() { Connection connection = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (Exception e) { e.printStackTrace(); } return connection; } }
- com.blogspot.geekonjava.gs
It is for all getter setter object will be here like in this project i made:
Product.java
package com.blogspot.geekonjava.gs;public class Product { private int id; private String name; private String description; private int price; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Product(){} public Product(String name, String description, int price) { this.name=name; this.description=description; this.price=price; } }
MAKE USE OF YOUR HTML CODING SKILLS
1.1 Create basic HTML code structure for index.jsp
Create the index.jsp file. This is the only page the user has to interact with. Make it ready for AngularJS, Material Design and jQuery by including the necessary library sources.<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Insert Products</title> <!-- include material design CSS --> <link rel="stylesheet" href="css/materialize.min.css" /> <!-- include material design icons --> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" /> <!-- custom CSS --> <style> .width-30-pct{ width:30%; } .text-align-center{ text-align:center; } .margin-bottom-1em{ margin-bottom:1em; } </style> </head> <body> <!-- page content and controls will be here --> <!-- page end here --> <!-- include jquery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <!-- material design js --> <script src="js/materialize.min.js"></script> <!-- include angular js --> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <script> // angular js codes will be here // jquery codes will be here </script> </body> </html>
1.2 Put the most important DIV tag
Inside this “div” tag is where every main content of the page will be loaded. Add the following code after the opeing “body” tag.<div class="container" ng-app="myApp" ng-controller="productsCtrl"> <div class="row"> <div class="col s12"> <h4>Products</h4> </div> <!-- end col s12 --> </div> <!-- end row --> </div> <!-- end container -->
1.3 HTML code of “create product form”
Put the following code under the “h4” tag in section 1.2. It is a form shown via modal or pop up. We will also use the same HTML form for updating a record later.<!-- 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" 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" 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" 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 id="btn-update-product" class="waves-effect waves-light btn margin-bottom-1em" ng-click="updateProduct()"><i class="material-icons left">edit</i>Save Changes</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>
1.4 HTML button to show the “create product HTML form”
Put the following code under the code in section 1.3, it will make a floating red button located at the lower right corner of the page.<!-- 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>
1.5 AngularJS Basic Code
Put the following AngularJS code inside the “script” tag of section 1.1 above.var app = angular.module('myApp', []); app.controller('productsCtrl', function($scope, $http) { // more angular JS codes will be here });
1.6 AngularJS “showCreateForm” function to show “create product form”
Put the following code inside the app.controller curly braces in section 1.5 above.$scope.showCreateForm = function(){ // clear form $scope.clearForm(); // change modal title $('#modal-product-title').text("Create New Product"); // hide update product button $('#btn-update-product').hide(); // show create product button $('#btn-create-product').show(); }
1.7 AngularJS “clearForm” function to remove any form values that exists
Put the following code under the “showCreateForm” function code in section 1.6 above.// clear variable / form values $scope.clearForm = function(){ $scope.id = ""; $scope.name = ""; $scope.description = ""; $scope.price = ""; }
1.8 AngularJS “createProduct” function
The following code is triggered when the “Create Product” button on the modal or pop up form was clicked. Put it under the code in section 1.8.// create new product $scope.createProduct = function(){ // fields in key-value pairs $http.post('create_product.php', { '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("New product created", 4000); // close modal $('#modal-product-form').closeModal(); // clear modal content $scope.clearForm(); // refresh the list $scope.getAll(); }); }
1.9 jQuery script to initialize modal
This small jQuery script will initialize our modal or pop up. This modal is used for “create product” and “update product” pop up forms.$(document).ready(function(){ // initialize modal $('.modal-trigger').leanModal(); });
AngularJS deals with JSON . So firstly need some change in struts.xml
struts.xml
Put below code under the <Struts> tag
<package name="default" extends="json-default"> <action name="addproduct" class="com.blogspot.geekonjava.json.ProductJSONAction" method="getFileName"> <result type="json" /> </action> </package>
And now this time to add third and last package
- com.blogspot.geekonjava.json
In this package all the JSON part which AngularJS will be dealing
Note : So put the json-simple.jar in you WEB-INF/lib
Info : Don't panic to find extra libraries download the project and you'll get everything.
ProductDB.java
package com.blogspot.geekonjava.db;import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import com.blogspot.geekonjava.gs.Product; public class ProductDB { public static Product fileToString(String filename) { Product p = new Product(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(filename); JSONObject json = (JSONObject) obj; String name = (String) json.get("name"); String description = (String) json.get("description"); int price = Integer.parseInt((String) json.get("price")); ProductDB.insert(name, description, price); System.out.println(name); } catch (Exception ex) { ex.printStackTrace(); } return p; } public static void insert(String name, String description, int price) { System.out.println("in insert "+name+ description); Connection connection = null; PreparedStatement preparedStatement = null; System.out.println("11111111111111111111111"); try { connection = ConnectionConfiguration.getConnection(); preparedStatement = (PreparedStatement) connection.prepareStatement("INSERT INTO products (name,description,price)" + "VALUES (?, ?,?)"); System.out.println("2222222222222222"); preparedStatement.setString(1, name); preparedStatement.setString(2, description); preparedStatement.setInt(3, price); preparedStatement.executeUpdate(); } 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(); } } } } }
ProductJSONAction.java
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; 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 ProductJSONAction{ static HttpServletRequest request ; public static String getFileName() { try { request = ServletActionContext.getRequest(); String filename = IOUtils.toString(request.getInputStream()); System.out.println("fileee "+filename); ProductDB.fileToString(filename); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "success"; } public String execute() { return Action.SUCCESS; } }
Comments
- Chạy ví dụ trên sẽ có màn hình như sau:
- Thay create_product.php bằng một action của struts2 mà trả về một chuỗi định dạng json, ví dụ: $http.post('struts2/addproduct.action', $scope.product)
- Thư viện Material tương thích ví dụ phiên bản v0.97.5
- Insert data là chức năng đầu tiên và căn bản để có dữ liệu cho các chức năng khác như list, update, delete.
- struts2-angularjs-crud-example-read
- struts2-angularjs-crud-example-update
- struts2-angularjs-crud-example-delete
This post is really nice and informative. The explanation given is really comprehensive and informative..
ReplyDeleteOffshore Angular Development Company – Nintriva
This comment has been removed by the author.
ReplyDelete