Tuesday, October 25, 2011

A website architecture using Tiles, DWR and Hibernate

Goal: Create a simple architecture using Java/JEE technology/frameworks which can be used to develop websites quickly.


Technology Used: 
   1. JSP, Apache Tiles, HTML, CSS, JavaScript : Render user interface, 
       Use Tiles template. 
       (http://tiwarij2eeblog.blogspot.com/2011/10/using-tiles-2-without-struts.html).
   2. DWR (Ajax Framework): Fetch data from server and render on UI using 
       javaScript.
   3. Hibernate: Add/Update/Search Data from Database.





Tuesday, October 11, 2011

Pagination Using Struts 2 and Hibernate 3.0

This blogs tell how to do pagination using Struts 2.0, Spring 3.0 and Hibernate 3.0 step by step. This blog is extension of http://tiwarij2eeblog.blogspot.com/2011/09/storing-and-retrieving-images-in-db.html. Here we will create search page which will display results with pagination.


Step 1: Setup eclipse as per above link and add some data to DB.
Step 2: Create anew Java bean as below



public class UserSearchBean {


private int selectedPageNumber;
private int totalPages;
private int serialNumberAddfactor;
private int noOfRecordsPerPage = 3; // Default


private String from;


// Search creteria
private String firstName;
private String lastName;


private List<User> selectedUserList;


       // Write Setters and getters


Step 3: Create a new java Action class as below



package org.paandav.blog.action;


import org.paandav.bolg.service.UserService;


import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;


public class SearchUserAction extends ActionSupport implements
ModelDriven<UserSearchBean> {


private static final long serialVersionUID = 1L;
private UserSearchBean model = new UserSearchBean();
private UserService userService;


public UserService getUserService() {
return userService;
}


public void setUserService(UserService userService) {
this.userService = userService;
}


public void setModel(UserSearchBean model) {
this.model = model;
}


@Override
public String execute() throws Exception {
if (!"INIT".equals(getModel().getFrom())) {
userService.getPaginatedResultForUserSearch(getModel());
}
return INPUT;
}


@Override
public UserSearchBean getModel() {
return model;
}


}


Step 4: Create new method getPaginatedResultForUserSearch in UserService.java and write implementation as below

UserService.java
UserSearchBean getPaginatedResultForUserSearch(UserSearchBean usb)
throws Exception;
UserServiceImpl.java
@Override
public UserSearchBean getPaginatedResultForUserSearch(UserSearchBean usb)
throws Exception {
return userDao.getPaginatedResultForUserSearch(usb);
}

Step 5: Create new method UserDAO and implement it as belwo

UserDAO.java
UserSearchBean getPaginatedResultForUserSearch(UserSearchBean usb)
throws Exception;

UserDAOImpl.java

@Override
public UserSearchBean getPaginatedResultForUserSearch(UserSearchBean usb)
throws Exception {

List<User> selectedUser = null;
Criteria crit = getCreteria(usb);
int totalNoOfRecords = (Integer) crit.setProjection(
Projections.rowCount()).uniqueResult();
int startIndex = 0;
int totalPages = 1;

if (totalNoOfRecords > usb.getNoOfRecordsPerPage()) {
double noOfPages = (double) totalNoOfRecords
/ (double) usb.getNoOfRecordsPerPage();
totalPages = (int) noOfPages;
if (noOfPages % totalPages > 0.0) {
totalPages++;
}
}

if (usb.getSelectedPageNumber() > 1) {
startIndex = usb.getNoOfRecordsPerPage()
* (usb.getSelectedPageNumber() - 1);
usb.setSerialNumberAddfactor(usb.getNoOfRecordsPerPage()
* (usb.getSelectedPageNumber() - 1));
}

usb.setTotalPages(totalPages);

crit = getCreteria(usb);
crit.setFirstResult(startIndex);
crit.setMaxResults(usb.getNoOfRecordsPerPage());

selectedUser = crit.list();
usb.setSelectedUserList(selectedUser);

return usb;
}

private Criteria getCreteria(UserSearchBean usb) {
Criteria criteria = getSession().createCriteria(User.class);
if (usb.getFirstName() != null && !"".equals(usb.getFirstName())) {
criteria.add(Restrictions.ilike("firstName", usb.getFirstName()));
}
if (usb.getLastName() != null && !"".equals(usb.getLastName())) {
criteria.add(Restrictions.ilike("lastName", usb.getLastName()));
}

return criteria;
}


Step 6: Now create a new actiom mapping in struts.xml as below

<action name="searchUser" class="org.paandav.blog.action.SearchUserAction">
<result name="input">
WEB-INF/jsp/userSearchPage.jsp
</result>
</action>
Step 7: Now create anew jsp file userSearchPage.jsp as below
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

</head>
<body style="font-family: verdana;">
<s:form action="searchUser" theme="simple">
<table align="center" border=1>
<tr bgcolor="aqua">
<td>First Name <s:textfield name="firstName"></s:textfield></td>
<td>Last Name <s:textfield name="lastName"></s:textfield></td>
<td colspan="3"><s:submit value="Search User"></s:submit></td>
</tr>
<s:if test="totalPages > 1">
<tr bgcolor="lightgrey">
<td colspan="5">Page No :<s:iterator value="totalPages.{#this}"
status="stat">
<s:submit value="%{#stat.count}" name="selectedPageNumber"></s:submit>
</s:iterator></td>
</tr>
</s:if>
<s:if test="selectedUserList != null && selectedUserList.size > 0">
<tr bgcolor="aqua">
<th>S.N</th>
<th>First Name</th>
<th>Last Name</th>
<th>Content type</th>
<th>File Name</th>
</tr>
<s:iterator value="selectedUserList" status="stat">
<tr bgcolor="#FFF288">
<td><s:property value="#stat.count + serialNumberAddfactor" /></td>
<td><s:property value="firstName" /></td>
<td><s:property value="lastName" /></td>
<td><s:property value="conTentType" /></td>
<td><s:property value="fileName" /></td>
</tr>
</s:iterator>
</s:if>
</table>
</s:form>
</body>
</html>

Step 9: Now start the server and access the URL

You will see a screen like below


Now if you don't fill any data in boxes it will display all data in table with pagination like belwo




Now you can try with filling some criteria and search.


Saturday, October 8, 2011

Using Tiles 2 without Struts

Sometimes we need tiles functionality and don't want to use Struts. Tiles is very useful when we want to use data access by other frameworks like DWR. This blog displays step by step procedure for using Apache Tiles 2 Without Struts.


Step 1: Create a new dynamic web project in eclipse and put the below jar files to WEB-INF/lib folder (you can exclude dwr jar files).




Step 2: Now configure the tiles listener and tiles servlet in web.xml file as below.



<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
                </param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
</listener>
<servlet>
<servlet-name>Tiles Dispatch Servlet</servlet-name>
<servlet-class>org.apache.tiles.web.util.TilesDispatchServlet</servlet-class>
</servlet>
<servlet-mapping> 
         <servlet-name>Tiles Dispatch Servlet</servlet-name> 
         <url-pattern>*.tiles</url-pattern> 
</servlet-mapping>

Step 3: Now create a template jsp file like below template.jsp in WebContent folder

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Test</title>
</head>
<body style="font-family: verdana;">
<table align="center" border=0 height="100%" width="100%">
<tr height="5%">
<td><tiles:insertAttribute name="header" /></td>
</tr>
<tr height="5%">
<td><tiles:insertAttribute name="menu" /></td>
</tr>
<tr height="75%">
<td><tiles:insertAttribute name="body" /></td>
</tr>
<tr height="5%" >
<td><tiles:insertAttribute name="footer" /></td>
</tr>
</table>
</body>
</html>

Step 4: Create folur other jsp  files like header.jsp, menu.jsp, home.jsp and footer.jsp in WebContent folder

Step 5: Now create a tiles.xml file inside WEB-INF folder and create template and other pages like below

<?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="outerLayout" template="teplate.jsp">
<put-attribute name="header" value="header.jsp" />
<put-attribute name="menu" value="menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="footer.jsp" />
</definition>
<definition name="homePage" extends="outerLayout">
<put-attribute name="body" value="home.jsp" />
</definition>
</tiles-definitions>

Step 6: Now start web-server and use the URL like 

http://localhost:8080/TGReality/homePage.tiles

all the pages will be called by using the name of tiles definition like homePage.tiles.

don't change *.tiles in web.xml.