Pages Navigation Menu

Coding is much easier than you think

Setting up jQuery jTable plugin in Struts 2 framework

Posted by in jQuery, jTable, Struts 2 Tutorial, Struts-2 | 19 comments

 
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,

 
Now to start with demonstration of above topic, let us Create a Dynamic Web Project in Eclipse, with following project structure.
 
jTable in struts 2
 
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
 
Jtable exception
 
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.
get json result in Jtable
 
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)
 
jquery jtable in struts 2
 
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
Integrating jQuery jTable plugin with Struts2 framework
 
On clicking ‘Add new record’
Struts 2 using jTable jQuery plug-in - Create record
 
On clicking edit button
Struts 2 jTable jQuery plug-in - Update record
 
On clicking delete button
Struts 2 jTable jQuery plug-in - Delete record
 
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.
 

dwd2
Download It – jTableInStruts2

 

Reference

 
http://jtable.org/ApiReference
 

Read More

How to Override Default Theme in Struts 2 ?

Posted by in Struts 2 Tutorial, Struts-2

 

Struts 2 have theme generation functionality due to which it automatically generates Table based HTML code for its tags. This is due the default theme (x_html)
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Other themes are

  • simple
  • css_xhtml
  • ajax

 
You can change this theme setting to any other theme on tag level, page level or application level as shown below.

 
1. Tag Level

<s:submit name="clear" action="ClearFormAction" value="Clear" theme="simple" />

 
2. Page Level

a) Static value

<s:set name="theme" value="'simple'" scope="page"/>

 
b) Dynamic property

<s:set name="theme" value="%{myTheme}" scope="page"/>

 

3. Application Level

<constant name="struts.ui.theme" value="simple"/>

 

Read More

Changing default style of s:actionerror / s:actionmessage tag

Posted by in Struts 2 Tutorial, Struts-2

 
In struts 2 when you use <s:actionerror /> tag, it displays the errors with bullets, On viewing the page source of the jsp page, we can see that error message is displayed using
 

<ul>
<li>error 1</li>
<li>error 2</li>
</ul>

 
But suppose if our requirement is to display the error message without bullet in the action errors or action messages
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
There are 2 ways to solve this problem
 
1. Customized the code in jsp, such that you can specify your own css for displaying the message
 

<s:if test="hasActionErrors()">
<s:iterator value="actionErrors">
<span class="msg"><s:property escape="false" />
</span>
</s:iterator>
</s:if>

 
2. Change the file in the “/template/simple/actionerror.ftl” and put it in the /web-directory/struts/simple if you are using simple theme
 

Similar kind of approach is followed for <s:actionmessage /> tag.

Read More

How to get checkbox values from displaytag using struts2

Posted by in Display Tag, Struts 2 Tutorial, Struts-2

 
Consider a scenario, such that we have a list of items and each item can be selected by checking its checkbox. Then a submit button is clicked after selecting all necessary checkboxes. So now, in our Action class, we could get the values of checkboxes which had been selected, by which we can implement delete functionality.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 

The following snippet of code is used to retrieve the value from a checkbox used inside displaytag.

 

<display:table name="productList" pagesize="10" requestURI="productAction" id="row">

<display:column title="Delete">
<s:checkbox name="productList[%{#attr.row_rowNum - 1}].chkBox"
  id="check%{#attr.row_rowNum - 1}" value="%{#attr.row.chkBox}"/>
</display:column>

<display:column property="product" title="Product Name"/>
<display:column property="price" title="Price"/>

</display:table>
<s:submit action="removeProduct" value="Delete"
  onClick="return confirm('Do you want to delete these items?');"/>

 
In our Action class, we can get the values of checkbox by creating getter & setter for the field “chkBox”.
 

Read More

Struts 2 tag not working in Display tag – Solution

Posted by in Display Tag, Struts 2 Tutorial, Struts-2

 
Consider a scenario, such that you want to display a value of a column based on certain condition.
 
For example:
 
if a student’s marks is greater than 50 display as ‘pass’, if its less than 50 then display as ‘fail’. For this scenario, in a display tag, most of us result in the following code snippet.
 


<display:table name="ranklist" id="row" pagesize="10"  requestURI="rankAction" >

<s:if test="%{mark > 50}">
<display:column title="Status">Pass</display:column>
</s:if>
<s:elseif test="%{mark < 50}">
<display:column title="Status">Fail</display:column>
</s:elseif>

</display:table>

 
But here unfortunately this code does not works, because the variable “mark”is not reachable inside the display tag, since it is not associated with current display table.
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
Solution :
 
So the correct way of coding is:
 

<display:table name="ranklist" id="row" pagesize="10"  requestURI="rankAction" >

<display:column property="userName" title="User Name" />

<s:if test="%{#attr.row.mark > 50}">
<display:column title="Status">Pass</display:column>
</s:if>

<s:elseif test="%{#attr.row.mark < 50}">
<display:column title="Status">Fail</display:column>
</s:elseif>

</display:table>

 
Generalized way to access the struts 2 tag via display tag is :- #attr.tableIdName.tableField. So the only way to access a struts 2 tag inside displaytag, is to follow the above syntax.
 
Example : To access a property tag inside display tag :

<s:property name="userId" value="#attr.row.userId" />

 

Read More

Concept of Servlets Vs Concept of Struts 2

Posted by in Java, Servlet, Struts 2 Tutorial, Struts-2 | 2 comments

 
In this article we will discuss about the conceptual difference between Servlets and Struts 2
 
** UPDATE: Struts 2 Complete tutorial now available here.
 
In case of Servlet when we have N number of request then only one object is created out of which N number of Threads are created , in which a request object is created. So the objects inside the thread are safe and not shared with other thread objects.
 
But suppose if the Servlet has Member variable, then those variable are not thread safe, as they are shared between all the threads created for each request.

The above concept is depicted pictographically below.
 
Servlets - Struts 1 Concepts
 

Note: Servlet & Struts 1 follows same concept.

 

In case of struts 2 for N number of request N number of object is created. So in this case, even the member variable for these objects are not shared between objects of other request, that the reason Struts 2 is said to be thread safe.
 

The concept of Struts 2 is depicted pictographically as below.
 
Struts 2 Concepts
 

Read More
Page 1 of 712345...Last»