Struts 2 and Tiles Framework Integration
Apache Tiles is a templating framework used to simplify the development of web application user interfaces. Tiles allow defining page fragments which can be combined into a complete page at runtime. These fragments, or tiles, can be used as reusable templates in order to reduce the duplication of common page elements or even embedded within other tiles. See the snapshot below.
** UPDATE: Struts 2 Complete tutorial now available here.
Advantage of tiles framework
- Code reusability
- Easy to modify
- Easy to remove
Jar Required
Folder structure
web.xml
Provide entry of listener class Struts2TilesListener in the web.xml file.
<listener> <listener-class>org.apache.struts2.tiles.StrutsTilesListener</listener-class> </listener>
Jsp Pages
Now We will define the template for our web application in baseLayout.jsp file. This template will contain different segments of web page (Header, Footer, Menu, Body).
File : baseLayout.jsp
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title><tiles:insertAttribute name="title" ignore="true" /></title> <style> .one { border-style: solid; border-color: #0000ff; border-collapse: collapse; } </style> </head> <body> <table border="1" align="center" class="one" width="80%"> <tr> <td height="30" colspan="2" class="one" width="20%"> <tiles:insertAttribute name="header" /> </td> </tr> <tr> <td height="250" class="one"> <tiles:insertAttribute name="menu" /> </td> <td width="350" class="one"> <tiles:insertAttribute name="body" /> </td> </tr> <tr> <td height="30" colspan="2" class="one"> <tiles:insertAttribute name="footer" /> </td> </tr> </table> </body> </html>
File : header.jsp
<html> <body> <div align="center" style="color: gray; font-weight: bold;"> Struts 2 - Tiles Demo - Header page </div> </body> </html>
File : footer.jsp
<html> <body> <div align="center" style="color: gray; font-weight: bold;"> Footer page © SimpleCodeStuffs.com </div> </body> </html>
File : body.jsp
<html> <body> <p align="center" style="color: gray;font-weight: bold;">Home Page</p> </body> </html>
File : menu.jsp
<%@taglib prefix="s" uri="/struts-tags"%> <html> <body> <s:url action="strutsAction" var="strutsAction" /> <s:url action="springAction" var="springAction" /> <div align="center"> Menu <br /> <br /> <br /> <br /> <s:a href="%{strutsAction}">Struts Tutorial</s:a> <br /> <br /> <s:a href="%{springAction}">Spring Tutorial</s:a> </div> <br> </body> </html>
File : springTutorial.jsp
<html> <body> <p align="center" style="color: gray;font-weight: bold;">Spring Tutorial !!!</p> </body> </html>
File : strutsTutorial.jsp
<html> <body> <p align="center" style="color: gray;font-weight: bold;">Struts Tutorial !!!</p> </body> </html>
File : index.jsp
It triggers homeAction during application start up
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=homeAction">
Action Class
package com.simplecodestuffs.action; public class TilesAction { public String home() { return "home"; } public String struts() { return "struts"; } public String spring() { return "spring"; } }
struts.xml
In struts.xml, inherit the tiles-default package and define all the result type as tiles
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="tiles-default"> <action name="*Action" method="{1}" class="com.simplecodestuffs.action.TilesAction"> <result name="home" type="tiles">home</result> <result name="struts" type="tiles">struts</result> <result name="spring" type="tiles">spring</result> </action> </package> </struts>
tiles.xml
The tiles.xml file must be located inside the WEB-INF directory, in which define all the tiles definitions
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN" "http://tiles.apache.org/dtds/tiles-config_2_0.dtd"> <tiles-definitions> <definition name="baseLayout" template="/baseLayout.jsp"> <put-attribute name="title" value="Template" /> <put-attribute name="header" value="/header.jsp" /> <put-attribute name="menu" value="/menu.jsp" /> <put-attribute name="body" value="/body.jsp" /> <put-attribute name="footer" value="/footer.jsp" /> </definition> <definition name="home" extends="baseLayout"> <put-attribute name="title" value="Home" /> <put-attribute name="body" value="/home.jsp" /> </definition> <definition name="struts" extends="baseLayout"> <put-attribute name="title" value="Struts Tutorial" /> <put-attribute name="body" value="/strutsTutorial.jsp" /> </definition> <definition name="spring" extends="baseLayout"> <put-attribute name="title" value="Spring Tutorial" /> <put-attribute name="body" value="/springTutorial.jsp" /> </definition> </tiles-definitions>
Demo
Home Page with Tiles
Struts Page with Tiles
Spring Page with Tiles
How to define multiple tiles files in struts 2 application?
To define multiple tiles, you need to add following entry in your web.xml file.
<context-param id="struts_tiles"> <param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG </param-name> <param-value> /WEB-INF/tiles1.xml,/WEB-INF/tiles2.xml</param-value> </context-param>
|
Read More
Struts2-Jfreechart integration
In this article we will learn to integrate Struts 2 with JFreeChart using struts2-jfreechart-plugin-x.x.x.jar for creating a pie chart in web application using JFreeChart library.
The JFreeChart is easiest and the most widely used library for creating a wide variety of good looking charts.
The Struts-JFreeChart plugin allows Struts 2 Actions to easily return generated charts and graphs.
Instead of streaming a generated chart directly to the HTTP response, this plugin provides a ChartResult, which handles the generation for you. This allows you to generate the chart in one class, and render it out in another class, effectively decoupling the view from the Actions.
** UPDATE: Struts 2 Complete tutorial now available here.
Libraries required :
- struts2-jfreechart-plugin-x.x.x.jar
- Commonly required Struts 2 jars
- jfreechart-x.x.x.jar
- jcommon-x.x.x.jar
Jfreechart library can be downloaded here.
Now Create a New Dynamic Web Project in eclipse with following folder structure
Struts 2 Action
File : JfreeChartAction.java
package com.simplecodestuffs.action; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.data.general.DefaultPieDataset; import com.opensymphony.xwork2.Action; public class JfreeChartAction implements Action { private JFreeChart chart; public String execute() throws Exception { DefaultPieDataset dataSet = new DefaultPieDataset(); dataSet.setValue("Agriculture", 10); dataSet.setValue("Residential heating", 4); dataSet.setValue("Commercial products", 15); dataSet.setValue("Industry", 42); dataSet.setValue("Transportation", 26); dataSet.setValue("Others", 3); chart = ChartFactory.createPieChart( "Source of Air Pollution ", // Title dataSet, // Data true, // Display the legend true, // Display tool tips false // No URLs ); chart.setBorderVisible(true); return SUCCESS; } // This method will get called if we specify <param name="value">chart</param> public JFreeChart getChart() { return chart; } }
Recommended reading:
Here Jfreechart provides DefaultPieDataset method to set static data and createPieChart() method creates the pie chart using the dataset.
struts.xml
To use the plugin, have your Struts configuration package extend the jfreechart-default package, which provides the chart result type.
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- package should extend jfreechart-default package --> <package name="default" namespace="/" extends="jfreechart-default"> <action name="displayChart" class="com.simplecodestuffs.action.JfreeChartAction"> <result name="success" type="chart"> <param name="value">chart</param> <param name="type">jpeg</param> <param name="width">600</param> <param name="height">400</param> </result> </action> </package> </struts>
Jsp page
<html> <head> <title>Struts2-Jfreechart integration</title> </head> <body> <h3>Struts2-Jfreechart integration</h3> <br /> <img src="displayChart"/> </body> </html>
In Jsp, servlet is called via img tag’s src attribute. This triggers the Action and render the image on the page.
** UPDATE: To Create Auto-Refreshing Pie Chart dynamically the following tutorial will help here.
Demo
Now right click on the project name and select Run As –> Run on Server.
|
Read More
Create Auto-Refreshing Pie Chart/Bar Chart in Servlet dynamically using JFreeChart
In this article we will learn about the step by step process of creating a pie chart in Servlet with values retrieved from database and displaying it in an auto-refreshing JSP page using JFreeChart library.
The JFreeChart is easiest and the most widely used library for creating a wide variety of good looking charts. In this post, we’ll learn to create pie chart using JFreeChart that can be returned as an image from a servlet. Here, I am going to retrieve data from database, create pie charts in a Servlet and display it using JSP.
Recommended reading
Pie Chart using YUI3 jquery chart plugin in Java web application
Struts2-Jfreechart integration
In order to sync the pie chart with values from a database that is frequently updated, I have written auto-refresh script which refresh the page automatically at regular intervals.
Libraries required :
jfreechart-x.x.x.jar
jcommon-x.x.x.jar
Download Jfreechart library from here.
Now let us create a sample table called ‘air_pollution’ in oracle database, that consists of the factors which causes air pollution and its percentage of emission.
create table air_pollution(source varchar(50), percentage int)
Here is the data contained in the above table
Now Create a New Dynamic Web Project in eclipse with following folder structure
Servlet
File : PieChartServlet.java
package com.simplecodestuffs.action; import java.io.IOException; import java.io.OutputStream; import java.sql.Connection; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.data.jdbc.JDBCPieDataset; import com.simplecodestuffs.jdbc.DataAccessObject; public class PieChartServlet extends HttpServlet { private static final long serialVersionUID = 1L; private Connection dbConnection = null; public PieChartServlet() { dbConnection = DataAccessObject.getConnection(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JDBCPieDataset dataSet = new JDBCPieDataset(dbConnection); try { dataSet.executeQuery("SELECT SOURCE,PERCENTAGE FROM AIR_POLLUTION ORDER BY PERCENTAGE"); JFreeChart chart = ChartFactory.createPieChart( "Source of Air Pollution ", // Title dataSet, // Data true, // Display the legend true, // Display tool tips false // No URLs ); chart.setBorderVisible(true); if (chart != null) { int width = 600; int height = 400; response.setContentType("image/jpeg"); OutputStream out = response.getOutputStream(); ChartUtilities.writeChartAsJPEG(out, chart, width, height); } } catch (SQLException e) { System.err.println(e.getMessage()); } } }
Recommended reading:
- AJAX implementation in Java web application using JQuery
- Dynamic Dependent Select Box in JSP & Servlet using JQuery and JSON via Ajax
Here Jfreechart provides JDBCPieDataSet method to retrieve appropriate data from database and createPieChart() method creates the pie chart with the populated dataset. writeChartAsJPEG() method is responsible for rendering the image in jpeg format.
Note :
Set the content type to the appropriate image format before trying to write it with the writeChartAs method. Here the content type is set as ‘image/jpeg’ since I have used writeChartAsJPEG() method.
DAO Class
Create utility class which connect to database Using Oracle JDBC driver
package com.simplecodestuffs.jdbc; import java.sql.Connection; import java.sql.DriverManager; public class DataAccessObject { private static Connection connection = null; public static Connection getConnection() { if (connection != null) return connection; else { // Store the database URL in a string String serverName = "127.0.0.1"; String portNumber = "1521"; String sid = "XE"; String dbUrl = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid; try { Class.forName("oracle.jdbc.driver.OracleDriver"); // set the url, username and password for the database connection = DriverManager.getConnection(dbUrl, "system", "admin"); } catch (Exception e) { e.printStackTrace(); } return connection; } } }
Web.xml
Make sure you have done servlet mapping properly in web.xml file as shown below
<servlet> <servlet-name>PieChartServlet</servlet-name> <servlet-class>com.simplecodestuffs.action.PieChartServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>PieChartServlet</servlet-name> <url-pattern>/displayChart</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>pieChart.jsp</welcome-file> </welcome-file-list>
Auto refresh Jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Pie Chart Demo</title> <script type="text/javascript"> function refreshPage() { document.forms.formId.submit(); } </script> </head> <body> <h3>Create Pie Chart Dynamically using JFreechart</h3> <% response.setIntHeader("Refresh", 10); %> <form id="formId"> <input type="button" onclick="refreshPage()" value="Refresh Page" /> <br /> <img src="displayChart" /> </form> </body> </html>
In Jsp, servlet is called via img tag’s src attribute, this triggers the servlet and render the image on the page.
To automate the page refreshing process, the following code is used
response.setIntHeader("Refresh",10);
which sends back header “Refresh” to the browser along with an value which indicates time interval in seconds. Here I set the time interval to 10 seconds, So the page will refresh and render updated data from database for every 10 seconds, this value can be set based on your requirement.
Note :
This automatic refreshing can cause a considerable performance impact since it hits database for every 10 second, so it is a good practice to have a ‘Refresh’ button to enable the end-users to decide on when to refresh the page.
Demo
Now right click on the project name and select Run As –> Run on Server.
Similarly to Create bar chart, replace the doGet method in the Servlet with the following code.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JDBCCategoryDataset dataset = new JDBCCategoryDataset(dbConnection); try { dataset.executeQuery("SELECT SOURCE,PERCENTAGE FROM AIR_POLLUTION ORDER BY PERCENTAGE"); JFreeChart chart = ChartFactory.createBarChart( "Source of Air Pollution", "Scource", "Percentage", dataset, PlotOrientation.VERTICAL, false, true, false); chart.setBorderVisible(true); if (chart != null) { int width = 600; int height = 400; response.setContentType("image/jpeg"); OutputStream out = response.getOutputStream(); ChartUtilities.writeChartAsJPEG(out, chart, width, height); } } catch (SQLException e) { System.err.println(e.getMessage()); } }
Demo
Bar chart – demo
|
Read More
Introduction to Hibernate
In this to we will learn about what hibernate is, and how to use hibernate in our application and its features.
What is hibernate ?
- It called as ORM tool (we will learn in subsequent tut)
- Used in the data layer to save date into the database
- Implements JPA (JPA is a set of standards which is prescribed for doing any operation in database.
1. Problem which Hibernate solves
Mapping member variables to column
Let take a Student class as an example, which has the following fields ID, Name, Department, Phone no, Address, Active.In a running application we may have lot of such objects, now to save the data in db; I need to create a Student table, in which I will save the Student objects as rows. So here N no of objects equal to N no of row in the table.
This implies that the class corresponds to the table and object of the class corresponds to the rows in the table. In java application, we will have a JDBC to connect to the db, and we will take this Student object, create an insert sql query and do an insert, Now all these data will be stored in db.
Now to select these data, we will create a select query to pull to the records and to store the records we will create a Student object to. So in Java we have data in form of objects, but there is no object in table, So java entity needs to be converted into a table entity, (i.e.) records.
The way we normally convert is by taking each of the values and map to its rows, this mapping is more tedious as we need to convert each object into SQL quires for saving, and for retrieving I have to convert a result set into corresponding java objects.
2. Mapping relationship
For example Student table has a column which is the primary key of another table (Address).
Here in java side care should be taken to map Student object to Student table and registration object to registration table.
3. Handling data types
Example:
To check whether the Student is active or not, in java side, we will create a Boolean variable which hold the value true or false, here in case of Database, we cannot have a column with type Boolean, for this scenario we can either have a char type or int type. So now we have to handle this data type conversion by ourselves.
4. Managing the changes to object state.
Suppose if we want to update any of the field n DB, then we have to pull the object from db, store it in Student object then write a java code to trigger update query.
The above 4 are the most common problem which we face in most of the java application. In our next article we shall learn to set up Hibernate in eclipse.
Read More
Setting up jQuery jTable plugin in Struts 2 framework
In this article we will learn to setup jTable and dependent libraries in Struts 2 web application. jTable is a jQuery plugin which is used to create AJAX based CRUD tables without coding HTML or Javascript, to know more about jTable please refer the article here
Steps done to set up our application for jTable
Libraries required for the setup,
- jQuery
- jQuery UI
- jTable
- struts2-json-plugin-2.x.x.jar
- Commonly required Struts 2 jars
Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
As show in the image download the required library mentioned and place it in js and css folder of eclipse work-space, and refer these files in the head section in the jsp as shown below.
Setup done from the browser perspective: jTable
jTable plugin allows you to issue an ajax request via jQuery plugin and expects a JSON object as a response, hence the following configuration needs to be made in Jsp file
Jsp Page
File : jTable.jsp
<html> <head> <title>jTable in Struts 2</title> <!-- jTable Metro theme --> <link href="css/metro/blue/jtable.css" rel="stylesheet" type="text/css" /> <link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" /> <!-- jTable script file. --> <script src="js/jquery-1.8.2.js" type="text/javascript"></script> <script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script> <script src="js/jquery.jtable.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $('#StudentTableContainer').jtable({ title : 'Students List', actions : { listAction : 'listAction' }, fields : { studentId : { title : 'Student Id', width : '30%', key : true, list : true, create : true }, name : { title : 'Name', width : '30%', edit : false }, department : { title : 'Department', width : '30%', edit : true }, emailId : { title : 'Email', width : '20%', edit : true } } }); $('#StudentTableContainer').jtable('load'); }); </script> </head> <body> <div> <h3>Integrating jTable jQuery plugin and Struts 2 framework</h3> <div id="StudentTableContainer"></div> </div> </body> </html>
As you can see, jTable just needs a div container as the only HTML tag. It fields options are explained below:
title: Title of the table.
actions: URLs of actions that are used to create/delete/update/list records.
fields: It defines the field names that represent columns of the record. Note that the field name should exactly match the instance variable defined in the model class.
Setup done from the server’s perspective: Struts 2 Action class
In the Action class, we are populating a list of type “Student”(Model). Since jTable accepts data only in Json format, so we are converting this List (Java Object) to Json(Javascript object Notation) format using struts2-json-plugin.jar.
**Update:: In the article AJAX implementation in Struts 2 using JQuery and JSON I have explained about usage of struts2-json-plugin.jar clearly, So if you are not aware of how struts2-json-plugin works, then please go thorough the above mentiioned link.
Action Class
package com.simplecodestuffs.action; import java.util.ArrayList; import java.util.List; import com.opensymphony.xwork2.Action; import com.simplecodestuffs.model.Student; public class JtableAction { private List<Student> records = new ArrayList<Student>(); private String result; public String list() { // Add data to Student list records.add(new Student(1, "Haripriya", "IT", "[email protected]")); records.add(new Student(2, "Dinesh", "ECE", "[email protected]")); records.add(new Student(3, "Prabhu", "MECH", "[email protected]")); records.add(new Student(4, "Badru", "ECE", "[email protected]")); records.add(new Student(5, "Lahir nisha", "CSC", "[email protected]")); records.add(new Student(6, "Nilafar nisha", "CSC", "[email protected]")); records.add(new Student(7, "Jamil", "ECE", "[email protected]")); records.add(new Student(8, "Mahes", "ECE", "[email protected]")); records.add(new Student(9, "Lourde", "IT", "[email protected]")); result = "OK"; return Action.SUCCESS; } public List<Student> getRecords() { return records; } public void setRecords(List<Student> records) { this.records = records; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
In case of read operations in jTable, Result property must be “OK” if operation is successful. If an error occurs, then Result property must be “ERROR”. If Result is “OK”, the Records property will contain an array of records defined in the servlet. If it’s ERROR, a Message property will contain an error message to show to the user. A sample return value for listAction is show below
{ "Result":"OK", "Records": [{ "studentId":1, "name":"Haripriya", "department":"IT", "emailId":"[email protected]" }] }
Model Class
Create the Model class which will have getters and setters for fields specified in jTable script.
package com.simplecodestuffs.model; public class Student { public Student() { } public Student(int studentId, String name, String department, String emailId) { super(); this.studentId = studentId; this.name = name; this.department = department; this.emailId = emailId; } private int studentId; private String name; private String department; private String emailId; public int getStudentId() { return studentId; } public String getName() { return name; } public String getDepartment() { return department; } public String getEmailId() { return emailId; } public void setStudentId(int studentId) { this.studentId = studentId; } public void setName(String name) { this.name = name; } public void setDepartment(String department) { this.department = department; } public void setEmailId(String emailId) { this.emailId = emailId; } }
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="json-default"> <action name="listAction" class="com.simplecodestuffs.action.JtableAction" method="list"> <result type="json">/jTable.jsp</result> </action> <action name="getJSONResult" class="com.simplecodestuffs.action.JtableAction" method="list"> <result type="json" /> </action> </package> </struts>
Since jTable accepts data only in Json format, So in order to convert java object to json object I have extended json-default package instead of struts-default package, please refer article here for more detail on json-default package.
Demo
On running the application i got the following response
Since I have not handled any exception, so the message displayed in error box is empty.
While debugging the error I found that the json response formed in struts application as below.
Hear the property names of jTable plugin are case sensitive. Only “Result”, “Records” and “Message” will work. In struts 2 the “json response” generated is in lower case["result", "records" and "message"], hence I edited the jtable.js to replace Result to result, Records to records and Message to message then it worked.
**Note: Along with the above keyword replace TotalRecordCount to totalRecordCount respectively, since this parameter will be used to display pagination count(Which I will implement in upcoming tutorial)
Now on including action for create, update and delete in jsp page as below
actions : { listAction : 'list', createAction : 'create', updateAction : 'update', deleteAction : 'delete' }
On running the application
On clicking ‘Add new record’
On clicking edit button
On clicking delete button
Note :
In the above program I have not included the logic for create, delete and update functions. In the article CRUD Operations in Struts 2 using jTable jQuery plugin via Ajax I have implemented CRUD operation using jTable jQuery plugin in Struts 2, and in the article Pagination in Struts 2 using jQuery jTable plugin I have implemented paging feature using the same plugin.
|
Reference
http://jtable.org/ApiReference