Developing Struts Web Module

In this we will be creating search interface for enabling the user to search tutorials. This example is an client to test our Struts Hibernate Plugin.


The web component of the application consists of the following files:


1. Search Tutorial Form (SearchTutorial.jsp):


This file is used to display the search form to the user. Here is the code of search form:






<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>

<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<html:html locale=”true”>
<head>
<title><bean:message key=”welcome.title”/></title>
<html:base/>
</head>
<body bgcolor=”white”>

<html:form action=”/searchTutorial”>

<html:errors/>

<table>

<tr>
<td align=”right”>
Search Tutorial
</td>
<td align=”left”>
<html:text property=”keyword” size=”30″ maxlength=”30″/>
</td>
</tr> 
<tr>
<td align=”right”>
<html:submit>Search</html:submit>
</td>
</tr>
</table>
</html:form>
</body>
</html:html>


Save SearchTutorial.jsp in to “C:\Struts-Hibernate-Integration\code\pages” directory.


2. Search Result Page (SearchResultPage.jsp)
This page is used to display the search result. Here is the code of search result page:






        <%@page language=”java” import=”java.util.*”%>
<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<p><font size=”4″ color=”#800000″ face=”Arial”>Search Results</font></p>

<%
List searchresult = (List) request.getAttribute(“searchresult”);
%>
<%
for (Iterator itr=searchresult.iterator(); itr.hasNext(); )
{
roseindia.net.dao.hibernate.Tutorial tutorial =
(roseindia.net.dao.hibernate.Tutorial)itr.next();
%>
<p><a href=”<%=tutorial.getPageurl()%>”>
<font face=”Arial” size=”3″><%=tutorial.getShortdesc()%></font></a><br>
<font face=”Arial” size=”2″><%=tutorial.getLongdesc()%></font></p>

<%
}
%>
<html:link page=”/pages/SearchTutorial.jsp”>Back to Search Page</html:link>


Save SearchResultPage.jsp in to “C:\Struts-Hibernate-Integration\code\pages” directory.


3. Search Java Form (SearchTutorialActionForm.java)
This is the Struts action form class. Here is the code of the Action Form:






package roseindia.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.*;

public class SearchTutorialActionForm extends ActionForm
{
  private String keyword=null;

public void setKeyword(String keyword){
    this.keyword=keyword;
  }

  public String getKeyword(){
    return this.keyword;
  }

   public void reset(ActionMapping mapping, HttpServletRequest request) {
    this.keyword=null;
    }
   public ActionErrors validate
      ActionMapping mapping, HttpServletRequest request ) {
      ActionErrors errors = new ActionErrors();
      
      ifgetKeyword() == null || getKeyword().length() ) {
        errors.add(“keyword”,new ActionMessage(“error.keyword.required”));
     }

      return errors;
  }

}

 4. Search Action Class (SearchTutorialAction.java)


This is Struts Action Class of our application. Here is the code of the Action Class:






package roseindia.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;

import java.util.List;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import roseindia.net.plugin.HibernatePlugIn;

import roseindia.net.dao.hibernate.Tutorial;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.Criteria;



public class SearchTutorialAction extends Action
{
  public ActionForward execute(
    ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse responsethrows Exception{
  SearchTutorialActionForm formObj = (SearchTutorialActionForm)form;

   System.out.println(“Getting session factory”);
   /*Get the servlet context */
   ServletContext context = request.getSession().getServletContext();
   /*Retrieve Session Factory */
   SessionFactory _factory = (SessionFactory)  
   context.getAttribute
(HibernatePlugIn.SESSION_FACTORY_KEY);
   /*Open Hibernate Session */
   Session  session = _factory.openSession();
     //Criteria Query Example
     Criteria crit = session.createCriteria(Tutorial.class);
     crit.add(Restrictions.like(“shortdesc”“%” + formObj.getKeyword() +“%”))//Like condition

   //Fetch the result from database
   List tutorials= crit.list();
   request.setAttribute(“searchresult”,tutorials);
   
    /*Close session */
      session.close();
    System.out.println(“Hibernate Session Closed”);
      return mapping.findForward(“success”);
  }
}

5. Entries into struts-config.xml


Add the following lines into your struts-config.xml file.


Form Bean: 
<form-bean
name=”TutorialSearch”
type=”roseindia.web.SearchTutorialActionForm”>
</form-bean>


Action Entry:
<action
path=”/searchTutorial”
type=”roseindia.web.SearchTutorialAction”
name=”TutorialSearch”
scope=”request”
validate=”true”
input=”/pages/SearchTutorial.jsp”>
<forward name=”success” path=”/pages/SearchResultPage.jsp”/>
</action>


Now we have created all the required stuffs for the web client. In the next section we will test our application.


Developing Struts Hibernate Plugin

In this section we will develop java code for Struts Hibernate Plugin. Our Hibernate Plugin will create Hibernate Session factory and cache it in the servlet context. This strategy enhances the performance of the application.


Source Code Of Hibernate Struts Plugin:






package roseindia.net.plugin;

import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;


public class HibernatePlugIn implements PlugIn {
   private String _configFilePath = “/hibernate.cfg.xml”;

    /**
     * the key under which the <code>SessionFactory</code> instance is stored
     * in the <code>ServletContext</code>.
     */
    public static final String SESSION_FACTORY_KEY 
            = SessionFactory.class.getName();

  private SessionFactory _factory = null;

   public void destroy() {
     try{
       _factory.close();
     }catch(HibernateException e){
      System.out.println(“Unable to close Hibernate Session Factory: ” + e.getMessage());
     }
       
   }

   public void init(ActionServlet servlet, ModuleConfig configthrows ServletException {
     System.out.println(“*************************************”);
   System.out.println(“**** Initilizing HibernatePlugIn   **********”);
        Configuration configuration = null;
        URL configFileURL = null;
        ServletContext context = null;

   try{
            configFileURL = HibernatePlugIn.class.getResource(_configFilePath);
            context = servlet.getServletContext();
            configuration = (new Configuration()).configure(configFileURL);
            _factory = configuration.buildSessionFactory();
      //Set the factory into session
      context.setAttribute(SESSION_FACTORY_KEY, _factory);

   }catch(HibernateException e){
    System.out.println(“Error while initializing hibernate: ” + e.getMessage());
   }
   System.out.println(“*************************************”);

   }

    /**
     * Setter for property configFilePath.
     @param configFilePath New value of property configFilePath.
     */
    public void setConfigFilePath(String configFilePath) {
        if ((configFilePath == null|| (configFilePath.trim().length() == 0)) {
            throw new IllegalArgumentException(
                    “configFilePath cannot be blank or null.”);
        }
        
        System.out.println(“Setting ‘configFilePath’ to ‘”  + configFilePath + “‘…”);
        _configFilePath = configFilePath;
    }


/*(SessionFactory) servletContext.getAttribute
(HibernatePlugIn.SESSION_FACTORY_KEY);
*/
  
}


In our plugin class we have define a variable _configFilePath to hold the name of Hibernate Configuration file.


private String _configFilePath = “/hibernate.cfg.xml”;


Following code define the key to store the session factory instance in the Servlet context.


public static final String SESSION_FACTORY_KEY = SessionFactory.class.getName();


The init() is called on the startup of the Struts Application. On startup the session factory is initialized and cached in the Servlet context.


configFileURL = HibernatePlugIn.class.getResource(_configFilePath);
context = servlet.getServletContext();
configuration = (new Configuration()).configure(configFileURL);
_factory = configuration.buildSessionFactory();
//Set the factory into session
context.setAttribute(SESSION_FACTORY_KEY, _factory);


Changes to be done in struts-config.xml file


Configuring Hibernate with Struts is very simple work it requires you to have hibernate.cfg.xml in your WEB-INF/classes directory, and to add the following line to the struts-config.xml file.


<plug-in className=”roseindia.net.plugin.HibernatePlugIn”></plug-in>


Testing the Plugin


Build your application and deploy on the tomcat server. Start tomcat server and observe the console output. It should display the following line:






 
 log4j:WARN Please initialize the log4j system properly.
*************************************
**** Initilizing HibernatePlugIn **********
*************************************
Aug 7, 2006 10:09:53 AM org.apache.struts.tiles.TilesPlugin initD
  

This means you have successfully configured your Struts Hibernate Plugin with struts application.


Writing Hibernate Configuration Files

In the previous section we completed the database setup and created required table and populated with the data. In this section we will write required hibernate configuration files.


For this tutorial we need following Hibernate configuration files:


Hibernate Configuration File


Hibernate configuration file (hibernate.cfg.xml) is used to provide the information which is necessary for making database connections. The mapping details for mapping the domain objects to the database tables are also a part of Hibernate configuration file. 


Here is the code of our Hibernate Configuration File:






<?xml version=’1.0′ encoding=’utf-8′?>
<!DOCTYPE hibernate-configuration PUBLIC
“-//Hibernate/Hibernate Configuration DTD//EN”
“http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”>

<hibernate-configuration>
<session-factory>
<property name=”hibernate.connection.driver_class”>com.mysql.jdbc.Driver</property>
<property name=”hibernate.connection.url”>jdbc:mysql://localhost/struts-hibernate</property>
<property name=”hibernate.connection.username”>root</property>
<property name=”hibernate.connection.password”></property>
<property name=”hibernate.connection.pool_size”>10</property>
<property name=”show_sql”>true</property>
<property name=”dialect”>org.hibernate.dialect.MySQLDialect</property>
<property name=”hibernate.hbm2ddl.auto”>update</property>
<!– Mapping files –>
<mapping resource=”/roseindia/net/dao/hibernate/Tutorial.hbm.xml”/>
</session-factory>
</hibernate-configuration> 

 


Place hibernate.cfg.xml file in the source directory e.g. “C:\Struts-Hibernate-Integration\code\src\java”


The <mapping resource=”> tag is used to specify the mapping file:


<mapping resource=”/roseindia/net/dao/hibernate/Tutorial.hbm.xml”/>


Code of Tutorial.hbm.xml:






 <?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE hibernate-mapping PUBLIC “-//Hibernate/Hibernate Mapping DTD//EN”
“http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”>

<hibernate-mapping auto-import=”true” default-lazy=”false”>

<class 
name=”roseindia.net.dao.hibernate.Tutorial” 
table=”tutorials”
>

<id
name=”id”
type=”java.lang.Integer”
column=”id”
>
<generator class=”increment” />
</id>

<property
name=”shortdesc”
type=”java.lang.String”
column=”shortdesc”
not-null=”true”
length=”50″
/>
<property
name=”longdesc”
type=”java.lang.String”
column=”longdesc”
not-null=”true”
length=”250″
/>
<property
name=”pageurl”
type=”java.lang.String”
column=”pageurl”
not-null=”true”
length=”100″
/>


</class>
</hibernate-mapping>

Place Tutorial.hbm.xml file in the source directory e.g. “C:\Struts-Hibernate-Integration\code\src\java\roseindia\net\dao\hibernate\” 


POJO Object
Here is the code of Java Bean object (Tutorial.java) used to store and retrieve the data from database.






package roseindia.net.dao.hibernate;

import java.io.Serializable;


public class Tutorial implements Serializable {

    /** identifier field */
    private Integer id;

    /** persistent field */
    private String shortdesc;

    /** persistent field */
    private String longdesc;

    /** persistent field */
    private String pageurl;

    /** full constructor */
    public Tutorial(Integer id, String shortdesc, String longdesc, String pageurl) {
        this.id = id;
        this.shortdesc = shortdesc;
        this.longdesc = longdesc;
        this.pageurl = pageurl;
    }

    /** default constructor */
    public Tutorial() {
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getShortdesc() {
        return this.shortdesc;
    }

    public void setShortdesc(String shortdesc) {
        this.shortdesc = shortdesc;
    }

    public String getLongdesc() {
        return this.longdesc;
    }

    public void setLongdesc(String longdesc) {
        this.longdesc = longdesc;
    }

    public String getPageurl() {
        return this.pageurl;
    }

    public void setPageurl(String pageurl) {
        this.pageurl = pageurl;
    }

}

In this section we have created all the Hibernate related stuffs.


Downloading Struts & Hibernate


In this we will download Struts & Hibernate and setup the development environment.


Downloading Hibernate


Hibernate is free open source software it can be download from http://www.hibernate.org/. Visit http://www.hibernate.org/ and then click on the Download link to go to the download page. From the download page download the current latest release of Hibernate Core. For this tutorial I have downloaded Hibernate hibernate-3.1.1.zip.


Download Struts


The latest release of Struts can be downloaded from http://struts.apache.org/download.cgi. For this tutorial I have download struts-1.2.9-bin.zip. Save downloaded file into your hard disk.


Downloading Ant


Ant is a free tool under GNU Licence and is freely available at http://jakarta.apache.org/ant/ , current version of ant is 1.6.5. Ant allows the developer to automate the repeated process involved in the development of J2EE application. Developers can easily write the script to automate the build process like compilation, archiving and deployment. For this tutorial I am using apache-ant-1.6.5.


Download MySQL JDBC Driver
Download mysql-connector-java-3.0.16-ga-bin.jar from here mysql-connector-java or you can download and use the latest version of mysql jdbc driver. Copy the JDBC driver file (mysql-connector-java-3.0.16-ga-bin.jar or latest version) to the jakarta-tomcat-5.5.9\common\lib directory of your tomcat installation. This will add the MySQL JDBC driver to the tomcat server.


Setting Up Development Environment


First we will create necessary directories and moved the required files to the appropriate directory. Follow the following steps to accomplish this:



  1. Create a directory in you c: drive called Struts-Hibernate-Integration.
      
  2. Unzip Downloaded file in the directory you have downloaded Struts.
      
  3. Go to the “struts-1.2.9-bin\webapps” directory and you will find struts-blank.war, struts-documentation.war, struts-examples.war, struts-mailreader.war and tiles-documentation.war files in the directory. Open struts-blank.war with WinZip and then click on the “Extract” button. WinZip asks for the directory for extracting the file, enter “C:\Struts-Hibernate-Integration” and click on Extract button.

      
  4. A new directory will created “C:\Struts-Hibernate-Integration\code” and the content of struts-blank.war is extracted in the code directory.
      
  5. Now we will add the hibernate code to our development environment. Extract hibernate-3.1.1.zip in the directory where you have downloaded. 
       
  6. Copy “hibernate3.jar” from <your downoaded direvory>\hibernate-3.1  into C:\Struts-Hibernate-Integration\code\WEB-INF\lib directory.
       
  7. Copy all the library files from “hibernate-3.1\lib” to “C:\Struts-Hibernate-Integration\code\WEB-INF\lib” directory.
      
  8. Create an directory libext under “C:\Struts-Hibernate-Integration\code\WEB-INF\” . We will used this directory to put extra jar files. Copy servlet-api.jar file your tomcat directory to “C:\Struts-Hibernate-Integration\code\WEB-INF\libext” directory. 
      
  9. Change in the build.xml file: Open “C:\Struts-Hibernate-Integration\code\WEB-INF\src\build.xml” file in your favourite editor and change as instructed below:
    a) Find “<property name=”servlet.jar” value=”/javasoft/lib/servlet.jar”/>” in the build.xml file and change it to “<property name=”servlet.jar” value=”./libext/servlet-api.jar”/>
    b) Find “<property name=”distpath.project” value=”/projects/lib”/>” and change it to “<property name=”distpath.project” value=”../../dist”/>
    c) Change “<property name=”jdbc20ext.jar” value=”/javasoft/lib/jdbc2_0-stdext.jar”/>” to “<property name=”jdbc20ext.jar” value=”./libext/jdbc2_0-stdext.jar”/>“.
    d) Change “<property name=”project.title” value=”Jakarta Struts Blank “/>” to “<property name=”project.title” value=”RoseIndia.net Struts Hibernate Integration Tutorial “/>
    e) Change “<property name=”project.distname” value=”blank”/>” to “<property name=”project.distname” value=”strutshibernate”/>
    e) Change “<target name=”project” depends=”clean,prepare,compile,javadoc”/>” to “<!–<target name=”project” depends=”clean,prepare,compile”/>–>
    You can download my build.xml fom here.
      
  10. Open console and go to the “C:\Struts-Hibernate-Integration\code\WEB-INF\src” directory  and type ant to compile the project. This show the following out put:

    C:\Struts-Hibernate-Integration\code\WEB-INF\src>ant
    Buildfile: build.xml

    clean:
    [delete] Deleting directory C:\Struts-Hibernate-Integration\code\WEB-INF\clas
    ses
    [mkdir] Created dir: C:\Struts-Hibernate-Integration\code\WEB-INF\classes

    prepare:

    resources:
    [copy] Copying 1 file to C:\Struts-Hibernate-Integration\code\WEB-INF\class
    es

    compile:

    project:

    dist:
    [jar] Building jar: C:\Struts-Hibernate-Integration\dist\strutshibernate.j
    ar
    [war] Building war: C:\Struts-Hibernate-Integration\dist\strutshibernate.w
    ar
    [war] Warning: selected war files include a WEB-INF/web.xml which will be
    ignored (please use webxml attribute to war task)

    all:

    BUILD SUCCESSFUL
    Total time: 3 seconds
    C:\Struts-Hibernate-Integration\code\WEB-INF\src>


    and it will create C:\Struts-Hibernate-Integration\dist\strutshibernate.war file which you can deploy on application server to test. You can ignore the warning generated while running the ant build tool.
       
  11. To test the application copy the strutshibernate.war to your tomcat webapps dirctory and start tomcat.
      
  12. Open browser and type http://localhost:8080/strutshibernate/. You browser page should look like: 
      

      
    This means you have successfully configured your development environment.

Setting up MySQL Database and Tables

I am assuming that you have running instance of MySQL Database and you know how to work with the MySQL database. To access the database you should have valid user name and password. 


Let’s now start by creating the database for our struts- hibernate integration tutorial. Our application is very very simple and it searches for the keywords typed by user in the table. The database will contain one table ‘tutorials’ for holding the tutorials links and descriptions. Here is the complete sql script for setting up the database.






 CREATE DATABASE `struts-hibernate` ;

CREATE TABLE `tutorials` (

`id` INT NOT NULL AUTO_INCREMENT ,
`shortdesc` VARCHAR( 50 ) NOT NULL ,
`longdesc` VARCHAR( 250 ) NOT NULL ,
`pageurl` VARCHAR( 100 ) NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM ;

The above table holds the short description, long description and url of the tutorials. The field ‘id‘ is the unique identifier for records in the articles table.


Here are the details of the each of the fields in the table:


id: Unique key for the table


shortdesc: This fields stores the short description of the tutorial.


longdesc: This field stores the full description about the tutorial


pageurl: This field is stores the url of the tutorial


Run the following query to populate table with tutorials data:






INSERT INTO `tutorials` VALUES (1, ‘JSP Tutorials, Hibernate and struts Tutorials’, ‘This site contains many quality Java, JSP Tutorials, Hibernate Tutorials, Struts Tutorials, JSF Tutorials, RMI, MySQL Tutorials, Spring Tutorials, source codes and links to other java resources. We have large number of links to the tutorials on java’, ‘http://roseindia.net/’);


INSERT INTO `tutorials` VALUES (2, ‘JSP Tutorial’, ‘Java Server Pages or JSP for short is Sun”s solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications.’, ‘http://www.roseindia.net/jsp/jsp.shtml’);



INSERT INTO `tutorials` VALUES (3, ‘Struts Tutorials – Jakarta Struts Tutorial’, ‘This complete reference of Jakarta Struts shows you how to develop Struts applications using ant and deploy on the JBoss Application Server. Ant script is provided with the example code. Many advance topics like Tiles, Struts Validation Framework, Ja’, ‘http://www.roseindia.net/struts/index.shtml’);



INSERT INTO `tutorials` VALUES (4, ‘The Complete Spring Tutorial’, ‘Spring is grate framework for development of Enterprise grade applications. Spring is a light-weight framework for the development of enterprise-ready applications. Spring can be used to configure declarative transaction management, remote access to’, ‘http://www.roseindia.net/spring/index.shtml’);



INSERT INTO `tutorials` VALUES (5, ‘Java Server Faces (JSF) Tutorial’, ‘JavaServer Faces or JSF is grate technology for the development of user interfaces for web applications. The Java Server Faces specification is defined by JSR 127 of the Java Community Process.’, ‘http://www.roseindia.net/jsf/’);



INSERT INTO `tutorials` VALUES (6, ‘Jboss 3.0 Tutorial’, ‘ This lesson shows you how to build you web application and install on the Jboss 3.0 application server. After the completion of this lesson you will be able to compile, assemble and deploy your J2EE application on Jboss 3.0 application server.’, ‘http://www.roseindia.net/jboss/index.shtml’);


In the above steps we have setup our database. In the next section we will write java stuffs to integrate struts and hibernate.


 


Struts Hibernate Integration

In this tutorial I will show you how to integrate Struts and Hibernate. After completing this tutorial you will be able to use Hibernate in your Struts project. We will be using Hibernate Struts plug-in to write high performance application using Struts and Hibernate.


Hibernate is Object-Oriented mapping tool that maps the object view of data into relational database and provides efficient persistence services such as create, read, update and delete (CRUD).


In this tutorial we will implement small search engine application that shows a search form to the user. User enters search string and presses search button. Struts framework process the request and passes it to the action for further processing. Action class uses Hibernate to make database calls and retrieves matching records from database and results are displayed to the user.


Full example code is provided with the tutorial and you can download and start working on it for your project or to learn Struts and Hibernate Integration. You can download the source code from here.



  1. Setting up MySQL Database and table
    This section describes how to setup database and populate it with the data. We are using MySQL Database for this tutorial.
      
  2. Downloading Struts, Hibernate and Integrate It
    This section explains you to setup the develop workbench for our Struts Hibernate tutorial
      
  3. Writing Hibernate configuration file, POJO class and Tutorial.hbm.xml (Hibernate mapping class)
    In this section we will write required hibernate objects like configuration files and then integrate all the stuffs.
      
  4. Developing Hibernate Struts Plugin
    In this section we will write Hibernate Struts Plugin Java code and integrate it with the Struts.
     
  5. Writing Web Client to Search the database using Struts Hibernate Plugin
    In this section we will write web client to test struts Plugin. We will be developing a search form to search the tutorials from the table.
     
  6. Build and testing the application
    In this section we will build our Struts Hibernate Plugin Application and then test.

Struts 2 Tutorials

Struts 2 Tutorials



  1. Introduction to Struts 2
    Introduction to Struts 2 framework.

Struts Hibernate Integration Tutorial NEW
In this tutorial I will show you how to integrate Struts and Hibernate. After completing this tutorial you will be able to use Hibernate in your Struts project. Download the source code of Struts Hibernate Integration Tutorial.



  1. Struts Hibernate Integration Tutorial
    In this tutorial I will show you how to integrate Struts and Hibernate. After completing this tutorial you will be able to use Hibernate in your Struts project. We will be using Hibernate Struts plug-in to write high performance application using Struts and Hibernate
      
  2. Setting up MySQL Database and table
    This section describes how to setup database and populate it with the data. We are using MySQL Database for this tutorial.
      
  3. Downloading Struts, Hibernate and Integrate It
    This section explains you to setup the develop workbench for our Struts Hibernate tutorial
      
  4. Writing Hibernate configuration file, POJO class and Tutorial.hbm.xml (Hibernate mapping class)
    In this section we will write required hibernate objects like configuration files and then integrate all the stuffs.
      
  5. Developing Hibernate Struts Plugin
    In this section we will write Hibernate Struts Plugin Java code and integrate it with the Struts.
     
  6. Writing Web Client to Search the database using Struts Hibernate Plugin
    In this section we will write web client to test struts Plugin. We will be developing a search form to search the tutorials from the table.
     
  7. Build and testing the application
    In this section we will build our Struts Hibernate Plugin Application and then test.

Logic Present Tag ()

present tag -This tag evaluates its nested body contents if the specified value is present in the request.


This tag checks the current request and depending on which attribute is specified, it evaluates the nested body content of this tag only if the specified value is present. 


Attributes of Present Tag































Attribute Name Description
cookie

It checks  the existence of a cookie with the specified name.

header

It checks the existence of an HTTP header with the specified name. The name match is performed in a case insensitive manner.

name

It checks the existence of a JSP bean, in any scope, with the specified name. If property is also specified, checks for a non-null property value for the specified property.

parameter

It checks the existence of at least one occurrence of the specified request parameter on this request, even if the parameter value is a zero-length string.

property

It checks the existence of a non-null property value, returned by a property getter method on the JSP bean (in any scope) that is specified by the name attribute. Property references can be simple, nested, and/or indexed.

role

It checks whether the currently authenticated user (if any) has been associated with any of the specified security roles. Use a comma-delimited list to check for multiple roles. 

scope

The bean scope within which to search for the bean named by the name property, or “any scope” if not specified.

user

It checks whether the currently authenticated user principal has the specified name.


 


Logic notPresent Tag (<logic:not Present>…</logic:not Present>) 


notPresent tag -This tag evaluates its nested body content if the specified value is not present in the request.


Tag evaluation of the nested body content occurs only if the specified value is not available in the request i.e… works in reverses to present tag.

Attributes of notPresent  Tag































Attribute Name Description
cookie

It checks  the existence of a cookie with the specified name.

header

It checks the existence of an HTTP header with the specified name. The name match is performed in a case insensitive manner.

name

It checks the existence of a JSP bean, in any scope, with the specified name. If property is also specified, checks for a non-null property value for the specified property.

parameter

It checks the existence of at least one occurrence of the specified request parameter on this request, even if the parameter value is a zero-length string.

property

It checks the existence of a non-null property value, returned by a property getter method on the JSP bean (in any scope) that is specified by the name attribute. Property references can be simple, nested, and/or indexed.

role

It checks whether the currently authenticated user (if any) has been associated with the specified security role.

scope

The bean scope within which to search for the bean named by the name property, or “any scope” if not specified.

user

It checks whether the currently authenticated user principal has the specified name.


 


 


Example Illustrating the use of the present <logic:present > and the notPresent <logic:notPresent > logic tags.


Here you will learn to use the Struts  Logic tags. We will cover an example that will show  a comparison between  the two logic tags (ie..<logic:present > and the <logic:notPresent >).


Example code


Creating an Action  Class


Develop a simple action class LogicAction.java.











package roseindia.net;

import java.io.*;
import java.util.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net

**/
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.*;

public class LogicAction extends Action 
{
  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

      

        return mapping.findForward(“success”);
    }
}


Creating Form Bean


Our form bean class contains only one property text. Here is the code of FormBean (LogicForm.java)











package roseindia.net;

import org.apache.struts.action.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net

**/

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EmptyForm extends ActionForm 
{
    
    private String text = “”;
       
  public String getText() 
    {
        return text;
    }
    
    public void setText(String text) 
    {
    this.text=text;
  }
   
    
  
    
}


Defining form Bean in struts-config.xml file


Add the following entry in the struts-config.xml file for defining the form bean






<form-bean name=”LogicForm”  type=”roseindia.net.LogicForm” />

 Developing the Action Mapping in the struts-config.xml

Here, Action mapping helps to select the method from the Action class for specific requests.






<action path=”/LogicAction”
type=”roseindia.net.LogicAction”
name=”LogicForm”
scope=”request”
input=”/pages/InputLogic.jsp”>
<forward name=”success” path=”/pages/output.jsp”/>
</action>

Developing the InputLogic.jsp page






<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>
<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<html:html>
<head>
<title>Using &lt;logic&gt; Tags</title>
</head>

<body>
<h1>Using &lt;logic&gt; Tags</h1>

<html:form action=”/LogicAction” method =”post”>

<h2>Enter text :</h2>
<html:text property=”text”/>
<html:submit value=”Submit”/> 
<html:cancel/>
</html:form>
</body>
</html:html>


Developing the output.jsp page:


Notice the property values






<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>

<HTML>
<HEAD>
<TITLE>Here’s Your Data…</TITLE>
</HEAD>
<BODY>
<H4>Here’s Your Data…</H4>

<h4>The text entered is:

<bean:write name=”LogicForm1″ property=”text”/></h4>

<logic:present name=”LogicForm1″ property=”text” >
<h5>Using the tag &lt;logic:present &gt; </h5> 
Result: Successfully supported 
</logic:present>

<logic:notPresent name=”LogicForm1″ property=”text1″ >
<h5>Using the tag&lt;logic:notPresent&gt;</h5> 
Result: Support for a Variable other than a String is not Present </logic:notPresent>


</BODY>
</HTML>


Add the following line in the index.jsp to call the form.


<li>
<html:link page=”/pages/InputLogic.jsp”>Struts File Upload</html:link>
<br>
Example demonstrates  how LogicAction Class works.
</li>


Building and Testing the Example 


To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following  page.


Writing  a text string to the InputLogic.jsp page lets you to see the working of  the  present Logic tag <logic:present > and the notPresent Logic tag <logic:notPresent >. 







It displays the following out.jsp page







Logic Match Tag ()

match tag – We use this tag to evaluate the contents contained in the nested body parts of this tag if the specified value is an appropriate substring of the requested variable.


This tag matches the variable specified as a String against the specified constant value. If the value is a substring  then the nested body content of this tag is evaluated.


Attributes of match Tag































Attribute Name Description
cookie

The variable to be matched is the value of the cookie whose name is specified by this attribute.

header

The variable to be matched is the value of the header whose name is specified by this attribute. The name match is performed in a case insensitive manner.

location

If not specified, a match between the variable and the value may occur at any position within the variable string. If specified, the match must occur at the specified location (either start or end) of the variable string.

name

The variable to be matched is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if property is specified.

parameter

The variable to be matched is the first, or only, value of the request parameter specified by this attribute.

property

The variable to be matched is the property (of the bean specified by the name attribute) specified by this attribute. The property reference can be simple, nested, and/or indexed.

scope

The bean scope within which to search for the bean named by the name property, or “any scope” if not specified.

value

The constant value which is checked for existence as a substring of the specified variable.


 


Logic notMatch  Tag (<logic:notMatch  >…</logic:notMatch  >) 


notMatchWe use this tag to evaluate the contents contained in the nested body parts of this tag if the specified value is not a substring of the requested variable.


This tag matches the variable specified by one of  attributes (as a String) against the specified constant value. If the value is not a substring  the nested body content of this tag is evaluated.



Attributes of notMatch  Tag































Attribute Name Description
cookie

The variable to be matched is the value of the cookie whose name is specified by this attribute.

header

The variable to be matched is the value of the header whose name is specified by this attribute. The name match is performed in a case insensitive manner.

location

If not specified, a match between the variable and the value may occur at any position within the variable string. If specified, the match must occur at the specified location (either start or end) of the variable string.

name

The variable to be matched is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if property is specified.

parameter

The variable to be matched is the first, or only, value of the request parameter specified by this attribute.

property

The variable to be matched is the property (of the bean specified by the name attribute) specified by this attribute. The property reference can be simple, nested, and/or indexed.

scope

The bean scope within which to search for the bean named by the name property, or “any scope” if not specified.

value

The constant value which is checked for existence as a substring of the specified variable.


 


Example Illustrating the use of the Match <logic:match > and the notMatch  <logic:notMatch  > logic tags.


Here you will learn to use the Struts  Logic tags. We will cover an example that will show  a comparison between  the two logic tags (ie..<logic:match > and the <logic:notMatch>).


Example code


Creating an Action  Class


Develop a simple action class LogicAction.java.











package roseindia.net;

import java.io.*;
import java.util.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net

**/
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.*;

public class LogicAction extends Action 
{
  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

      

        return mapping.findForward(“success”);
    }
}


Creating Form Bean


Our form bean class contains only one property text. Here is the code of FormBean (LogicForm.java)











package roseindia.net;

import org.apache.struts.action.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net

**/

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EmptyForm extends ActionForm 
{
    
    private String text = “”;
       
  public String getText() 
    {
        return text;
    }
    
    public void setText(String text) 
    {
    this.text=text;
  }
   
    
  
    
}


Defining form Bean in struts-config.xml file


Add the following entry in the struts-config.xml file for defining the form bean






<form-bean name=”LogicForm”  type=”roseindia.net.LogicForm” />

 Developing the Action Mapping in the struts-config.xml

Here, Action mapping helps to select the method from the Action class for specific requests.






<action path=”/LogicAction”
type=”roseindia.net.LogicAction”
name=”LogicForm”
scope=”request”
input=”/pages/InputLogic.jsp”>
<forward name=”success” path=”/pages/output.jsp”/>
</action>

Developing the InputLogic.jsp page






<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>

<html:html>
<head>
<title>Using &lt;logic&gt; Tags</title>
</head>

<body>
<h1>Using &lt;logic&gt; Tags</h1>

<html:form action=”/LogicAction” method =”post”>

<h2>Enter text:</h2>
<html:text property=”text”/>

<br>
<h4>The &lt;logic:match&gt;tag works if the entered </h4>
<h4>text contains “amit”</h4>
<h4>The &lt;logic:notMatch&gt;tag always evaluate the </h4>
<h4>entered text against the”abc” value</h4>
<br>

<html:submit value=”Submit”/>


<html:cancel/>
</html:form>
</body>
</html:html>

Developing the output.jsp page


Notice the values






<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>

<HTML>
<HEAD>
<TITLE>Here’s Your Data…</TITLE>
</HEAD>

<BODY>
<H4>Here’s Your Data…</H4>

<h4>The text entered is:

<bean:write name=”LogicForm” property=”text”/></h4>


<logic:match name=”LogicForm” property=”text” value=”amit”>
<h5>Using the tag &lt;logic:match &gt; </h5> 
Result : entered text contains “amit”
</logic:match>



<logic:notMatch name=”LogicForm” property=”text” value=”abc”>
<h5>Using the tag&lt;logic:notMatch&gt;</h5> 
Result: entered text does not contains “abc”
</logic:notMatch>

</BODY>
</HTML>

Add the following line in the index.jsp to call the form.


<li>
<html:link page=”/pages/InputLogic.jsp”>Struts File Upload</html:link>
<br>
Example demonstrates  how LogicAction Class works.
</li>


Building and Testing the Example 


To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following  page.


Writing text including “amit” and excluding “abc” to the InputLogic.jsp page displays the working of  the  match Logic tag <logic:match > and the notMatch Logic tag <logic:notMatch > .







It displays the following to the out.jsp page







Writing text including “amit” and  “abc” to the InputLogic.jsp page displays the working of  the  match Logic tag <logic:match > and the notMatch Logic tag <logic:notMatch > .







The <logic:notEqual > evaluated here displays the output.jsp as







Logic LessEqual Tag ()

lessEqual Tag – If the requested variable is either less or equal to the specified values then we use this tag to evaluate the contents contained in the nested body parts of this tag.


This tag compares the variable against the specified constant value. If the variable is less than or equal to the specified value then the nested body contents of this tag is evaluated


Attributes of lessEqual Tag



























Attribute Name Description
cookie

The variable contains  the cookie value needed to compare .Here the name is specified by this attribute.

header

The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner.

name

The variable to be compared is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if property is specified.

parameter

The variable to be compared is the first, or only, value of the request parameter specified by this attribute.

property

The variable contains  the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed.

scope

This specifies the bean scope within which  the bean is searched  by the name property, or “any scope” if not specified.

value

The constant value is specified by other attribute(s) of this tag, needed to compare


 


Logic LessThan Tag (<logic:lessThan >…</logic:lessThan>) 


lessThan TagIf the requested variable is less than the specified values then we use this tag to evaluate the contents contained in the nested body parts of this tag.


This tag compares the variable against the specified constant value. If the variable is less than  the specified value then the nested body contents of this tag is evaluated


Attributes of lessThan Tag



























Attribute Name Description
cookie

The variable contains  the cookie value needed to compare .Here the name is specified by this attribute.

header

The variable contains the header value needed to compare whose name is specified by this attribute. The name match is performed in a case insensitive manner.

name

The variable to be compared is the JSP bean specified by this attribute, if property is not specified, or the value of the specified property of this bean, if property is specified.

parameter

The variable to be compared is the first, or only, value of the request parameter specified by this attribute.

property

The variable contains  the bean property value needed to compare ,it is specified by this attribute. The property reference can be simple, nested, and/or indexed.

scope

This specifies the bean scope within which  the bean is searched  by the name property, or “any scope” if not specified.

value

The constant value is specified by other attribute(s) of this tag, needed to compare


Example Illustrating the use of the lessEqual <logic:LessEqual > and the lessThan <logic:LessThan > logic tags.


Here you will learn to use the Struts  Logic tags. We will cover an example that will show  a comparison between  the two logic tags (ie..<logic:lessEqual > and the <logic:LessThan >).


Example code


Creating an Action  Class


Develop a simple action class LogicAction.java.











package roseindia.net;

import java.io.*;
import java.util.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net

**/
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.*;

public class LogicAction extends Action 
{
  public ActionForward execute(ActionMapping mapping,
    ActionForm form,
    HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException {

      

        return mapping.findForward(“success”);
    }
}


Creating Form Bean


Our form bean class contains only one property number. Here is the code of FormBean (LogicForm.java)











package roseindia.net;

import org.apache.struts.action.*;

/**

* @author Amit Gupta
* @Web http://www.roseindia.net
* @Email struts@roseindia.net

**/

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LogicForm extends ActionForm 
{
    
    private long number;        
  public 
long getNumber() 
    {
        return number;
    }
    
    public void setNumber(long number) 
    {
    this.number=number;
  }
   
    
  
    
}


Defining form Bean in struts-config.xml file


Add the following entry in the struts-config.xml file for defining the form bean






<form-bean name=”LogicForm”  type=”roseindia.net.LogicForm” />

 Developing the Action Mapping in the struts-config.xml

Here, Action mapping helps to select the method from the Action class for specific requests.






<action path=”/LogicAction”
type=”roseindia.net.LogicAction”
name=”LogicForm”
scope=”request”
input=”/pages/InputLogic.jsp”>
<forward name=”success” path=”/pages/output.jsp”/>
</action>

Developing the InputLogic.jsp page






<%@ taglib uri=”/tags/struts-html” prefix=”html” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>

<html:html>
<head>
<title>Using &lt;logic&gt; Tags</title>
</head>

<body>
<h1>Using &lt;logic&gt; Tags</h1>

<html:form action=”/LogicAction” method =”post”>

<h2>Enter a number:</h2>
<html:text property=”number”/>

<br>
<h3>The &lt;logic:lessEqual&gt;tag works if you enter a value</h3>
<h3>less than or equal to 100</h3>
<h3>The &lt;logic:lessThan&gt;tag works if you enter a value</h3>
<h3>less than to 10000</h3>
<br>

<html:submit value=”Submit”/>


<html:cancel/>
</html:form>
</body>
</html:html>

Developing the output.jsp page






<%@ taglib uri=”/tags/struts-bean” prefix=”bean” %>
<%@ taglib uri=”/tags/struts-logic” prefix=”logic” %>

<HTML>
<HEAD>
<TITLE>Here’s Your Data…</TITLE>
</HEAD>

<BODY>
<H3>Here’s Your Data…</H3>

<h4>The number entered is:

<bean:write name=”LogicForm” property=”number”/></h4>


<logic:lessEqual name=”LogicForm” property=”number” value=”100“>
<h4>Using the tag&lt;logic:lessEqual&gt;</h4> 
Result : lessEqual
</logic:lessEqual>


<logic:lessThan name=”LogicForm” property=”number” value=”10000“>
<h4>Using the tag &lt;logic:lessThan &gt; </h4> 
Result : lessThan
</logic:lessThan>


</BODY>
</HTML>
</HTML>

Add the following line in the index.jsp to call the form.


<li>
<html:link page=”/pages/InputLogic.jsp”>Struts File Upload</html:link>
<br>
Example demonstrates  how LogicAction Class works.
</li>


Building and Testing the Example 


To build and deploy the application go to Struts\Strutstutorial directory and type ant on the command prompt. This will deploy the application. Open the browser and navigate to the InputLogic.jsp page. Your browser displays the following  page.


Writing a number equal to 101 to the InputLogic.jsp page displays the working of  the  lessThan Logic tag <logic:lessThan > 







It displays the following out.jsp page







Now  write data equal 100  to the InputLogic.jsp to compare the working of  the lessEqual and lessThan tags







Here both tags are evaluated it displays the output.jsp as