This tutorial can concentrate on creating, reading, updating, deleting and searching database records. we'll make out using a Google’s
AngularJS, Struts2 and MySQL.
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`
--
CREATETABLE IF NOTEXISTS `products` (
`id` int(11) NOTNULL AUTO_INCREMENT,
`name` varchar(512) NOTNULL,
`description` textNOTNULL,
`price` int(11) NOTNULL,
PRIMARYKEY (`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;
importjava.sql.Connection;
importjava.sql.DriverManager;
publicclassConnectionConfiguration {
publicstaticfinal String URL = "jdbc:mysql://localhost:3306/strutsangularcrud";
/**
* In my case username is "root" *
*/
publicstaticfinal String USERNAME = "root";
/**
* In my case password is "1234" *
*/
publicstaticfinal String PASSWORD = "";
publicstatic 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;
publicclassProduct {
privateint id;
private String name;
private String description;
privateint price;
publicintgetId() {
return id;
}
publicvoidsetId(int id) {
this.id = id;
}
public String getName() {
return name;
}
publicvoidsetName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
publicvoidsetDescription(String description) {
this.description = description;
}
publicintgetPrice() {
return price;
}
publicvoidsetPrice(int price) {
this.price = price;
}
publicProduct(){}
publicProduct(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>
<metacharset="utf-8">
<metahttp-equiv="X-UA-Compatible"content="IE=edge">
<metaname="viewport"content="width=device-width, initial-scale=1">
<title>Insert Products</title>
<!-- include material design CSS -->
<linkrel="stylesheet"href="css/materialize.min.css"/>
<!-- include material design icons -->
<linkhref="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.
<divclass="container"ng-app="myApp"ng-controller="productsCtrl">
<divclass="row">
<divclass="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 -->
<divid="modal-product-form"class="modal">
<divclass="modal-content">
<h4id="modal-product-title">Create New Product</h4>
<divclass="row">
<divclass="input-field col s12">
<inputng-model="name"type="text"class="validate"id="form-name"placeholder="Type name here..."/>
<labelfor="name">Name</label>
</div>
<divclass="input-field col s12">
<textareang-model="description"type="text"class="validate materialize-textarea"placeholder="Type description here..."></textarea>
<labelfor="description">Description</label>
</div>
<divclass="input-field col s12">
<inputng-model="price"type="text"class="validate"id="form-price"placeholder="Type price here..."/>
<labelfor="price">Price</label>
</div>
<divclass="input-field col s12">
<aid="btn-create-product"class="waves-effect waves-light btn margin-bottom-1em"ng-click="createProduct()"><iclass="material-icons left">add</i>Create</a>
<aid="btn-update-product"class="waves-effect waves-light btn margin-bottom-1em"ng-click="updateProduct()"><iclass="material-icons left">edit</i>Save Changes</a>
<aclass="modal-action modal-close waves-effect waves-light btn margin-bottom-1em"><iclass="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 -->
<divclass="fixed-action-btn"style="bottom:45px; right:24px;">
<aclass="waves-effect waves-light btn modal-trigger btn-floating btn-large red"href="#modal-product-form"ng-click="showCreateForm()"><iclass="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
<packagename="default"extends="json-default">
<actionname="addproduct"class="com.blogspot.geekonjava.json.ProductJSONAction"method="getFileName">
<resulttype="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;
importjava.sql.Connection;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
importjava.util.ArrayList;
importjava.util.List;
importorg.json.simple.JSONObject;
importorg.json.simple.parser.JSONParser;
importcom.blogspot.geekonjava.gs.Product;
publicclassProductDB {
publicstatic 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;
}
publicstaticvoidinsert(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
package com.blogspot.geekonjava.json;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importjavax.servlet.http.HttpServletRequest;
importorg.apache.commons.io.IOUtils;
importorg.apache.struts2.ServletActionContext;
importcom.blogspot.geekonjava.db.ProductDB;
importcom.blogspot.geekonjava.gs.Product;
importcom.opensymphony.xwork2.Action;
publicclassProductJSONAction{
static HttpServletRequest request ;
publicstatic 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;
}
}
Output should look like this
This section is for insert 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.