Posts Tagged ‘Struts’

Integrating Hibernate with Struts1.x

Friday, July 2nd, 2010
We have got list of post(s) about Hibernate. Today as a next step we’ll try to intergrate with MVC framework. We’ll take the most used one which Struts1.3. For example we’ll take the same Singer Example and we’ll work with that for intergrating with struts also.Since we have the domain object generated already, we can make use of the same domain object to populate the values from DB, when we use the Hibernate.
We just take the examples of listing all the Singers from Singers table. Since we are using Struts1.x, we may need to write the action class and form class. The following code shows Form Class. Since we are going to list all the Singers, then our Form looks like the following.
		package com.techmaddy.form;

		/*
		*  Copyright 2010 - Kumarasamy
		*	kumarasamy@techmaddy.com
		*/

		import javax.servlet.http.HttpServletRequest;

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

		import com.techmaddy.singer.Singer;

		public class SingerForm extends ActionForm {

			private static final long serialVersionUID = 1L;

			private Singer[] singer =  new Singer[0];

			public Singer[] getSinger() {
				return singer;
			}

			public void setSinger(Singer[] singer) {
				this.singer = singer;
			}

			public void reset(ActionMapping mapping, HttpServletRequest request) {
				singer =  new Singer[0];
			}

		}
	
The DAO class will make a call to DB and returns the results. This is almost very similar to the class CRUDTest.java in Simple CRUD Operation With Hibernate. Instead of my CRUDTest class, we have an DAO Class which gets the data from DB.
My DAO Class looks like the following.
			package com.techmaddy.bo;

			/*
			*  Copyright 2010 - Kumarasamy
			*	kumarasamy@techmaddy.com
			*/

			import java.util.ArrayList;
			import java.util.Iterator;
			import java.util.List;

			import org.hibernate.Session;
			import org.hibernate.Transaction;
			import org.hibernate.Query;

			import com.techmaddy.singer.HibernateSessionFactory;
			import com.techmaddy.singer.Singer;

			public class SingerManager {

				public Singer[] getAllSingers() {
					List singer = new ArrayList();
					Session session = null;
					Transaction tx = null;

					session = HibernateSessionFactory.getSession();

					tx = session.beginTransaction();
					Query qry = session.createQuery("from Singer");
					for (Iterator iterator = qry.iterate(); iterator.hasNext();) {
						singer.add(iterator.next());
					}

					return (Singer[]) singer.toArray(new Singer[0]);
				}

			}
	
The same way, based in the action performed from the screen, we can make a call to Editing and deleting the Singers.The following Images shows the result screen.
Struts-Hibernate Integration
Download
To download the War file for Singer with Struts Integration Click Here
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Struts-Validator FrameWork

Sunday, April 5th, 2009
In Struts we have two kinds of validation a). Server Side Validation b). Client Side Validation.
The server side validation can be done in two ways. One can use ActionForm to validate. The second method is make use of XML based validation. The XML based validation will happen based on validation.xml.In the form based validation the validation happens in validate method of ActionForm.
ActionErrors class is used to hold the Error messages and used to display it on View.
Adding Validator Framework Support
		<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
			<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
		</plug-in>
		
Using validation.xml
The above configuration adds validator support in the struts.The validation.xml file is used to declare sets of validations that should be applied to Form Beans. Each Form Bean that you want to validate has its own definition in this file. Inside that definition you specify the validations that you want to apply to the Form Bean’s fields. Following is a sample validation.xml file that illustrates how validations are defined:
			<form-validation>
				<formset>
					<!-- validation mappings -->
					<form name="exampleXMLForm">
						<field property="name" depends="required, minlength">
							<arg key="exampleXMLForm.name" />
							<arg key="${var:minlength}" resource="false" />
							<var>
								<var-name>minlength</var-name>
								<var-value>3</var-value>
							</var>
						</field>
						<field property="age" depends="required, integer, validwhen">
							<arg key="exampleXMLForm.age"/>
							<arg name="validwhen" key="${var:min}" resource="false" />
							<var>
								<var-name>test</var-name>
								<var-value>(*this* > 18)</var-value>
							</var>
						</field>
					</form>
				</formset>
			</form-validation>
The above xml defines the fileds Name and age validations. This is an XML based validation. The peiece of code defines the actionmapping and form bean definition in struts-config.xml
			<form-beans>
				<form-bean name="exampleForm" type="com.techmaddy.tmvalidator.ExampleForm" />
				<form-bean name="exampleXMLForm" type="com.techmaddy.tmvalidator.ExampleXMLForm" />
			</form-beans>
			<action-mappings>
				<action attribute="exampleForm" input="/example.jsp" name="exampleForm" path="/example" scope="request"			type="com.techmaddy.tmvalidator.ExampleAction" validate="true">
					<forward name="example" path="/example.jsp" />
				</action>
				<action attribute="exampleXMLForm" input="/exampleXML.jsp"			name="exampleXMLForm" path="/exampleXML" scope="request"			type="com.techmaddy.tmvalidator.ExampleXMLAction" validate="true">
					<forward name="example" path="/exampleXML.jsp" />
				</action>
			</action-mappings>
Using ActionForm

This Class is used to validate the the user input form and sets the error message in ActionErrors.


			package com.techmaddy.tmvalidator;

			import javax.servlet.http.HttpServletRequest;
			import org.apache.struts.action.ActionErrors;
			import org.apache.struts.action.ActionForm;
			import org.apache.struts.action.ActionMapping;
			import org.apache.struts.action.ActionMessage;

			/** * * @author Kumarasamy */

			public class ExampleForm extends ActionForm {

				private String name;

				private Integer age;

				public String getName() {
					return name;
				}

				public void setName(String name) {
					this.name = name;
				}

				public Integer getAge() {
					return age;
				}

				public void setAge(Integer age) {
					this.age = age;
				}

				public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {
					ActionErrors actionErrors = new ActionErrors();

					if (name.length() < 3) {
						actionErrors.add("name", new ActionMessage("error.name"));
					}

					if (age == null || age < 18) {
						actionErrors.add("age", new ActionMessage("error.age"));
					}// return collection of action messages

					return actionErrors;
				}

				//Reset the values
					public void reset(ActionMapping mapping, HttpServletRequest request) {
						setName("");
						setAge(0);
					}
				}
				
Download
To download the WAR file which Contains the example for Struts Validator FrameWork Click Here
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Adding Tiles in your Struts Project

Sunday, March 22nd, 2009
Tiles is a framework for the development user interface. Tiles is enables the developers to develop the web applications by assembling the reusable tiles (jsp, html, etc..). Tiles uses the concept of reuse and enables the developers to define a template for the web site and then use this layout to populate the content of the web site. For example, if you have to develop a web site having more that 500 page of static content and many dynamically generated pages. The layout of the web site often changes according to the business requirement. In this case you can use the Tiles framework to design the template for the web site and use this template to populate the contents. In future if there is any requirement of site layout change then you have to change the layout in one page. This will change the layout of you whole web site
Steps To Create Tiles Application
Tiles is very useful framework for the development of web applications. Here are the steps necessary for adding Tiles to your Struts application:
  1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.
  2. Create layout JSPs.
  3. Develop the web pages using layouts.
  4. Repackage, run and test application.
Add the Tiles TLD to web.xml file
Tiles can can be used with or without Struts. Following entry is required in the web.xml file before you can use the tiles tags in your application.
		<jsp-config>
			<taglib>
				<taglib-uri>/WEB-INF/struts-tiles.tld</taglib-uri>
				<taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
			</taglib>
		</jsp-config>
		
Struts-Config.xml Changes
		<plug-in className="org.apache.struts.tiles.TilesPlugin" >
			<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
			<set-property property="moduleAware" value="true" />
		</plug-in>
		
The above configuration will add Tiles support in your project.My tiles definition as follows in tiles-defs.xml
			<definition name="IT.rootLayout" path="/rootLayout.jsp">
				<put name="topBanner" value="top.html"/>
				<put name="leftMenu" value="leftMenu.html"/>
				<put name="Desktop" value="Desktop.jsp"/>
				<put name="footer" value="footer.html"/>
			</definition>
		
In the above code i have defined a Tile element, IT.rootLayout. The page is rootLayout.jsp and it has four components, Which is topBanner,leftMenu,Desktop,footer.My rootLayout.jsp will look like the following.
		<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
		<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
			<html:html locale="true">
			<head>
				<title>Test Tiles</title>
			</head>
			<body>
			<table width="100%" cellspacing="0" cellpadding="0" border="1">
			<tr>
				<td><tiles:insert attribute="topBanner"/></td>
			</tr>
			<tr>
				<td><tiles:insert attribute="leftMenu"/></td>
			</tr>
			<tr>
				<td>
					<table cellspacing="0" cellpadding="0" border="1" width="100%">
					<tr valign="top">
						<td ><tiles:insert attribute="Desktop" /></td>
					</tr>
					</table>
				</td>
			</tr>
			<tr>
				<td><tiles:insert attribute="footer"/></td>
			</tr>
		</table>
		</body>
		</html:html>
	
To call the tile component IT.rootLayout, i”m going to add the following definition in struts-config.xml
		<action path="/IT.rootLayout" forward="IT.rootLayout"/>
		
We are done!!!! We have added a Tile definition and pages also
Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)
Get Adobe Flash player