<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ViralPatel.net &#187; J2EE</title>
	<atom:link href="http://viralpatel.net/blogs/category/j2ee/feed" rel="self" type="application/rss+xml" />
	<link>http://viralpatel.net/blogs</link>
	<description>Tutorials, Java, J2EE, Struts, AJAX, JavaScript, CSS, Web 2.0, MySQL, Articles</description>
	<lastBuildDate>Wed, 10 Mar 2010 12:02:35 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Writing a URL Shortner in Java Struts2 &amp; Hibernate</title>
		<link>http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html</link>
		<comments>http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html#comments</comments>
		<pubDate>Wed, 17 Feb 2010 09:16:40 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Struts2]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=2029</guid>
		<description><![CDATA[This is an attempt to create a simple URL shortner service in pure JEE with Struts2 and Hibernate. 

Creating Base Framework
I always have Basic framework ready which gives a kick start to the web app development. You don&#8217;t have to hassle about different configuration issues/jar file issues etc. Let us start with creating sample base [...]]]></description>
			<content:encoded><![CDATA[<p>This is an attempt to create a simple URL shortner service in pure JEE with Struts2 and Hibernate. </p>
<p><img src="http://img.viralpatel.net/2010/02/shorty-url-shortner-struts2-hibernate.png" alt="shorty-url-shortner-struts2-hibernate" title="shorty-url-shortner-struts2-hibernate" width="523" height="189" class="aligncenter size-full wp-image-2031" /></p>
<h2>Creating Base Framework</h2>
<p>I always have Basic framework ready which gives a kick start to the web app development. You don&#8217;t have to hassle about different configuration issues/jar file issues etc. Let us start with creating sample base framework for our project. We will use Struts2 and Hibernate for this implementation.<br />
First lets create a Dynamic web project in eclipse.<br />
<img alt="Dynamic web project" src="http://img.viralpatel.net/2008/12/eclipse-new-project-struts-example.png" title="Dynamic web project" class="aligncenter" width="369" height="365" /><br />
We will name our project <strong>Shorty</strong>.</p>
<p>Then, we will add all the required Jar files for our project. Following is the list of Jars that I have included in the <strong>WEB-INF/lib</strong> folder.<br />
<img src="http://img.viralpatel.net/2010/02/shorty-struts2-hibernate-jars.png" alt="shorty-struts2-hibernate-jars" title="shorty-struts2-hibernate-jars" width="232" height="375" class="aligncenter size-full wp-image-2033" /></p>
<p>You can download all of the above JARs from <a rel="nofollow" target="_blank" href="http://www.ibiblio.org/maven/">http://www.ibiblio.org/maven/</a></p>
<p>Now lets us change the web.xml file and add Struts filter. This will add Struts support in our base framework.<br />
Following will be the web.xml content.<br />
<strong>WEB-INF/web.xml</strong></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app id=&quot;WebApp_ID&quot; version=&quot;2.4&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;&gt;
	&lt;display-name&gt;Go&lt;/display-name&gt;
	&lt;welcome-file-list&gt;
		&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
	&lt;/welcome-file-list&gt;
 	&lt;filter&gt;
		&lt;filter-name&gt;struts2&lt;/filter-name&gt;
		&lt;filter-class&gt;
			org.apache.struts2.dispatcher.FilterDispatcher
		&lt;/filter-class&gt;
	&lt;/filter&gt;
	&lt;filter-mapping&gt;
		&lt;filter-name&gt;struts2&lt;/filter-name&gt;
		&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
	&lt;/filter-mapping&gt;

&lt;/web-app&gt;
</pre>
<p>Now create a source folder called <strong>resources</strong>. Right click on your project in Project explorer -> New -> Source Folder.</p>
<p>Create a file hibernate.cfg.xml in the resources folder. This will be the configuration file of Hibernate which contains database connection strings and other related data.</p>
<p><strong>resources/hibernate.cfg.xml</strong></p>
<pre class="brush: xml;">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;

	&lt;session-factory&gt;

		&lt;property name=&quot;connection.driver_class&quot;&gt;
			com.mysql.jdbc.Driver
		&lt;/property&gt;
		&lt;property name=&quot;connection.url&quot;&gt;
			jdbc:mysql://localhost:3306/shorty
		&lt;/property&gt;
		&lt;property name=&quot;connection.username&quot;&gt;username&lt;/property&gt;
		&lt;property name=&quot;connection.password&quot;&gt;password&lt;/property&gt;

		&lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
		&lt;property name=&quot;dialect&quot;&gt;
			org.hibernate.dialect.MySQLDialect
		&lt;/property&gt;
		&lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
		&lt;property name=&quot;cache.provider_class&quot;&gt;
			org.hibernate.cache.NoCacheProvider
		&lt;/property&gt;
		&lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
		&lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;

	&lt;/session-factory&gt;

&lt;/hibernate-configuration&gt;
</pre>
<p>Also lets create package structure for the source code in our base framework. We will create few packages in <strong>src</strong> folder.<br />
<img src="http://img.viralpatel.net/2010/02/url-shortner-base-framework-package.png" alt="url-shortner-base-framework-package" title="url-shortner-base-framework-package" width="203" height="84" class="aligncenter size-full wp-image-2035" /></p>
<p>Now we are ready with a basic framework that has Hibernate and Struts2 support. This can now be used to create any application using these two technologies.</p>
<p>Let us start with creating database design for our simplest URL shortner.</p>
<h2>Database Design for URL Shortner</h2>
<p>Our requirement is very simple. We will have a single table in database that holds the value for URLs and its shortcode. Following will be the DDL for LINKS table. Note that we will also track number of clicks on each URL. </p>
<pre class="brush: sql;">
CREATE TABLE LINKS
(
	id 		INT PRIMARY KEY AUTO_INCREMENT,
	shortcode 	VARCHAR(20),
	url 		VARCHAR(255),
	clicks		INT DEFAULT 0,
	created	TIMESTAMP DEFAULT NOW()
);
</pre>
<h2>Adding logic to create shortcode</h2>
<p>URL Shortner is all about creating short codes for a long url. The logic that we will use to create a short code is simple. We will add URL into database table with auto generating primary key. This primary key will be a unique number. Then we convert this number to a string representation of base48 with characters 0 to 9 a to z and A to Z. Following is the logic for this.</p>
<pre class="brush: java;">
	public static String base48Encode(Long no) {
		Double num = Double.valueOf(no);
		String charSet = &quot;23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ&quot;;
		Integer length = charSet.length();
		String encodeString = new String();
		while(num &gt; length) {
			encodeString = charSet.charAt(num.intValue() % length)+encodeString;
			 num = Math.ceil(new Double(num / length) - 1) ;
		}
		encodeString = charSet.charAt(num.intValue())+encodeString;

		return encodeString;
	}
</pre>
<p>In above method we have passed a long number (which will be auto generated primary key) and get string representation.</p>
<p>We will add this logic into a file ShortyUtil.java. Create ShortyUtil class under <em>net.viralpatel.shorty.util</em> package. </p>
<p><strong>net.viralpatel.shorty.util.ShortyUtil</strong></p>
<pre class="brush: java;">
package net.viralpatel.shorty.util;

public class ShortyUtil {
	public static String base48Encode(Long no) {
		Double num = Double.valueOf(no);
		String charSet = &quot;23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ&quot;;
		Integer length = charSet.length();
		String encodeString = new String();
		while(num &gt; length) {
			encodeString = charSet.charAt(num.intValue() % length)+encodeString;
			 num = Math.ceil(new Double(num / length) - 1) ;
		}
		encodeString = charSet.charAt(num.intValue())+encodeString;

		return encodeString;
	}

	public static String getShortCodeFromURL(String URL) {

		int index=0;
		for(index=URL.length()-1; index&gt;=0 &amp;&amp; URL.charAt(index)!= '/' ;index--);
		String shortCode = URL.substring(index+1);

		return shortCode;
	}
}
</pre>
<h2>Connecting to Database using Hibernate</h2>
<p>Adding Hibernate related code is easy. </p>
<p>First add <em>HibernateUtil</em> class in <em>net.viralpatel.shorty.util</em> that we will use to create SessionFactory object. </p>
<p><strong>net.viralpatel.shorty.util.HibernateUtil</strong></p>
<pre class="brush: java;">
package net.viralpatel.shorty.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new AnnotationConfiguration().configure().buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}
</pre>
<p>Now create an entity class that will map to LINKS table in database. Create Link.java class under <code>net.viralpatel.shorty.model</code> package.</p>
<p><strong>net.viralpatel.shorty.model.Link</strong></p>
<pre class="brush: java;">
package net.viralpatel.shorty.model;

import java.io.Serializable;
import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name=&quot;LINKS&quot;)
public class Link implements Serializable{

	private static final long serialVersionUID = -8767337896773261247L;

	private Long id;
	private String shortCode;
	private String url;
	private Long clicks;
	private Date created;

	@Id
	@GeneratedValue
	@Column(name=&quot;id&quot;)
	public Long getId() {
		return id;
	}
	@Column(name = &quot;shortcode&quot;)
	public String getShortCode() {
		return shortCode;
	}
	@Column(name = &quot;created&quot;)
	public Date getCreated() {
		return created;
	}
	@Column(name = &quot;url&quot;)
	public String getUrl() {
		return url;
	}
	@Column(name = &quot;clicks&quot;)
	public Long getClicks() {
		return clicks;
	}
	public void setClicks(Long clicks) {
		this.clicks = clicks;
	}
	public void setShortCode(String shortCode) {
		this.shortCode = shortCode;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public void setCreated(Date created) {
		this.created = created;
	}
	public void setId(Long id) {
		this.id = id;
	}
}
</pre>
<p>Now add the mapping for above entity class Link.java in hibernate.cfg.xml file. Add following link in &gt;session-factory&lt; tag:</p>
<pre class="brush: java;">
&lt;mapping class=&quot;net.viralpatel.shorty.model.Link&quot; /&gt;
</pre>
<p>Also we will need a controller class that we invoke from Struts action class to do read/write in database. Create LinkController.java under net.viralpatel.shorty.controller package.</p>
<p><strong>net.viralpatel.shorty.controller.LinkController</strong></p>
<pre class="brush: java;">
package net.viralpatel.shorty.controller;

import org.hibernate.Query;
import org.hibernate.classic.Session;

import net.viralpatel.shorty.model.Link;
import net.viralpatel.shorty.util.HibernateUtil;
import net.viralpatel.shorty.util.ShortyUtil;

public class LinkController extends HibernateUtil {

	public Link get(String shortCode) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Query query = session.createQuery(&quot;from Link where shortcode = :shortcode&quot;);
		query.setString(&quot;shortcode&quot;, shortCode);
		Link link = (Link) query.uniqueResult();
		if(null != link) {
			link.setClicks(link.getClicks());
			session.save(link);
		}
		session.getTransaction().commit();

		return link;

	}

	public Link add(Link link) {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();

		Query query = session.createQuery(&quot;from Link where url = :url&quot;);
		query.setString(&quot;url&quot;, link.getUrl());
		Link oldLink = (Link) query.uniqueResult();
		if(null != oldLink)
			return oldLink;

		session.save(link);
		if(null == link.getShortCode()) {
			link.setShortCode(ShortyUtil.base48Encode(link.getId()));
			session.save(link);
		}
		session.getTransaction().commit();
		return link;
	}
}
</pre>
<h2>Adding Struts2 Support</h2>
<p>The UI for our URL shortner is very simple. We will have a index.jsp page which has a textbox for entering long URL and a small <em>Shorten</em> button. Also we will add a functionality where we can see some statistics/details of any short url. For example if shortcode <em>http://&lt;shorturl&gt;q1d</em> points to http://viralpatel.net then <em>http://&lt;shorturl&gt;q1d+</em> will show a page with details about url http://viralpatel.net.<br />
<strong>Related:</strong> <a target="_blank" href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html">Tutorial: Create Struts 2 Application in Eclipse</a></p>
<p>Lets starts with creating Action class. Create a class <code>LinkAction.java</code> under <code>net.viralpatel.shorty.view</code> package.</p>
<p><strong>LinkAction.java</strong></p>
<pre class="brush: java;">
package net.viralpatel.shorty.view;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.interceptor.ServletRequestAware;
import net.viralpatel.shorty.controller.LinkController;
import net.viralpatel.shorty.model.Link;
import net.viralpatel.shorty.util.ShortyUtil;

import com.opensymphony.xwork2.ActionSupport;

public class LinkAction extends ActionSupport implements ServletRequestAware {

	private static final long serialVersionUID = 1L;
	private final static String DETAIL = &quot;detail&quot;;
	private String url;
	private Link link;

	private LinkController linkController;

	private HttpServletRequest request;

	public LinkAction() {
		linkController = new LinkController();
	}
	public String add() {
		link = new Link();
		link.setUrl(this.url);
		link = linkController.add(link);

		return SUCCESS;
	}
	public String get() {

		String uri = request.getRequestURI();

		uri = ShortyUtil.getShortCodeFromURL(uri);

		if(uri.charAt(uri.length()-1) == '+') {
			uri = uri.substring(0, uri.length()-1);
			this.link = this.linkController.get(uri);
			return DETAIL;
		}

		this.link = this.linkController.get(uri);
		if(null == this.link) {
			addActionError(getText(&quot;error.url.unavailable&quot;));
			return INPUT;
		} else {

			setUrl(link.getUrl());
			return SUCCESS;
		}
	}
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Link getLink() {
		return link;
	}

	public void setLink(Link link) {
		this.link = link;
	}
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
}
</pre>
<p>Also create struts configuration file struts.xml under resources folder and copy following content into it.<br />
<strong>resources/struts.xml</strong></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE struts PUBLIC
    &quot;-//Apache Software Foundation//DTD Struts Configuration 2.0//EN&quot;
    &quot;http://struts.apache.org/dtds/struts-2.0.dtd&quot;&gt;

&lt;struts&gt;
	&lt;constant name=&quot;struts.enable.DynamicMethodInvocation&quot;
		value=&quot;false&quot; /&gt;
	&lt;constant name=&quot;struts.devMode&quot; value=&quot;false&quot; /&gt;
	&lt;constant name=&quot;struts.custom.i18n.resources&quot;
		value=&quot;MessageResources&quot; /&gt;

	&lt;package name=&quot;default&quot; extends=&quot;struts-default&quot; namespace=&quot;/&quot;&gt;
		&lt;action name=&quot;add&quot; class=&quot;net.viralpatel.shorty.view.LinkAction&quot;
			method=&quot;add&quot;&gt;
			&lt;result name=&quot;success&quot;&gt;index.jsp&lt;/result&gt;
		&lt;/action&gt;
		&lt;action name=&quot;*&quot; class=&quot;net.viralpatel.shorty.view.LinkAction&quot;
			method=&quot;get&quot;&gt;
			&lt;result name=&quot;success&quot; type=&quot;redirect&quot;&gt;${url}&lt;/result&gt;
			&lt;result name=&quot;input&quot;&gt;index.jsp&lt;/result&gt;
			&lt;result name=&quot;detail&quot;&gt;detail.jsp&lt;/result&gt;
		&lt;/action&gt;
	&lt;/package&gt;
&lt;/struts&gt;
</pre>
<p>Note that we have used wildcard mapping in Struts2 action class. This is to ensure we call LinkAction for any shortcode passed in url shortner service.</p>
<p>Create a resource bundle file MessageResources.properties which will hold value for domain name of our URL shortner and an error message.<br />
<strong>resources/MessageResources.properties</strong></p>
<pre class="brush: xml;">
shorty.base.url=http://shorty/
error.url.unavailable=Couldn't find the site's URL to redirect to.
</pre>
<p>You may want to change value of <em>key shorty.base.url</em> to your domain name.</p>
<p>Add following JSP files in WebContent folder.</p>
<p><strong>WebContent/index.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ taglib uri=&quot;/struts-tags&quot; prefix=&quot;s&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;title&gt;Shorty - An Open Source URL Shortner in Struts2/Hibernate | ViralPatel.net&lt;/title&gt;
&lt;link href=&quot;css/style.css&quot; rel=&quot;stylesheet&quot;/&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1 class=&quot;title&quot;&gt;Shorty&lt;/h1&gt;
&lt;br&gt;
&lt;p&gt;A Simple URL Shortner in Struts2/Hibernate/MySQL&lt;/p&gt;
&lt;br&gt;&lt;br&gt;
&lt;div id=&quot;link-container&quot;&gt;

	&lt;s:form action=&quot;add&quot; method=&quot;post&quot;&gt;
		&lt;s:actionerror/&gt;
		&lt;s:textfield name=&quot;url&quot; cssClass=&quot;link&quot;/&gt;
		&lt;s:submit value=&quot;Shorten&quot;/&gt;
	&lt;/s:form&gt;
	&lt;s:if test=&quot;link.shortCode != null&quot;&gt;
			&lt;h3&gt;&lt;s:text name=&quot;shorty.base.url&quot;/&gt;&lt;s:property value=&quot;link.shortCode&quot;/&gt;&lt;/h3&gt;
	&lt;/s:if&gt;

&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>WebContent/detail.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ taglib uri=&quot;/struts-tags&quot; prefix=&quot;s&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;title&gt;Shorty - An Open Source URL Shortner in Struts2/Hibernate | ViralPatel.net&lt;/title&gt;
&lt;link href=&quot;css/style.css&quot; rel=&quot;stylesheet&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h1 class=&quot;title&quot;&gt;Shorty&lt;/h1&gt;

	Short Code: &lt;s:property value=&quot;link.shortCode&quot; /&gt; &lt;br /&gt;
	Original URL: &lt;s:property value=&quot;link.url&quot; /&gt; &lt;br /&gt;
	Clicks: &lt;s:property value=&quot;link.clicks&quot; /&gt; &lt;br /&gt;
	Created On: &lt;s:property value=&quot;link.created&quot; /&gt; &lt;br /&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>That&#8217;s all Folks</h2>
<p>Execute the web project in your favorite container like Tomcat, Glassfish etc.<br />
<img src="http://img.viralpatel.net/2010/02/shorty-url-shortner-struts2-hibernate.png" alt="shorty-url-shortner-struts2-hibernate" title="shorty-url-shortner-struts2-hibernate" width="523" height="189" class="aligncenter size-full wp-image-2031" /></p>
<h2>Download</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/shorty/Shorty.war"><strong>Download WAR File with Source Code</strong></a></p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html" title="Tutorial: Create Struts2 Hibernate Example in Eclipse">Tutorial: Create Struts2 Hibernate Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html&amp;title=Writing a URL Shortner in Java Struts2 &#038; Hibernate&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html&amp;title=Writing a URL Shortner in Java Struts2 &#038; Hibernate" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html&amp;title=Writing a URL Shortner in Java Struts2 &#038; Hibernate" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html&amp;title=Writing a URL Shortner in Java Struts2 &#038; Hibernate" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Tutorial: Create Struts2 Hibernate Example in Eclipse</title>
		<link>http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html</link>
		<comments>http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html#comments</comments>
		<pubDate>Fri, 15 Jan 2010 15:08:02 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Struts2]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1993</guid>
		<description><![CDATA[This is a demo Contact Manager application that we will create using Struts2 and Hibernate framework. In this article we will see how we can use Hibernate to perform Insert / Delete operations in Struts2 framework.
Our Goal
Our goal will be to demonstrate the use of Struts2 with Hibernate framework and to create a demo application [...]]]></description>
			<content:encoded><![CDATA[<p>This is a demo Contact Manager application that we will create using Struts2 and Hibernate framework. In this article we will see how we can use Hibernate to perform Insert / Delete operations in Struts2 framework.</p>
<h2>Our Goal</h2>
<p>Our goal will be to demonstrate the use of Struts2 with Hibernate framework and to create a demo application &#8220;Contact Manager&#8221;. The basic requirement of the Contact Manager app will be:</p>
<ol>
<li>Add new contact in the contact list.</li>
<li>Display all contacts from contact list.</li>
<li>Delete a contact from contact list.</li>
</ol>
<p>Once we will build the application it will look like:<br />
<img src="http://img.viralpatel.net/2010/01/struts2-hibernate-contact-manager.png" alt="struts2-hibernate-contact-manager" title="struts2-hibernate-contact-manager" width="450" height="419" class="aligncenter size-full wp-image-1994" /></p>
<h2>Getting Started</h2>
<p>For our Contact Manager example, we will use MySQL database. Create a table <strong>contacts</strong> in any MySQL database. This is very preliminary example and thus we have minimum columns to represent a contact. Feel free to extend this example and create a more complex application. </p>
<pre class="brush: sql;">
CREATE TABLE CONTACTS
(
	id 		INT PRIMARY KEY AUTO_INCREMENT,
	firstname 	VARCHAR(30),
	lastname	VARCHAR(30),
	cell_no		VARCHAR(15),
	email_id	VARCHAR(30),
	website		VARCHAR(150),
	birthdate	DATE,
	created		TIMESTAMP DEFAULT NOW()
);
</pre>
<h2>Creating Project in Eclipse</h2>
<p>Open Eclipse and goto File -> New -> Project and select <strong>Dynamic Web Project</strong> in the New Project wizard screen.<br />
<img alt="struts dynamic web project" src="http://img.viralpatel.net/2008/12/eclipse-new-project-struts-example.png" title="struts dynamic web project" class="aligncenter" width="369" height="365" /></p>
<p>After selecting Dynamic Web Project, press Next.<br />
<img alt="dynamic web project" src="http://img.viralpatel.net/2008/12/eclipse-new-dynamic-web-project-struts.png" title="dynamic web project" class="aligncenter" width="471" height="511" /></p>
<p>Write the name of the project. For example <strong>ContactManager</strong>. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press <strong>Finish</strong>.</p>
<p>We will need a source folder called <strong>resources</strong>. Right click on Project in project explorer and select New -> Source Folder and create a folder with name <em>resources</em>.</p>
<p>Also we will create Java packages for our application. As we will use Struts2, we will follow MVC architecture. Create 4 packages in the sources.<br />
<img src="http://img.viralpatel.net/2010/01/struts2-hibernate-package.png" alt="struts2-hibernate-package" title="struts2-hibernate-package" width="253" height="154" class="aligncenter size-full wp-image-1998" /></p>
<p>We created 4 new packages. The <strong>net.viralpatel.contact.controller</strong> will hold the Java class that will act as controller and will fetch the data from database and pass it to view. The <strong>net.viralpatel.contact.model</strong> package will hold the Hibernate persistent model class. The <strong>net.viralpatel.contact.view</strong> will contain the struts2 action class. And finally the <strong>net.viralpatel.contact.util</strong> will have some hibernate related util file that will be see shortly.</p>
<h2>Required JAR Files</h2>
<p>Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does not exists.<br />
<img src="http://img.viralpatel.net/2010/01/struts2-hibernate-required-jar.png" alt="" title="struts2-hibernate-required-jar" width="235" height="392" class="aligncenter size-full wp-image-1997" /></p>
<h2>Create JSP for Contact Manager</h2>
<p>We will need only one JSP file for this tutorial. The JSP will include a form to add new contact as well as will list the contacts at the end. Create a JSP file <strong>index.jsp</strong> in <strong>WebContent</strong> folder and copy following content into it.<br />
<strong>WebContent/index.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;Contact Manager - Struts2 Hibernate Example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;Contact Manager&lt;/h1&gt;
&lt;s:actionerror/&gt;

&lt;s:form action=&quot;add&quot; method=&quot;post&quot;&gt;
	&lt;s:textfield name=&quot;contact.firstName&quot; label=&quot;Firstname&quot;/&gt;
	&lt;s:textfield name=&quot;contact.lastName&quot; label=&quot;Lastname&quot;/&gt;
	&lt;s:textfield name=&quot;contact.emailId&quot; label=&quot;Email&quot;/&gt;
	&lt;s:textfield name=&quot;contact.cellNo&quot; label=&quot;Cell No.&quot;/&gt;
	&lt;s:textfield name=&quot;contact.website&quot; label=&quot;Homepage&quot;/&gt;
	&lt;s:textfield name=&quot;contact.birthDate&quot; label=&quot;Birthdate&quot;/&gt;
	&lt;s:submit value=&quot;Add Contact&quot; align=&quot;center&quot;/&gt;
&lt;/s:form&gt;

&lt;h2&gt;Contacts&lt;/h2&gt;
&lt;table&gt;
&lt;tr&gt;
	&lt;th&gt;Name&lt;/th&gt;
	&lt;th&gt;Email&lt;/th&gt;
	&lt;th&gt;Cell No.&lt;/th&gt;
	&lt;th&gt;Birthdate&lt;/th&gt;
	&lt;th&gt;Homepage&lt;/th&gt;
	&lt;th&gt;Delete&lt;/th&gt;
&lt;/tr&gt;
&lt;s:iterator value=&quot;contactList&quot; var=&quot;contact&quot;&gt;
	&lt;tr&gt;
		&lt;td&gt;&lt;s:property value=&quot;lastName&quot;/&gt;, &lt;s:property value=&quot;firstName&quot;/&gt; &lt;/td&gt;
		&lt;td&gt;&lt;s:property value=&quot;emailId&quot;/&gt;&lt;/td&gt;
		&lt;td&gt;&lt;s:property value=&quot;cellNo&quot;/&gt;&lt;/td&gt;
		&lt;td&gt;&lt;s:property value=&quot;birthDate&quot;/&gt;&lt;/td&gt;
		&lt;td&gt;&lt;a href=&quot;&lt;s:property value=&quot;website&quot;/&gt;&quot;&gt;link&lt;/a&gt;&lt;/td&gt;
		&lt;td&gt;&lt;a href=&quot;delete?id=&lt;s:property value=&quot;id&quot;/&gt;&quot;&gt;delete&lt;/a&gt;&lt;/td&gt;
	&lt;/tr&gt;
&lt;/s:iterator&gt;
&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Adding Hibernate Support</h2>
<p>For adding hibernate support, we will add following source code in Contact Manager application.<br />
<strong>hibernate.cfg.xml</strong> &#8211; This is the Hibernate configuration file. This file will contain configurations such as database connection information, persistence class info etc. Create <em>hibernate.cfg.xml</em> under <em>resources</em> folder and copy following content into it.</p>
<pre class="brush: xml;">
&lt;?xml version='1.0' encoding='utf-8'?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
        &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
        &quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;

&lt;hibernate-configuration&gt;
	&lt;session-factory&gt;
		&lt;property name=&quot;connection.driver_class&quot;&gt;
			com.mysql.jdbc.Driver
		&lt;/property&gt;
		&lt;property name=&quot;connection.url&quot;&gt;
			jdbc:mysql://localhost:3306/ContactManager
		&lt;/property&gt;
		&lt;property name=&quot;connection.username&quot;&gt;root&lt;/property&gt;
		&lt;property name=&quot;connection.password&quot;&gt;root&lt;/property&gt;
		&lt;property name=&quot;connection.pool_size&quot;&gt;1&lt;/property&gt;
		&lt;property name=&quot;dialect&quot;&gt;
			org.hibernate.dialect.MySQLDialect
		&lt;/property&gt;
		&lt;property name=&quot;current_session_context_class&quot;&gt;thread&lt;/property&gt;
		&lt;property name=&quot;cache.provider_class&quot;&gt;
			org.hibernate.cache.NoCacheProvider
		&lt;/property&gt;
		&lt;property name=&quot;show_sql&quot;&gt;true&lt;/property&gt;
		&lt;property name=&quot;hbm2ddl.auto&quot;&gt;update&lt;/property&gt;

		&lt;mapping class=&quot;net.viralpatel.contact.model.Contact&quot; /&gt;

	&lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p><strong>HibernateUtil.java</strong> &#8211; This is the Util file that we use to create connection with hibernate. Create HibernateUtil.java under package <strong>net.viralpatel.contact.util</strong> and copy following content into it.</p>
<pre class="brush: java;">
package net.viralpatel.contact.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			return new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println(&quot;Initial SessionFactory creation failed.&quot; + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}
</pre>
<p><strong>Contact.java</strong> &#8211; This is the persistence entity class that will map to Contacts table in MySQL. Create Contact.java under <strong>net.viralpatel.contact.model</strong> package and copy following content into it.</p>
<pre class="brush: java;">
package net.viralpatel.contact.model;

import java.io.Serializable;
import java.sql.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name=&quot;Contacts&quot;)
public class Contact implements Serializable{

	private static final long serialVersionUID = -8767337896773261247L;

	private Long id;
	private String firstName;
	private String lastName;
	private String emailId;
	private String cellNo;
	private Date birthDate;
	private String website;

	private Date created;

	@Id
	@GeneratedValue
	@Column(name=&quot;id&quot;)
	public Long getId() {
		return id;
	}
	@Column(name=&quot;firstname&quot;)
	public String getFirstName() {
		return firstName;
	}
	@Column(name=&quot;lastname&quot;)
	public String getLastName() {
		return lastName;
	}
	@Column(name=&quot;email_id&quot;)
	public String getEmailId() {
		return emailId;
	}
	@Column(name=&quot;cell_no&quot;)
	public String getCellNo() {
		return cellNo;
	}
	@Column(name=&quot;birthdate&quot;)
	public Date getBirthDate() {
		return birthDate;
	}
	@Column(name=&quot;website&quot;)
	public String getWebsite() {
		return website;
	}
	@Column(name=&quot;created&quot;)
	public Date getCreated() {
		return created;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}
	public void setCellNo(String cellNo) {
		this.cellNo = cellNo;
	}
	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}
	public void setCreated(Date created) {
		this.created = created;
	}
	public void setWebsite(String website) {
		this.website = website;
	}
}
</pre>
<p>Note how we have mapped Contact class with Contacts table using Java persistence API annotations.</p>
<h2>Adding Controller to access data</h2>
<p>We will add a controller class in Contact Manager application which will be used to get/save data from hibernate. This controller will be invoked from Struts action class. Create a file <strong>ContactManager.java</strong> under <strong>net.viralpatel.contact.controller</strong> package and copy following content into it.</p>
<pre class="brush: java;">
package net.viralpatel.contact.controller;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.classic.Session;

import net.viralpatel.contact.model.Contact;
import net.viralpatel.contact.util.HibernateUtil;

public class ContactManager extends HibernateUtil {

	public Contact add(Contact contact) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(contact);
		session.getTransaction().commit();
		return contact;
	}
	public Contact delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Contact contact = (Contact) session.load(Contact.class, id);
		if(null != contact) {
			session.delete(contact);
		}
		session.getTransaction().commit();
		return contact;
	}

	public List&lt;Contact&gt; list() {

		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List&lt;Contact&gt; contacts = null;
		try {

			contacts = (List&lt;Contact&gt;)session.createQuery(&quot;from Contact&quot;).list();

		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return contacts;
	}
}
</pre>
<p>Note that how we have created different methods in controller class to add/delete/list the contacts. Also the ContactManager class is extending HibernateUtil class thus allowing it to access <strong>sessionFactory</strong> object.</p>
<h2>Adding Struts2 Support</h2>
<p>Let us add Struts2 support to our web application. For that, will add following entry in deployment descriptor (WEB-INF/web.xml).</p>
<h3> Add Struts2 Filter in web.xml</h3>
<pre class="brush: xml;">
&lt;filter&gt;
	&lt;filter-name&gt;struts2&lt;/filter-name&gt;
	&lt;filter-class&gt;
		org.apache.struts2.dispatcher.FilterDispatcher
	&lt;/filter-class&gt;
&lt;/filter&gt;
&lt;filter-mapping&gt;
	&lt;filter-name&gt;struts2&lt;/filter-name&gt;
	&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;
</pre>
<h3>Creating struts.xml</h3>
<p>We will need to create struts.xml file that will hold the action mapping for our example. Create a file <strong>struts.xml</strong> in resources folder and add following content into it.<br />
<strong>struts.xml</strong></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE struts PUBLIC
    &quot;-//Apache Software Foundation//DTD Struts Configuration 2.0//EN&quot;
    &quot;http://struts.apache.org/dtds/struts-2.0.dtd&quot;&gt;

&lt;struts&gt;
	&lt;constant name=&quot;struts.enable.DynamicMethodInvocation&quot;
		value=&quot;false&quot; /&gt;
	&lt;constant name=&quot;struts.devMode&quot; value=&quot;false&quot; /&gt;

	&lt;package name=&quot;default&quot; extends=&quot;struts-default&quot; namespace=&quot;/&quot;&gt;

		&lt;action name=&quot;add&quot;
			class=&quot;net.viralpatel.contact.view.ContactAction&quot; method=&quot;add&quot;&gt;
			&lt;result name=&quot;success&quot; type=&quot;chain&quot;&gt;index&lt;/result&gt;
			&lt;result name=&quot;input&quot; type=&quot;chain&quot;&gt;index&lt;/result&gt;
		&lt;/action&gt;

		&lt;action name=&quot;delete&quot;
			class=&quot;net.viralpatel.contact.view.ContactAction&quot; method=&quot;delete&quot;&gt;
			&lt;result name=&quot;success&quot; type=&quot;chain&quot;&gt;index&lt;/result&gt;
		&lt;/action&gt;

		&lt;action name=&quot;index&quot;
			class=&quot;net.viralpatel.contact.view.ContactAction&quot;&gt;
			&lt;result name=&quot;success&quot;&gt;index.jsp&lt;/result&gt;
		&lt;/action&gt;
	&lt;/package&gt;
&lt;/struts&gt;
</pre>
<p><strong>Related:</strong><br />
<a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html">Create Struts Application in Eclipse</a><br />
<a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html">Create Struts2 Application in Eclipse</a></p>
<h3>Create Action class</h3>
<p>Up-till now we have almost completed our Contact Manager application in Struts2 and Hibernate. Only task left is to add Struts Action class. Create a class <strong>ContactAction.java</strong> under <strong>net.viralpatel.contact.view</strong> package and copy following content into it.</p>
<pre class="brush: java;">
package net.viralpatel.contact.view;

import java.util.List;

import net.viralpatel.contact.controller.ContactManager;
import net.viralpatel.contact.model.Contact;

import com.opensymphony.xwork2.ActionSupport;

public class ContactAction extends ActionSupport {

	private static final long serialVersionUID = 9149826260758390091L;
	private Contact contact;
	private List&lt;Contact&gt; contactList;
	private Long id;

	private ContactManager linkController;

	public ContactAction() {
		linkController = new ContactManager();
	}
	public String execute() {
		if(null != contact) {
			linkController.add(getContact());
		}
		this.contactList = linkController.list();
		System.out.println(contactList);
		System.out.println(contactList.size());
		return SUCCESS;
	}
	public String add() {
		System.out.println(getContact());
		try {
		linkController.add(getContact());
		}catch(Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	public String delete() {
		linkController.delete(getId());
		return SUCCESS;
	}
	public Contact getContact() {
		return contact;
	}
	public List&lt;Contact&gt; getContactList() {
		return contactList;
	}
	public void setContact(Contact contact) {
		this.contact = contact;
	}
	public void setContactList(List&lt;Contact&gt; contactsList) {
		this.contactList = contactsList;
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
}
</pre>
<p><code>ContactAction</code> class contains different methods that gets called by Struts2. The execute() method is the default method which gets called when we call /index action from browser. It fetches the list of contacts and display it in index.jsp. Similarly, when a new contact is added, add() method is called. If you check the action mapping entry in <code>struts.xml</code> for <code>add()</code> method, the &lt;result&gt; is mapped with <code>/index</code> action and the type is chain. This is because we want to display the list of contact once we add a new one. Hence we have done Action chaining and called <code>/index</code> action after <code>/add</code> action.</p>
<h2>The Contact Manager App</h2>
<p>That&#8217;s it. The app is ready, just compile and run the project in Eclipse Run -> Run As -> Run on Server. Set the URL to:<br />
<strong>http://localhost:&lt;port&gt;/&lt;project name&gt;/index</strong></p>
<p><img src="http://img.viralpatel.net/2010/01/struts2-hibernate-contact-manager.png" alt="struts2-hibernate-contact-manager" title="struts2-hibernate-contact-manager" width="450" height="419" class="aligncenter size-full wp-image-1994" /><br />
Fill the contact form and hit enter and the new contact will be persisted in database and will be shown in below table. Similarly, click on <em>delete</em> link next to a record. It will delete the record from database.</p>
<p>Let me know your input about this application.<br />
Cheers. </p>
<h2>Download Source</h2>
<p><a href="http://viralpatel.net/blogs/download/hibernate/StrutsHibernate.zip">Download Source without JAR files (19.2 KB)</a></p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate ">Writing a URL Shortner in Java Struts2 &#038; Hibernate </a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/10/inner-classes-in-java.html" title="Inner classes in Java, the mystery within.">Inner classes in Java, the mystery within.</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html&amp;title=Tutorial: Create Struts2 Hibernate Example in Eclipse&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html&amp;title=Tutorial: Create Struts2 Hibernate Example in Eclipse" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html&amp;title=Tutorial: Create Struts2 Hibernate Example in Eclipse" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html&amp;title=Tutorial: Create Struts2 Hibernate Example in Eclipse" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>Struts 2 Ajax Tutorial with Example</title>
		<link>http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html</link>
		<comments>http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html#comments</comments>
		<pubDate>Wed, 13 Jan 2010 09:46:27 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Struts]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[struts2-series]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1985</guid>
		<description><![CDATA[Welcome to the last part of 7 article series of Struts 2 Framework tutorials. In previous article we saw how to implement File Upload functionality in Struts 2. In this article we will see how we can implement Ajax support in a webapplication using Struts2 framework.
AJAX support in Struts 2
Struts 2 provides built-in support to [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to the last part of 7 article series of Struts 2 Framework tutorials. In <a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">previous article</a> we saw how to implement File Upload functionality in Struts 2. In this article we will see how we can implement Ajax support in a webapplication using Struts2 framework.<br />
<style type="text/css">#struts { color:#222222; width: 98%; background-color: #EEFF99; padding:5px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }#struts h3 { font-size: 18px; text-decoration:underline; }#struts ul { list-style:none; }#struts ul li { padding:3px; }</style><div id="struts"><h3>Struts 2 Tutorials</h3><ul>	<li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1: Introduction to Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Part 2: Create Hello World Application in Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">Part 6: Struts 2 File Upload and Save Example</a></li>	<li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html">Part 7: Struts 2 Ajax Tutorial with Example</a></li></ul></div></p>
<h2>AJAX support in Struts 2</h2>
<p>Struts 2 provides built-in support to AJAX using Dojo Toolkit library. If you are new to Dojo, you may want to go through the <a href="http://viralpatel.net/blogs/2009/02/introduction-to-dojo-toolkit-javascript-framework.html">Introduction of DOJO Toolkit</a>.</p>
<p>Struts 2 comes with powerful set of Dojo AJAX APIs which you can use to add Ajax support. In order to add Ajax support, you need to add following JAR file in your classpath:<br />
<strong>struts2-dojo-plugin.jar</strong></p>
<p>Also once we add this JAR file, we need to add following code snippet in whatever JSP file we need to add AJAX support.</p>
<pre class="brush: xml;">
&lt;%@ taglib prefix=&quot;sx&quot; uri=&quot;/struts-dojo-tags&quot;%&gt;
</pre>
<p>First define the taglib sx which we will use to add AJAX enabled tags.</p>
<pre class="brush: xml;">
&lt;sx:head/&gt;
</pre>
<p>Add this head tag in your JSP between &lt;head&gt; &#8230; &lt;/head&gt; tags. This sx:head tag will include required javascript and css files to implement Ajax.</p>
<h2>AJAX Example: Struts2 Ajax Drop Down</h2>
<p>Let us add simple AJAX support in our StrutsHelloWorld web application. We will use the base code that we used in previous articles and add Ajax on top of it.</p>
<p>We will create a drop down which will Autocomplete and suggest the input. For this we will add Dojo support to our webapp.</p>
<h3>Step 1: Adding JAR file</h3>
<p>As discussed earlier we will add struts2-dojo-plugin.jar in classpath (WEB-INF/lib). Thus, following is the list of required jar files. Note that these jars are needed to run full application including all the samples of previous parts of this tutorial series.<br />
<img src="http://img.viralpatel.net/2010/01/struts2-ajax-jar-files.png" alt="struts2-ajax-jar-files" title="struts2-ajax-jar-files" width="228" height="288" class="aligncenter size-full wp-image-1986" /></p>
<h3>Step 2: Create AJAX Action class</h3>
<p>We will create an action class which will get called for our Ajax example. Create a file <code>AjaxAutocomplete.java</code> in <code>net.viralpatel.struts2</code> package and copy following content into it.<br />
<strong>AjaxAutocomplete.java</strong></p>
<pre class="brush: java;">
package net.viralpatel.struts2;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import com.opensymphony.xwork2.ActionSupport;

public class AjaxAutocomplete extends ActionSupport {
	private String data = &quot;Afghanistan, Zimbabwe, India, United States, Germany, China&quot;;
	private List&lt;String&gt; countries;
	private String country;

	public String execute() {
		countries = new ArrayList&lt;String&gt;();
		StringTokenizer st = new StringTokenizer(data, &quot;,&quot;);

		while (st.hasMoreTokens()) {
			countries.add(st.nextToken().trim());
		}
		return SUCCESS;
	}
	public String getCountry() {
		return this.country;
	}

	public List&lt;String&gt; getCountries() {
		return countries;
	}

	public void setCountries(List&lt;String&gt; countries) {
		this.countries = countries;
	}
	public void setCountry(String country) {
		this.country = country;
	}
}
</pre>
<p>In above code we have created a simple action class with attribute <code>String country</code> and <code>List countries</code>. The countries list will be populated with country names when execute() method is called. Here for this example, we have loaded static data. You may feel free to change this and add data from database.</p>
<h3>Step 3: Create JSP</h3>
<p>Create JSP file to display Autocomplete textbox for our Ajax action. Create AjaxDemo.jsp in WebContent directory.<br />
<strong>AjaxDemo.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;%@ taglib prefix=&quot;sx&quot; uri=&quot;/struts-dojo-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;Welcome&lt;/title&gt;
	&lt;sx:head /&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h2&gt;Struts 2 Autocomplete (Drop down) Example!&lt;/h2&gt;

	Country:
	&lt;sx:autocompleter size=&quot;1&quot; list=&quot;countries&quot; name=&quot;country&quot;&gt;&lt;/sx:autocompleter&gt;
	&lt;/action&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In above JSP file we have used sx:autocompleter tag to render an autocomplete drop down which users Ajax class to fetch data internally. Note that we have mapped the <code>list</code> attribute with <code>List countries</code>.</p>
<h3>Step 4: Creating Struts.xml entry</h3>
<p>Add following action entry in Struts.xml file:</p>
<pre class="brush: xml;">
&lt;action name=&quot;ajaxdemo&quot; class=&quot;net.viralpatel.struts2.AjaxAutocomplete&quot;&gt;
	&lt;interceptor-ref name=&quot;loggingStack&quot;&gt;&lt;/interceptor-ref&gt;
	&lt;result name=&quot;success&quot; type=&quot;tiles&quot;&gt;/ajaxdemo.tiles&lt;/result&gt;
	&lt;result type=&quot;tiles&quot;&gt;/ajaxdemo.tiles&lt;/result&gt;
&lt;/action&gt;
</pre>
<p>Notice that we are using Tiles here in this example. You may want to use AjaxDemo.jsp instead of /ajaxdemo.tiles to render the output directly in JSP.</p>
<h2>That&#8217;s All Folks</h2>
<p>Compile and Run the application in eclipse.<br />
<img src="http://img.viralpatel.net/2010/01/struts2-ajax-drop-down.png" alt="struts2-ajax-drop-down" title="struts2-ajax-drop-down" width="448" height="517" class="aligncenter size-full wp-image-1987" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-7-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (24KB)</strong></a></p>
<h2>Conclusion</h2>
<p>Struts2 Framework provides wide variety of features to create a rich web application. In this Struts2 series we saw different aspects of Struts 2 like <a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">introduction of struts2</a>, <a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">hello world application</a>, <a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">validation framework</a>, <a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">tiles plugin</a>, <a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">strurts2 interceptors</a>, <a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">file upload</a> and ajax support. </p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate ">Writing a URL Shortner in Java Struts2 &#038; Hibernate </a></li><li><a href="http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html" title="Tutorial: Create Struts2 Hibernate Example in Eclipse">Tutorial: Create Struts2 Hibernate Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" title="Introduction to Struts 2 Framework">Introduction to Struts 2 Framework</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html&amp;title=Struts 2 Ajax Tutorial with Example&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html&amp;title=Struts 2 Ajax Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html&amp;title=Struts 2 Ajax Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html&amp;title=Struts 2 Ajax Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Configuring MDP and Controlling it With and Without JMX</title>
		<link>http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html</link>
		<comments>http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html#comments</comments>
		<pubDate>Thu, 07 Jan 2010 20:05:13 +0000</pubDate>
		<dc:creator>Vinay Tawney</dc:creator>
				<category><![CDATA[J2EE]]></category>
		<category><![CDATA[jmx]]></category>
		<category><![CDATA[message driven bean]]></category>
		<category><![CDATA[Spring]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1976</guid>
		<description><![CDATA[This note demonstrates how to create and deploy an MDP, and how to control it, using both Spring’s inbuilt component management mechanisms, and JMX.
Scenario
We have a number of JMS listeners in our application. Having ported our hardware to a grid of virtual machines, we want the feature to switch-on and switch-off the listeners on the [...]]]></description>
			<content:encoded><![CDATA[<p>This note demonstrates how to create and deploy an MDP, and how to control it, using both Spring’s inbuilt component management mechanisms, and JMX.</p>
<h2>Scenario</h2>
<p>We have a number of JMS listeners in our application. Having ported our hardware to a grid of virtual machines, we want the feature to switch-on and switch-off the listeners on the VMs, and re-allocate the listeners to VMs across the grid on-demand, to make best use of the resources.</p>
<h2>Scope</h2>
<p>This note just deals briefly with configuring the MDP, and switching it on and off.</p>
<h2>Concepts</h2>
<p>- What is an MDP?<br />
- MDP stands for Message Driven Pojo.</p>
<p>In the EJB world we have MDBs (Message Driven Beans). These are standard JEE components which are configured on a server and which act as a Message Listener.</p>
<p>Spring provides MDPs as an answer to MDBs.</p>
<p>Some helpful links are:</p>
<ul>
<li>MDB<br />
<a rel="nofollow" target="_blank" href="http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts5.html">http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts5.html</a></li>
<li>MDP<br />
<a rel="nofollow" target="_blank" href="http://static.springsource.org/spring/docs/2.5.x/reference/jms.html">http://static.springsource.org/spring/docs/2.5.x/reference/jms.html</a><br />
<a rel="nofollow" target="_blank" href="http://static.springsource.org/spring/docs/2.5.x/reference/jms.html#jms-asynchronousMessageReception">http://static.springsource.org/spring/docs/2.5.x/reference/jms.html#jms-asynchronousMessageReception</a></li>
<li>JMX<br />
<a rel="nofollow" target="_blank" href="http://java.sun.com/j2se/1.5.0/docs/guide/jmx/">http://java.sun.com/j2se/1.5.0/docs/guide/jmx/</a></p>
<p><a rel="nofollow" target="_blank" href="http://java.sun.com/j2se/1.5.0/docs/guide/jmx/overview/JMXoverviewTOC.html">http://java.sun.com/j2se/1.5.0/docs/guide/jmx/overview/JMXoverviewTOC.html</a></p>
<p><a rel="nofollow" target="_blank" href="http://tomcat.apache.org/tomcat-5.5-doc/monitoring.html">http://tomcat.apache.org/tomcat-5.5-doc/monitoring.html</a></li>
<li>Spring JMX<br />
<a rel="nofollow" target="_blank" href="http://static.springsource.org/spring/docs/2.5.x/reference/jmx.html">http://static.springsource.org/spring/docs/2.5.x/reference/jmx.html</a></li>
</ul>
<h2>Creating a simple Spring MDP component, and controlling it using the Spring container provided “start” and “stop” methods</h2>
<h3>MDP Spring configuration</h3>
<p>Extract from the Spring Config XML file spring_context_jms.xml</p>
<pre class="brush: xml;">
&lt;!-- Destination configuration --&gt;
&lt;bean id=&quot;sample_queue&quot;
		class=&quot;org.apache.activemq.command.ActiveMQQueue&quot;
		autowire=&quot;constructor&quot;&gt;
		&lt;constructor-arg&gt;
			&lt;value&gt;SAMPLE.QUEUE&lt;/value&gt;
		&lt;/constructor-arg&gt;
&lt;/bean&gt;

&lt;!-- Message Listener Container configuration --&gt;
&lt;bean id=&quot;sample_jmsContainer&quot;
class=&quot;org.springframework.jms.listener.DefaultMessageListenerContainer102&quot;&gt;
		&lt;property name=&quot;connectionFactory&quot;
			ref=&quot;activeMqQueueConnectionFactory&quot; /&gt;
		&lt;property name=&quot;destination&quot; ref=&quot; sample_queue&quot; /&gt;
		&lt;property name=&quot;messageListener&quot;
			ref=&quot;sample_messageListener&quot; /&gt;
&lt;/bean&gt;

&lt;!-- Message Driven POJO (MDP) configuration --&gt;
	&lt;bean id=&quot;sample_messageListener&quot;
		class=&quot;jmsexample.ExampleListener&quot;&gt;
&lt;property name=&quot;listener&quot; ref=&quot;sample_jmsContainer&quot; /&gt;
	&lt;/bean&gt;
</pre>
<p>The sample class we create (sample_messageListener of class &#8220;jmsexample.ExampleListener&#8221;) must extend javax.jms.MessageListener and implement the “onMessage” method.</p>
<p>As seen from the Spring configuration above, we have provided this as a ref to the &#8220;messageListener&#8221; property in the “DefaultMessageListenerContainer102” class.</p>
<p>Also as seen above, we have provided a ref to &#8220;sample_jmsContainer&#8221; in the bean &#8220;sample_messageListener&#8221;. (This is so that we are able to expose it using JMX &#8211; as discussed further on).</p>
<h3>Configuring Spring components in a Web application in Tomcat</h3>
<p>The MDPs are deployed in a Web application as JMSWebApplication.war.<br />
Follows is an extract from the web.xml</p>
<pre class="brush: xml;">
&lt;display-name&gt;JMSWebApplication&lt;/display-name&gt;
&lt;welcome-file-list&gt;
    &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
    &lt;welcome-file&gt;default.html&lt;/welcome-file&gt;
&lt;/welcome-file-list&gt;
&lt;context-param&gt;
    &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt;
    &lt;param-value&gt;classpath:spring_context.xml&lt;/param-value&gt;
&lt;/context-param&gt;
&lt;listener&gt;
    &lt;description&gt;Context Loader Listener&lt;/description&gt;
    &lt;listener-class&gt;
org.springframework.web.context.ContextLoaderListener
    &lt;/listener-class&gt;
&lt;/listener&gt;
</pre>
<h3>Getting a handle to the Spring’s “Listener Container” component and calling start and stop on it (Non-JMX)</h3>
<p>Follows is a relevant extract from the client jsp:</p>
<pre class="brush: java;">
&lt;%@page import=&quot;org.springframework.beans.factory.BeanFactory,org.springframework.context.ApplicationContext,org.springframework.context.support.ClassPathXmlApplicationContext,org.springframework.jms.listener.DefaultMessageListenerContainer102,org.springframework.web.context.WebApplicationContext,org.springframework.web.context.support.WebApplicationContextUtils&quot;%&gt;

ServletContext context = application
				.getContext(&quot;/JMSWebApplication&quot;);
	WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(context);

DefaultMessageListenerContainer102 listener = (DefaultMessageListenerContainer102) wac
				.getBean(&quot;sample_jmsContainer&quot;);

listener.stop();
//listener.start();
</pre>
<h2>Exposing and Controlling the Listener component using Spring JMX</h2>
<p>This involves configuring Spring JMX.<br />
Since this is deployed in Tomcat, we will enable JMX in Tomcat and connect to it using jconsole to control this component.</p>
<h3>Configuring Spring JMX (server/container), and Exposing the component in JMX</h3>
<pre class="brush: xml;">
&lt;bean id=&quot;exporter&quot;
		class=&quot;org.springframework.jmx.export.MBeanExporter&quot;&gt;
		&lt;property name=&quot;beans&quot;&gt;
			&lt;map&gt;
				&lt;entry key=&quot;bean:name=sample_listener_jmx&quot;
					value-ref=&quot; sample_messageListener&quot; /&gt;
			&lt;/map&gt;
		&lt;/property&gt;
	&lt;/bean&gt;
</pre>
<h3>Arguments to Tomcat to enable JMX</h3>
<p>Provide these (self-explanatory) arguments to the JVM while starting up Tomcat </p>
<pre class="brush: xml;">
      -Dcom.sun.management.jmxremote.port=10088 \
      -Dcom.sun.management.jmxremote.ssl=false \
      -Dcom.sun.management.jmxremote.authenticate=false \
</pre>
<h3>Code skeleton of   jmsexample. ExampleListener </h3>
<p>(Note the “startListener” and “stopListener” methods,  and use of the “DefaultMessageListenerContainer102”  class.)</p>
<pre class="brush: java;">
package jmsexample;
&lt; imports come here ... &gt;

public class ExampleListener implements MessageListener {

	private DefaultMessageListenerContainer102 listener;
	&lt; other variables here ... &gt;

	public void onMessage(Message message) {

		&lt; Business Logic here ... &gt;

	}

	@ManagedAttribute(description = &quot;Starts the Listener&quot;, currencyTimeLimit = 15)
	public void startListener() {

		System.out.println(&quot;Starting listener&quot;);
		getListener().start();
		System.out.println(&quot;listener started &quot; + getListener().isRunning());
	}

	@ManagedAttribute(description = &quot;Stops the Listener&quot;, currencyTimeLimit = 15)
	public void stopListener() {

		System.out.println(&quot;Stopping listener&quot;);
		getListener().stop();
		System.out.println(&quot;listener stopped &quot; + getListener().isRunning());
	}

	public DefaultMessageListenerContainer102 getListener() {
		return listener;
	}

	public void setListener(DefaultMessageListenerContainer102 listener) {
		this.listener = listener;
	}

	&lt; other methods here ...&gt;
}
</pre>
<h2>View in jconsole of controlling the component</h2>
<p>(Note the “startListener” and “stopListener” methods exposed)<br />
The remote connection string here, for example, is service:jmx:rmi:///jndi/rmi://localhost:10088/jmxrmi<br />
<img src="http://img.viralpatel.net/2010/01/jconsole-controller.png" alt="jconsole-controller" title="jconsole-controller" width="675" height="551" class="aligncenter size-full wp-image-1977" /></p>
<h2>A simple java based rmi client using Tomcat JMX to control the components</h2>
<h3>Client code snippet and configuration</h3>
<pre class="brush: java;">
String address =
         &quot;service:jmx:rmi:///jndi/rmi://localhost:10088/jmxrmi&quot;;
	JMXServiceURL serviceURL = new JMXServiceURL(address);
	Map&lt;String, Object&gt; environment = null;
	JMXConnector connector = JMXConnectorFactory.connect(serviceURL,
				environment);
	MBeanServerConnection mBeanConnection = connector
				.getMBeanServerConnection();

	ObjectName exampleServiceName = ObjectName
				.getInstance(&quot;bean:name=sample_listener_jmx&quot;);

mBeanConnection.invoke(exampleServiceName, &quot;startListener&quot;, null, null);
//mBeanConnection.invoke(exampleServiceName, &quot;stopListener&quot;, null, null);
</pre>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2008/12/tutorial-struts-spring-framework-example-in-eclipse.html" title="Tutorial:Struts Spring framework example in Eclipse.">Tutorial:Struts Spring framework example in Eclipse.</a></li><li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" title="Introduction to Struts 2 Framework">Introduction to Struts 2 Framework</a></li><li><a href="http://viralpatel.net/blogs/2009/10/according-to-tld-or-attribute-directive-in-tag-file-issue.html" title="Solving &#8220;According to TLD or attribute directive in tag file&#8221; issue">Solving &#8220;According to TLD or attribute directive in tag file&#8221; issue</a></li><li><a href="http://viralpatel.net/blogs/2009/02/http-session-handling-tutorial-using-servlet-filters-session-error-filter-servlet-filter.html" title="Tutorial: HTTP Session handling using Servlet Filters">Tutorial: HTTP Session handling using Servlet Filters</a></li><li><a href="http://viralpatel.net/blogs/2009/01/tutorial-java-servlet-filter-example-using-eclipse-apache-tomcat.html" title="Java Servlet Filter tutorial example using Eclipse &#038; Tomcat">Java Servlet Filter tutorial example using Eclipse &#038; Tomcat</a></li><li><a href="http://viralpatel.net/blogs/2008/12/tutorial-create-custom-tag-library-taglib-in-jsp.html" title="Tutorial: Create JSP custom tag library">Tutorial: Create JSP custom tag library</a></li><li><a href="http://viralpatel.net/blogs/2008/12/implement-ldap-authentication-in-tomcat-jboss-server-for-java-app.html" title="Implement LDAP authentication in Tomcat &#038; JBoss server for Java app">Implement LDAP authentication in Tomcat &#038; JBoss server for Java app</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html&amp;title=Configuring MDP and Controlling it With and Without JMX&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html&amp;title=Configuring MDP and Controlling it With and Without JMX" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html&amp;title=Configuring MDP and Controlling it With and Without JMX" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html&amp;title=Configuring MDP and Controlling it With and Without JMX" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Struts 2 File Upload and Save Tutorial with Example</title>
		<link>http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html</link>
		<comments>http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html#comments</comments>
		<pubDate>Wed, 30 Dec 2009 16:11:56 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[How-To]]></category>
		<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[struts file upload]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[struts2-series]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1969</guid>
		<description><![CDATA[Welcome to Part-6 of 7-part series of Struts2 Framework. In previous part we went through basics of Struts2 Interceptors. Also we created a custom interceptor and integrated it through Struts2 application.
It is strongly recommended to go through previous articles in case you new to Struts2 Framework.
Today we will see how to do File Upload in [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to Part-6 of 7-part series of Struts2 Framework. In <a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">previous part</a> we went through basics of Struts2 Interceptors. Also we created a custom interceptor and integrated it through Struts2 application.</p>
<p>It is strongly recommended to go through previous articles in case you new to Struts2 Framework.<br />
<style type="text/css">#struts { color:#222222; width: 98%; background-color: #EEFF99; padding:5px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }#struts h3 { font-size: 18px; text-decoration:underline; }#struts ul { list-style:none; }#struts ul li { padding:3px; }</style><div id="struts"><h3>Struts 2 Tutorials</h3><ul>	<li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1: Introduction to Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Part 2: Create Hello World Application in Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">Part 6: Struts 2 File Upload and Save Example</a></li>	<li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html">Part 7: Struts 2 Ajax Tutorial with Example</a></li></ul></div></p>
<p>Today we will see how to do File Upload in Struts2. We will use Struts2 built-in <strong>FileUploadInterceptor</strong> in our example to upload the file. The Struts 2 File Upload Interceptor is based on MultiPartRequestWrapper, which is automatically applied to the request if it contains the file element.</p>
<h2>Required JAR file</h2>
<p>Before we start, we need to make sure <strong>commons-io.jar</strong> file is present in the classpath. Following are the list of required Jar files.<br />
<img src="http://img.viralpatel.net/2009/12/struts2-file-upload-jar-files.png" alt="struts2-file-upload-jar-files" title="struts2-file-upload-jar-files" width="208" height="259" class="aligncenter size-full wp-image-1971" /></p>
<h2>Getting Started</h2>
<p>In order to add file upload functionality we will add an action class <strong>FileUploadAction</strong> to our project. Create file <code>FileUploadAction.java</code> in package <code>net.viralpatel.struts2</code>.<br />
 FileUploadAction.java</p>
<pre class="brush: java;">
package net.viralpatel.struts2;

import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport implements
		ServletRequestAware {
	private File userImage;
	private String userImageContentType;
	private String userImageFileName;

	private HttpServletRequest servletRequest;

	public String execute() {
		try {

			String filePath = servletRequest.getRealPath(&quot;/&quot;);
			System.out.println(&quot;Server path:&quot; + filePath);
			File fileToCreate = new File(filePath, this.userImageFileName);

			FileUtils.copyFile(this.userImage, fileToCreate);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());

			return INPUT;
		}
		return SUCCESS;
	}

	public File getUserImage() {
		return userImage;
	}

	public void setUserImage(File userImage) {
		this.userImage = userImage;
	}

	public String getUserImageContentType() {
		return userImageContentType;
	}

	public void setUserImageContentType(String userImageContentType) {
		this.userImageContentType = userImageContentType;
	}

	public String getUserImageFileName() {
		return userImageFileName;
	}

	public void setUserImageFileName(String userImageFileName) {
		this.userImageFileName = userImageFileName;
	}

	@Override
	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;

	}
}
</pre>
<p>In above class file we have declared few attributes:</p>
<ul>
<li><code>private File userImage;</code> -> This will store actual uploaded File</li>
<li><code>private String userImageContentType;</code> -> This string will contain the Content Type of uploaded file. </li>
<li><code>private String userImageFileName;</code> -> This string will contain the file name of uploaded file.</li>
</ul>
<p>The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string. The name should be <file attribute>ContentType and <file attribute>FileName. For example if the file attribute in action file is <code>private File uploadedFile</code>, the content type will be uploadedFileContentType and file name uploadedFileFileName.</p>
<p>Also note in above action class, we have implemented interface <strong>org.apache.struts2.interceptor.ServletRequestAware</strong>. This is to get servletRequest object. We are using this path to save the uploaded file in <code>execute()</code> method. We have used <code>FileUtil.copyFile()</code> method of commons-io package to copy the uploaded file in root folder. This file will be retrieved in JSP page and displayed to user.</p>
<h2>The JSPs</h2>
<p>Create two JSP file in WebContent folder. UserImage.jsp will display a form to user to upload image. On submit, the file will be uploaded and saved on server. User will be sent to SuccessUserImage.jsp file where File details will be displayed. Copy following code into it.<br />
<strong>UserImage.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Upload User Image&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;h2&gt;Struts2 File Upload &amp; Save Example&lt;/h2&gt;
&lt;s:actionerror /&gt;
&lt;s:form action=&quot;userImage&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
	&lt;s:file name=&quot;userImage&quot; label=&quot;User Image&quot; /&gt;
	&lt;s:submit value=&quot;Upload&quot; align=&quot;center&quot; /&gt;
&lt;/s:form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>SuccessUserImage.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Success: Upload User Image&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h2&gt;Struts2 File Upload Example&lt;/h2&gt;
	User Image: &lt;s:property value=&quot;userImage&quot;/&gt;
	&lt;br/&gt;
	Content Type: &lt;s:property value=&quot;userImageContentType&quot;/&gt;
	&lt;br/&gt;
	File Name: &lt;s:property value=&quot;userImageFileName&quot;/&gt;
	&lt;br/&gt;
	Uploaded Image:
	&lt;br/&gt;
	&lt;img src=&quot;&lt;s:property value=&quot;userImageFileName&quot;/&gt;&quot;/&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h2>Struts.xml entry</h2>
<p>Add following entry for FileUploadAction class to struts.xml file.</p>
<pre class="brush: xml;">
		&lt;action name=&quot;userImage&quot;
			class=&quot;net.viralpatel.struts2.FileUploadAction&quot;&gt;
			&lt;interceptor-ref name=&quot;fileUpload&quot;&gt;
				&lt;param name=&quot;maximumSize&quot;&gt;2097152&lt;/param&gt;
				&lt;param name=&quot;allowedTypes&quot;&gt;
					image/png,image/gif,image/jpeg,image/pjpeg
				&lt;/param&gt;
			&lt;/interceptor-ref&gt;
			&lt;interceptor-ref name=&quot;defaultStack&quot;&gt;&lt;/interceptor-ref&gt;
			&lt;result name=&quot;success&quot;&gt;SuccessUserImage.jsp&lt;/result&gt;
			&lt;result name=&quot;input&quot;&gt;UserImage.jsp&lt;/result&gt;
		&lt;/action&gt;
</pre>
<p>Note that in above entry we have specified two parameter to fileUpload interceptor, <strong>maximumSize</strong> and <strong>allowedTypes</strong>. These are optional parameters that we can specify to interceptor. The maximumSize param will set the maximum file size that can be uploaded. By default this is 2MB. And the allowedTypes param specify the allowed content types of file which can be uploaded. Here we have specified it to be an image file (image/png,image/gif,image/jpeg,image/pjpeg).</p>
<p>The file upload interceptor also does the validation and adds errors, these error messages are stored in the struts-messsages.properties file. The values of the messages can be overridden by providing the text for the following keys:</p>
<ul>
<li><strong>struts.messages.error.uploading</strong> &#8211; error when uploading of file fails</li>
<li><strong>struts.messages.error.file.too.large</strong> &#8211; error occurs when file size is large</li>
<li><strong>struts.messages.error.content.type.not.allowed</strong> &#8211; when the content type is not allowed</li>
</ul>
<h2>That&#8217;s All Folks</h2>
<p>Compile and Execute the project in eclipse and goto link http://localhost:8080/StrutsHelloWorld/UserImage.jsp<br />
<b>Image Upload Screen</b><br />
<img src="http://img.viralpatel.net/2009/12/struts2-file-upload-example.png" alt="struts2-file-upload-example" title="struts2-file-upload-example" width="455" height="319" class="aligncenter size-full wp-image-1972" /></p>
<p>Image Upload Screen in case of error<br />
<img src="http://img.viralpatel.net/2009/12/struts2-file-upload-error.jpg" alt="struts2-file-upload-error" title="struts2-file-upload-error" width="436" height="370" class="aligncenter size-full wp-image-1974" /><br />
Image Upload Screen on success<br />
<img src="http://img.viralpatel.net/2009/12/struts2-file-upload-success.jpg" alt="struts2-file-upload-success" title="struts2-file-upload-success" width="540" height="576" class="aligncenter size-full wp-image-1973" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-6-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (20KB)</strong></a></p>
<h2>Moving On</h2>
<p>Struts2 makes life very easy. It was like a piece of cake to implement File Upload with Struts2. In next part we will see Struts2 Ajax Example.</p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate ">Writing a URL Shortner in Java Struts2 &#038; Hibernate </a></li><li><a href="http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html" title="Tutorial: Create Struts2 Hibernate Example in Eclipse">Tutorial: Create Struts2 Hibernate Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" title="Introduction to Struts 2 Framework">Introduction to Struts 2 Framework</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html&amp;title=Struts 2 File Upload and Save Tutorial with Example&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html&amp;title=Struts 2 File Upload and Save Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html&amp;title=Struts 2 File Upload and Save Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html&amp;title=Struts 2 File Upload and Save Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Struts2 Interceptors Tutorial with Example</title>
		<link>http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html</link>
		<comments>http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html#comments</comments>
		<pubDate>Tue, 29 Dec 2009 15:45:22 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Struts]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[struts2-interceptors]]></category>
		<category><![CDATA[struts2-series]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1966</guid>
		<description><![CDATA[Welcome to Part-5 of 7-Part series where we are discussing different aspects of Struts2 Framework. In the previous article we saw how to integrate Tiles framework with Struts2. 
Today we will explorer the world of Interceptors in Struts2. We will see what Interceptors are and how to configure them in a Struts2 based web application.
Struts [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to Part-5 of 7-Part series where we are discussing different aspects of Struts2 Framework. In the <a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">previous article</a> we saw how to integrate Tiles framework with Struts2. </p>
<p>Today we will explorer the world of Interceptors in Struts2. We will see what Interceptors are and how to configure them in a Struts2 based web application.</p>
<style type="text/css">#struts { color:#222222; width: 98%; background-color: #EEFF99; padding:5px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }#struts h3 { font-size: 18px; text-decoration:underline; }#struts ul { list-style:none; }#struts ul li { padding:3px; }</style><div id="struts"><h3>Struts 2 Tutorials</h3><ul>	<li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1: Introduction to Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Part 2: Create Hello World Application in Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">Part 6: Struts 2 File Upload and Save Example</a></li>	<li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html">Part 7: Struts 2 Ajax Tutorial with Example</a></li></ul></div>
<h2>Struts 2 Interceptors: Basics</h2>
<p>Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.<br />
<img alt="struts2 request processing lifecycle" src="http://img.viralpatel.net/2009/12/struts-2-request-cycle.png" title="struts2 request processing lifecycle" class="aligncenter" width="481" height="184" /><br />
The request processing lifecycle of Struts2 framework is pretty much discussed <a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1 &#8211; Introduction to Struts2 Framework</a>.</p>
<ol>
<li>Request is generated by user and sent to Servlet container.</li>
<li>Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.</li>
<li>One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.</li>
<li>Action is executed and the Result is generated by Action.</li>
<li>The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.</li>
</ol>
<p>Thus the Struts2 Interceptors removes cross cutting tasks such as logging from action components and create cleaner separation of MVC.</p>
<p>Struts2 comes with default list of Interceptors already configured in the application in <code>struts-default.xml</code> file. We can create our own custom Interceptors and plugin into a Struts2 based web application. </p>
<p>Framework creates an object of <strong>ActionInvocation</strong> that encapsulates the action and all the interceptors configured for that action. Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work. Interceptors can alter the workflow of action. It may prevent the execution of action.</p>
<h2>Our Goal</h2>
<p>Our goal will be to create a customer interceptor <strong>MyLoggingInterceptor</strong>, which will log the request before any action is called. Also it will prints the Action class name and execution time of action in milliseconds. </p>
<h2>Create Logging Interceptor</h2>
<p>Create a java class <code>MyLoggingInterceptor</code> in package <code>net.viralpatel.struts2.interceptors</code> and copy following content into it.<br />
 <img src="http://img.viralpatel.net/2009/12/struts2-logging-interceptors.png" alt="struts2-logging-interceptors" title="struts2-logging-interceptors" width="260" height="105" class="aligncenter size-full wp-image-1967" /></p>
<pre class="brush: java;">
package net.viralpatel.struts2.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyLoggingInterceptor implements Interceptor{

	private static final long serialVersionUID = 1L;

	public String intercept(ActionInvocation invocation) throws Exception {

		String className = invocation.getAction().getClass().getName();
		long startTime = System.currentTimeMillis();
		System.out.println(&quot;Before calling action: &quot; + className);

		String result = invocation.invoke();

		long endTime = System.currentTimeMillis();
		System.out.println(&quot;After calling action: &quot; + className
				+ &quot; Time taken: &quot; + (endTime - startTime) + &quot; ms&quot;);

		return result;
	}

	public void destroy() {
		System.out.println(&quot;Destroying MyLoggingInterceptor...&quot;);
	}
	public void init() {
		System.out.println(&quot;Initializing MyLoggingInterceptor...&quot;);
	}
}
</pre>
<h2>Configuring Interceptor in struts.xml</h2>
<p>Once we have created an interceptor class, all we need to do is to configure it in <code>struts.xml</code> file and use it with actions.</p>
<p>To configure newly created interceptor, add following code in struts.xml</p>
<pre class="brush: xml;">
		&lt;interceptors&gt;
			&lt;interceptor name=&quot;mylogging&quot;
				class=&quot;net.viralpatel.struts2.interceptor.MyLoggingInterceptor&quot;&gt;
			&lt;/interceptor&gt;
			&lt;interceptor-stack name=&quot;loggingStack&quot;&gt;
				&lt;interceptor-ref name=&quot;mylogging&quot; /&gt;
				&lt;interceptor-ref name=&quot;defaultStack&quot; /&gt;
			&lt;/interceptor-stack&gt;
		&lt;/interceptors&gt;
</pre>
<p>This code has to be added after &lt;result-types &gt; tag in &lt;package &gt;&lt;/package&gt;<br />
Here we have configured a new interceptor mylogging with tag &lt;interceptor &gt;. Also note that we have defined an <strong>interceptor-stack</strong> with name loggingStack. This is to make sure Sturts2 calls all the default interceptors as well while calling our custom interceptor. This is very important as the validation logic will not work in our struts2 application if we ignore the default stack of interceptors.</p>
<p>We can make the new loggingStack as default interceptor stack or can configure it at each action level. In order to make it default stack, we should add following in struts.xml</p>
<pre class="brush: xml;">
&lt;default-interceptor-ref name=&quot;loggingStack&quot;&gt;&lt;/default-interceptor-ref&gt;
</pre>
<p>Once we add above code in Struts.xml, the logginStack will be applied to all the actions in that package.</p>
<p>Also we may want to apply the custom interceptor stack to only certain actions. To do so, we must add interceptor-ref tag in action.</p>
<pre class="brush: xml;">
&lt;action name=&quot;login&quot;
	class=&quot;net.viralpatel.struts2.LoginAction&quot;&gt;
	&lt;interceptor-ref name=&quot;loggingStack&quot;&gt;&lt;/interceptor-ref&gt;
	&lt;result name=&quot;success&quot; type=&quot;tiles&quot;&gt;/welcome.tiles&lt;/result&gt;
	&lt;result name=&quot;error&quot;&gt;Login.jsp&lt;/result&gt;
&lt;/action&gt;
</pre>
<h2>That&#8217;s All Folks</h2>
<p>If we execute our StrutsHelloWorld application in Eclipse and see the console logs, we will find the log statements that we print in our interceptor.</p>
<pre class="brush: xml;">
Initializing MyLoggingInterceptor...
..
..
..
Before calling action: net.viralpatel.struts2.LoginAction
..
..
After calling action: net.viralpatel.struts2.LoginAction Time taken: 313 ms
..
..
..
Destroying MyLoggingInterceptor...
</pre>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-5-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (17KB)</strong></a></p>
<h2>Moving On</h2>
<p>Today we saw what are Struts Interceptors and how to create a custom interceptor and configure it with a Struts2 based web application. In the <a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">next part</a> we will see Struts2 File Upload Example.</p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate ">Writing a URL Shortner in Java Struts2 &#038; Hibernate </a></li><li><a href="http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html" title="Tutorial: Create Struts2 Hibernate Example in Eclipse">Tutorial: Create Struts2 Hibernate Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" title="Introduction to Struts 2 Framework">Introduction to Struts 2 Framework</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html&amp;title=Struts2 Interceptors Tutorial with Example&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html&amp;title=Struts2 Interceptors Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html&amp;title=Struts2 Interceptors Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html&amp;title=Struts2 Interceptors Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Struts 2 Tiles Plugin Tutorial with Example in Eclipse</title>
		<link>http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html</link>
		<comments>http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html#comments</comments>
		<pubDate>Mon, 28 Dec 2009 13:58:51 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Struts]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[struts2-series]]></category>
		<category><![CDATA[tiles]]></category>
		<category><![CDATA[tiles-plugin]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1958</guid>
		<description><![CDATA[Welcome to Part-4 of the 7-part series where we will go through different aspects for Struts2 Framework with some useful examples. In previous part we went through Struts2 Validation Framework. We saw how easy it is to integrate validation in your struts2 application. 
In this part we will discuss about Tiles Framework and its Integration [...]]]></description>
			<content:encoded><![CDATA[<p>Welcome to Part-4 of the 7-part series where we will go through different aspects for Struts2 Framework with some useful examples. In previous part we went through <a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example"><strong>Struts2 Validation Framework</strong></a>. We saw how easy it is to integrate validation in your struts2 application. </p>
<p>In this part we will discuss about Tiles Framework and its Integration with Struts2. We will add Tiles support to our HelloWorld Struts application that we created in previous parts. I strongly recommend you to go through previous articles and download the source code of our sample application.</p>
<style type="text/css">#struts { color:#222222; width: 98%; background-color: #EEFF99; padding:5px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }#struts h3 { font-size: 18px; text-decoration:underline; }#struts ul { list-style:none; }#struts ul li { padding:3px; }</style><div id="struts"><h3>Struts 2 Tutorials</h3><ul>	<li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1: Introduction to Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Part 2: Create Hello World Application in Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">Part 6: Struts 2 File Upload and Save Example</a></li>	<li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html">Part 7: Struts 2 Ajax Tutorial with Example</a></li></ul></div>
<h2>Introduction to Tiles 2</h2>
<p>Nowadays, website are generally divided into pieces of reusable template that are being rendered among different web pages. For example a site containing header, footer, menu etc. This items remains same through out the website and give it a common look and feel. It is very difficult to hard code this in each and every webpage and if later a change is needed than all the pages needs to be modified. Hence we use templatization mechanism. We create a common Header, Footer, Menu page and include this in each page.</p>
<p>Tiles Plugin allow both templating and componentization. In fact, both mechanisms are similar: you<br />
define parts of page (a &#8220;Tile&#8221;) that you assemble to build another part or a full page. A part can<br />
take parameters, allowing dynamic content, and can be seen as a method in JAVA language. Tiles is a templating system used to maintain a consistent look and feel across all the web pages of a web application. It increase the reusability of template and reduce code duplication.</p>
<p>A common layout of website is defined in a central configuration file and this layout can be extended across all the webpages of the web application.</p>
<h2>Our Application Layout</h2>
<p>Our goal is to add Header, Footer and Menu to our StrutsHelloWorld application. Following will be the layout of the same.<br />
<img src="http://img.viralpatel.net/2009/12/struts2-tiles-layout.gif" alt="struts2-tiles-layout" title="struts2-tiles-layout" width="359" height="321" class="aligncenter size-full wp-image-1959" /></p>
<h2>Required JAR files</h2>
<p>In order to add Tiles support to our Struts2 application, we will need few jar files. Following is the list of JARs in our example. Add these JARs in WEB-INF/lib folder.<br />
<img src="http://img.viralpatel.net/2009/12/struts2-tiles-jar-files.png" alt="struts2-tiles-jar-files" title="struts2-tiles-jar-files" width="205" height="240" class="aligncenter size-full wp-image-1960" /></p>
<h2>Configuring Tiles in web.xml</h2>
<p>To configure Tiles, an entry for listener has to be made in web.xml. Open the web.xml from WEB-INF folder and add following code into it.</p>
<pre class="brush: xml;">
	&lt;listener&gt;
		&lt;listener-class&gt;
			org.apache.struts2.tiles.StrutsTilesListener
		&lt;/listener-class&gt;
	&lt;/listener&gt;
	&lt;context-param&gt;
		&lt;param-name&gt;tilesDefinitions&lt;/param-name&gt;
		&lt;param-value&gt;/WEB-INF/tiles.xml&lt;/param-value&gt;
	&lt;/context-param&gt;
</pre>
<p>The above code configure Tiles listener in web.xml. An input configuration file <code>/WEB-INF/tiles.xml</code> is passed as argument. This file contains the Tiles definition for our web application.</p>
<p>Create a file <strong>tiles.xml</strong> in WEB-INF folder and copy following code into it.<br />
<img src="http://img.viralpatel.net/2009/12/struts2-tiles-xml.png" alt="struts2-tiles-xml" title="struts2-tiles-xml" width="129" height="104" class="aligncenter size-full wp-image-1961" /></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;

&lt;!DOCTYPE tiles-definitions PUBLIC
       &quot;-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN&quot;
       &quot;http://tiles.apache.org/dtds/tiles-config_2_0.dtd&quot;&gt;
&lt;tiles-definitions&gt;
	&lt;definition name=&quot;baseLayout&quot; template=&quot;/BaseLayout.jsp&quot;&gt;
		&lt;put-attribute name=&quot;title&quot; value=&quot;&quot; /&gt;
		&lt;put-attribute name=&quot;header&quot; value=&quot;/Header.jsp&quot; /&gt;
		&lt;put-attribute name=&quot;menu&quot; value=&quot;/Menu.jsp&quot; /&gt;
		&lt;put-attribute name=&quot;body&quot; value=&quot;&quot; /&gt;
		&lt;put-attribute name=&quot;footer&quot; value=&quot;/Footer.jsp&quot; /&gt;
	&lt;/definition&gt;
	&lt;definition name=&quot;/welcome.tiles&quot; extends=&quot;baseLayout&quot;&gt;
		&lt;put-attribute name=&quot;title&quot; value=&quot;Welcome&quot; /&gt;
		&lt;put-attribute name=&quot;body&quot; value=&quot;/Welcome.jsp&quot; /&gt;
	&lt;/definition&gt;
	&lt;definition name=&quot;/customer.tiles&quot; extends=&quot;baseLayout&quot;&gt;
		&lt;put-attribute name=&quot;title&quot; value=&quot;Customer Form&quot; /&gt;
		&lt;put-attribute name=&quot;body&quot; value=&quot;/Customer.jsp&quot; /&gt;
	&lt;/definition&gt;
	&lt;definition name=&quot;/customer.success.tiles&quot; extends=&quot;baseLayout&quot;&gt;
		&lt;put-attribute name=&quot;title&quot; value=&quot;Customer Added&quot; /&gt;
		&lt;put-attribute name=&quot;body&quot; value=&quot;/SuccessCustomer.jsp&quot; /&gt;
	&lt;/definition&gt;
&lt;/tiles-definitions&gt;
</pre>
<p>Here in tiles.xml we have define a template <strong>baseLayout</strong>. This layout contains attributes such as Header, Title, Body, Menu and Footer. The layout is then extended and new definitions for Welcome page and Customer page is defined. We have override the default layout and changed the content for Body and Title. </p>
<h2>Creating JSPs</h2>
<p><img src="http://img.viralpatel.net/2009/12/struts-2-tiles-layout-jsp.png" alt="struts-2-tiles-layout-jsp" title="struts-2-tiles-layout-jsp" width="168" height="193" class="aligncenter size-full wp-image-1962" />We will define the template for our webapplication in a JSP file called BaseLayout.jsp. This template will contain different segments of web page (Header, Footer, Menu etc). Create 4 new JSP files BaseLayout.jsp, Header.jsp, Menu.jsp and Footer.jsp and copy following content in each of them.<br />
<strong>BaseLayout.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ taglib uri=&quot;http://tiles.apache.org/tags-tiles&quot; prefix=&quot;tiles&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
&quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
&lt;title&gt;&lt;tiles:insertAttribute name=&quot;title&quot; ignore=&quot;true&quot; /&gt;&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;table border=&quot;1&quot; cellpadding=&quot;2&quot; cellspacing=&quot;2&quot; align=&quot;center&quot;&gt;
	&lt;tr&gt;
		&lt;td height=&quot;30&quot; colspan=&quot;2&quot;&gt;&lt;tiles:insertAttribute name=&quot;header&quot; /&gt;
		&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td height=&quot;250&quot;&gt;&lt;tiles:insertAttribute name=&quot;menu&quot; /&gt;&lt;/td&gt;
		&lt;td width=&quot;350&quot;&gt;&lt;tiles:insertAttribute name=&quot;body&quot; /&gt;&lt;/td&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
		&lt;td height=&quot;30&quot; colspan=&quot;2&quot;&gt;&lt;tiles:insertAttribute name=&quot;footer&quot; /&gt;
		&lt;/td&gt;
	&lt;/tr&gt;
&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>Header.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;h2&gt;Struts2 Example - ViralPatel.net&lt;/h2&gt;
</pre>
<p><strong>Menu.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;s:a href=&quot;customer-form&quot;&gt;Customer&lt;/s:a&gt;
</pre>
<p><strong>Footer.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
Copyright &amp;copy; ViralPatel.net
</pre>
<h2>Modifications in Struts.xml</h2>
<p>In struts.xml we defined result tag which maps a particular action with a JSP page. Now we will modify it and map the result with Tiles. Following will be the content of struts.xml file.</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE struts PUBLIC
    &quot;-//Apache Software Foundation//DTD Struts Configuration 2.0//EN&quot;
    &quot;http://struts.apache.org/dtds/struts-2.0.dtd&quot;&gt;

&lt;struts&gt;
	&lt;constant name=&quot;struts.enable.DynamicMethodInvocation&quot;
		value=&quot;false&quot; /&gt;
	&lt;constant name=&quot;struts.devMode&quot; value=&quot;false&quot; /&gt;
	&lt;constant name=&quot;struts.custom.i18n.resources&quot;
		value=&quot;ApplicationResources&quot; /&gt;

	&lt;package name=&quot;default&quot; extends=&quot;struts-default&quot; namespace=&quot;/&quot;&gt;
		&lt;result-types&gt;
			&lt;result-type name=&quot;tiles&quot;
				class=&quot;org.apache.struts2.views.tiles.TilesResult&quot; /&gt;
		&lt;/result-types&gt;
		&lt;action name=&quot;login&quot;
			class=&quot;net.viralpatel.struts2.LoginAction&quot;&gt;
			&lt;result name=&quot;success&quot; type=&quot;tiles&quot;&gt;/welcome.tiles&lt;/result&gt;
			&lt;result name=&quot;error&quot;&gt;Login.jsp&lt;/result&gt;
		&lt;/action&gt;
		&lt;action name=&quot;customer&quot;
			class=&quot;net.viralpatel.struts2.CustomerAction&quot;&gt;
			&lt;result name=&quot;success&quot; type=&quot;tiles&quot;&gt;/customer.success.tiles&lt;/result&gt;
			&lt;result name=&quot;input&quot; type=&quot;tiles&quot;&gt;/customer.tiles&lt;/result&gt;
		&lt;/action&gt;
		&lt;action name=&quot;customer-form&quot;&gt;
			&lt;result name=&quot;success&quot; type=&quot;tiles&quot;&gt;/customer.tiles&lt;/result&gt;
		&lt;/action&gt;
	&lt;/package&gt;
&lt;/struts&gt;
</pre>
<p>The struts.xml now defines a new Result type for Tiles. This result type is used in <code>&lt;result&gt;</code> tag for different actions. Also note that we have define a new action customer-form. This is just an empty declaration to redirect user to Customer form page when she clicks Customer link from menu.</p>
<h2>That&#8217;s All Folks</h2>
<p>Compile and Execute the application in Eclipse and see that the header, menu and footer are properly applied.<br />
<strong>Welcome Page with Tiles</strong><br />
<img src="http://img.viralpatel.net/2009/12/struts-2-welcome-page-tiles.png" alt="struts-2-welcome-page-tiles" title="struts-2-welcome-page-tiles" width="506" height="477" class="aligncenter size-full wp-image-1963" /><br />
<strong>Customer Page with Tiles</strong><br />
<img src="http://img.viralpatel.net/2009/12/struts2-tiles-customer-page.png" alt="struts2-tiles-customer-page" title="struts2-tiles-customer-page" width="506" height="477" class="aligncenter size-full wp-image-1964" /><br />
<strong>Customer Success Page with Tiles</strong><br />
<img src="http://img.viralpatel.net/2009/12/struts2-customer-added-tiles.png" alt="struts2-customer-added-tiles" title="struts2-customer-added-tiles" width="506" height="477" class="aligncenter size-full wp-image-1965" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-4-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (11KB)</strong></a></p>
<h2>Moving On</h2>
<p>Today we saw how we can configure Tiles framework with Struts2 application. In <a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">next part</a> we will discuss about Struts2 Interceptors and see example of it. I hope you liked this article. Feel free to post your queries and comments in comment section.</p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2008/12/tutorial-struts-tiles-plugin-example-in-eclipse.html" title="Tutorial: Struts Tiles plugin example in Eclipse">Tutorial: Struts Tiles plugin example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate ">Writing a URL Shortner in Java Struts2 &#038; Hibernate </a></li><li><a href="http://viralpatel.net/blogs/2010/01/tutorial-struts2-hibernate-example-eclipse.html" title="Tutorial: Create Struts2 Hibernate Example in Eclipse">Tutorial: Create Struts2 Hibernate Example in Eclipse</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html&amp;title=Struts 2 Tiles Plugin Tutorial with Example in Eclipse&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html&amp;title=Struts 2 Tiles Plugin Tutorial with Example in Eclipse" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html&amp;title=Struts 2 Tiles Plugin Tutorial with Example in Eclipse" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html&amp;title=Struts 2 Tiles Plugin Tutorial with Example in Eclipse" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Struts2 Validation Framework Tutorial with Example</title>
		<link>http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html</link>
		<comments>http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html#comments</comments>
		<pubDate>Thu, 24 Dec 2009 11:05:38 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[How-To]]></category>
		<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Struts]]></category>
		<category><![CDATA[struts validator]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[struts2-series]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1949</guid>
		<description><![CDATA[
Welcome to Part-3 of 7-part series of tutorials where we will go through different practical aspects of Struts2 Framework. In the last part we Created a Basic Struts2 Application from Scratch. I strongly recommend you to go through the previous articles in case you are new to Struts2.
In this article we will learn how to [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/12/struts2-validation-framework.png" alt="struts2-validation-framework" title="struts2-validation-framework" width="585" height="143" class="aligncenter size-full wp-image-1950" /><br />
Welcome to Part-3 of 7-part series of tutorials where we will go through different practical aspects of Struts2 Framework. In the last part we Created a <a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html">Basic Struts2 Application from Scratch</a>. I strongly recommend you to go through the previous articles in case you are new to Struts2.</p>
<p>In this article we will learn how to leverage Struts2 Validation Framework in an application. For this we will use StrutsHelloWorld application which we created in <a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html">previous article</a> as base and starts adding validation logic to it.</p>
<style type="text/css">#struts { color:#222222; width: 98%; background-color: #EEFF99; padding:5px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }#struts h3 { font-size: 18px; text-decoration:underline; }#struts ul { list-style:none; }#struts ul li { padding:3px; }</style><div id="struts"><h3>Struts 2 Tutorials</h3><ul>	<li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1: Introduction to Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Part 2: Create Hello World Application in Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">Part 6: Struts 2 File Upload and Save Example</a></li>	<li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html">Part 7: Struts 2 Ajax Tutorial with Example</a></li></ul></div>
<h2>Introduction to Struts2 Validation Framework</h2>
<p>Struts Action 2 relies on a validation framework provided by XWork to enable the application of input validation rules to your Actions before they are executed. Struts2 Validation Framework allows us to separate the validation logic from actual Java/JSP code, where it can be reviewed and easily modified later. </p>
<p>The Struts2 Validation Framework alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.</p>
<p>Validation framework comes with set of useful routines to handle form validation automatically and it can handle both <strong>server side</strong> as well as <strong>client side</strong> form validation. If certain validation is not present, you can create your own validation logic by implementing java interface <code>com.opensymphony.xwork2.Validator</code> and plug it into validation framework as a re-usable component.</p>
<p>Validator uses XML configuration files to determine which validation routines should be installed and how they should be applied for a given application. validators.xml file contains all common validators declaration. If validators.xml file is not present in classpath, a default validation file is loaded from path <code>com/opensymphony/xwork2/validator/validators/default.xml</code>.</p>
<p>The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.</p>
<h2>Validators Scope</h2>
<p>There are two types of Validators in Struts2 Validation Framework.</p>
<ol>
<li>Field Validators</li>
<li>Non-field validators</li>
</ol>
<p><strong>Field validators</strong>, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.</p>
<pre class="brush: xml;">
&lt;validators&gt;
  &lt;field name=&quot;bar&quot;&gt;
      &lt;field-validator type=&quot;required&quot;&gt;
          &lt;message&gt;You must enter a value for bar.&lt;/message&gt;
      &lt;/field-validator&gt;
  &lt;/field&gt;
&lt;/validators&gt;
</pre>
<p><strong>Non-field validators</strong> only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.</p>
<pre class="brush: xml;">
&lt;validators&gt;
      &lt;validator type=&quot;expression&quot;&gt;
            &lt;param name=&quot;expression&quot;&gt;foo lt bar&lt;/param&gt;
            &lt;message&gt;Foo must be greater than Bar.&lt;/message&gt;
      &lt;/validator&gt;
&lt;/validators&gt;
</pre>
<h2>Getting Started</h2>
<p>Let us add validation logic to StrutsHelloWorld application that we created in previous article. For this tutorial, we will create an Action class called <strong>CustomerAction</strong> which will contain few fields. Create a file CustomerAction.java in package net.viralpatel.struts2.<br />
<img src="http://img.viralpatel.net/2009/12/customer-action-struts2.png" alt="customer-action-struts2" title="customer-action-struts2" width="226" height="106" class="aligncenter size-full wp-image-1952" /><br />
Copy following content into it.<br />
<strong>CustomerAction.java</strong></p>
<pre class="brush: java;">
package net.viralpatel.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport{
	private String name;
	private Integer age;
	private String email;
	private String telephone;

	public String addCustomer() {
		return SUCCESS;
	}

	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 String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getTelephone() {
		return telephone;
	}
	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}
}
</pre>
<p>Note that CustomerAction class has fields name, email, telephone and age. Also it has a method called <code>addCustomer()</code> which doesn&#8217;t have any logic, it just return SUCCESS.</p>
<p>Now we will add entry for this new action class in <strong>struts.xml</strong> file. Open the struts.xml file which will be present under resources folder. And add following content between &lt;package&gt;&lt;/package&gt; tag.</p>
<pre class="brush: xml;">
		&lt;action name=&quot;customer&quot;
			class=&quot;net.viralpatel.struts2.CustomerAction&quot;&gt;
			&lt;result name=&quot;success&quot;&gt;SuccessCustomer.jsp&lt;/result&gt;
			&lt;result name=&quot;input&quot;&gt;Customer.jsp&lt;/result&gt;
		&lt;/action&gt;
</pre>
<p>Note that we are mapping the CustomerAction class with name customer. Also on success user will be redirected to SuccessCustomer.jsp page. Notice that there is another result tag with name input. Whenever the validation logic encounter some validation error, it redirects the user back to page specified as input. Thus in our example, user will be redirected back to Customer.jsp in case of any errors.</p>
<p>Create two new JSPs <code>Customer.jsp</code> (which will contain Customer form) and <code>SuccessCustomer.jsp</code> (which will be displayed on success).<br />
<img src="http://img.viralpatel.net/2009/12/struts2-validation-jsp-files.png" alt="struts2-validation-jsp-files" title="struts2-validation-jsp-files" width="170" height="121" class="aligncenter size-full wp-image-1953" /><br />
<strong>Customer.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Customer Form - Struts2 Demo | ViralPatel.net&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;h2&gt;Customer Form&lt;/h2&gt;

&lt;s:form action=&quot;customer.action&quot; method=&quot;post&quot;&gt;
	&lt;s:textfield name=&quot;name&quot; key=&quot;name&quot; size=&quot;20&quot; /&gt;
	&lt;s:textfield name=&quot;age&quot; key=&quot;age&quot; size=&quot;20&quot; /&gt;
	&lt;s:textfield name=&quot;email&quot; key=&quot;email&quot; size=&quot;20&quot; /&gt;
	&lt;s:textfield name=&quot;telephone&quot; key=&quot;telephone&quot; size=&quot;20&quot; /&gt;
	&lt;s:submit method=&quot;addCustomer&quot; key=&quot;label.add.customer&quot; align=&quot;center&quot; /&gt;
&lt;/s:form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p><strong>SuccessCustomer.jsp</strong></p>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Customer Page - Struts2 Demo | ViralPatel.net&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
	&lt;h2&gt;Customer Added Successfully.&lt;/h2&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>We have created Customer.jsp file which will display Customer form. But we don&#8217;t have link to this page from our web application. So we will create a link to Customer.jsp from Welcome.jsp page. Open Welcome.jsp page and add following link code into it.</p>
<pre class="brush: xml;">
	&lt;s:a href=&quot;Customer.jsp&quot;&gt;Add Customer&lt;/s:a&gt;
</pre>
<p>Now open the ApplicationResources.properties file from /resources folder and add following key/values in it.</p>
<pre class="brush: xml;">
name= Name
age= Age
email= Email
telephone= Telephone
label.add.customer=Add Customer

errors.invalid=${getText(fieldName)} is invalid.
errors.required=${getText(fieldName)} is required.
errors.number=${getText(fieldName)} must be a number.
errors.range=${getText(fieldName)} is not in the range ${min} and ${max}.
</pre>
<p>Execute the code in Eclipse and see the output. You will see login page. Enter username=admin and password=admin123 and do login. On welcome page you will see a link to Add Customer page. Click on that link and you will see Customer page.<br />
<img src="http://img.viralpatel.net/2009/12/struts2-customer-form.png" alt="struts2-customer-form" title="struts2-customer-form" width="412" height="306" class="aligncenter size-full wp-image-1954" /></p>
<h2>Adding Validation Logic</h2>
<p>Now we are ready with the basic customer form on which we will add the validation logic. Following will be the validations rules:</p>
<ol>
<li>Name field is mandatory</li>
<li>Age field is mandatory. It should be a number between 1 and 100.</li>
<li>Email field is mandatory. It should be a valid email address.</li>
<li>Telephone is mandatory.</li>
</ol>
<p>In order to define validation logic for particular form, we first have to create an XML file which will hold this data. Struts2 define a specific naming convention in defining validation xml files. The format is <strong>&lt;ActionClassName&gt;-validation.xml</strong>. So for our application we will create a file <strong>CustomerAction-validation.xml</strong>. Note that this file should be present in the same package as of action class.<br />
Create file CustomerAction-validation.xml in package net.viralpatel.struts2. And copy following content into it.<br />
<img src="http://img.viralpatel.net/2009/12/struts2-validation-xml.png" alt="struts2-validation-xml" title="struts2-validation-xml" width="273" height="130" class="aligncenter size-full wp-image-1955" /><br />
<strong>CustomerAction-validation.xml</strong></p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE validators PUBLIC
  		&quot;-//OpenSymphony Group//XWork Validator 1.0.2//EN&quot;
  		&quot;http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd&quot;&gt;
&lt;validators&gt;
	&lt;field name=&quot;name&quot;&gt;
		&lt;field-validator type=&quot;requiredstring&quot;&gt;
			&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
			&lt;message key=&quot;errors.required&quot; /&gt;
		&lt;/field-validator&gt;
	&lt;/field&gt;
	&lt;field name=&quot;age&quot;&gt;
		&lt;field-validator type=&quot;required&quot;&gt;
			&lt;message key=&quot;errors.required&quot; /&gt;
		&lt;/field-validator&gt;
		&lt;field-validator type=&quot;int&quot;&gt;
			&lt;param name=&quot;min&quot;&gt;1&lt;/param&gt;
			&lt;param name=&quot;max&quot;&gt;100&lt;/param&gt;
			&lt;message key=&quot;errors.range&quot;/&gt;
		&lt;/field-validator&gt;
	&lt;/field&gt;
	&lt;field name=&quot;email&quot;&gt;
		&lt;field-validator type=&quot;requiredstring&quot;&gt;
			&lt;message key=&quot;errors.required&quot; /&gt;
		&lt;/field-validator&gt;
		&lt;field-validator type=&quot;email&quot;&gt;
			&lt;message key=&quot;errors.invalid&quot; /&gt;
		&lt;/field-validator&gt;
	&lt;/field&gt;
	&lt;field name=&quot;telephone&quot;&gt;
		&lt;field-validator type=&quot;requiredstring&quot;&gt;
			&lt;message key=&quot;errors.required&quot; /&gt;
		&lt;/field-validator&gt;
	&lt;/field&gt;
&lt;/validators&gt;
</pre>
<p>And that&#8217;s it. We just added validation logic to our example. Note that the validations xml file contains different field-validators. </p>
<h2>Client Side Validation</h2>
<p>It is very easy to add Client Side validation or JavaScript validation to any form in Struts2. All you have to do is to add <strong>validate=&#8221;true&#8221;</strong> in form tag in your JSP file. For example open Customer.jsp and add validate=&#8221;true&#8221; in form tag. Struts2 automatically generates the JavaScript code for client side validation of form.</p>
<pre class="brush: xml;">
&lt;s:form action=&quot;customer.action&quot; method=&quot;post&quot; validate=&quot;true&quot;&gt;
	...
&lt;/s:form&gt;
</pre>
<h2>That&#8217;s All Folks</h2>
<p>Execute the application and test the Customer form with different values.<br />
<strong>Customer page</strong><br />
<img src="http://img.viralpatel.net/2009/12/struts2-customer-form.png" alt="struts2-customer-form" title="struts2-customer-form" width="412" height="306" class="aligncenter size-full wp-image-1954" /><br />
<strong>Customer page with errors</strong><br />
<img src="http://img.viralpatel.net/2009/12/customer-page-validation-errors.png" alt="customer-page-validation-errors" title="customer-page-validation-errors" width="412" height="382" class="aligncenter size-full wp-image-1956" /><br />
<strong>Customer page on success</strong><br />
<img src="http://img.viralpatel.net/2009/12/customer-page-success.png" alt="customer-page-success" title="customer-page-success" width="426" height="204" class="aligncenter size-full wp-image-1957" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-3-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (9KB)</strong></a></p>
<h2>Moving On</h2>
<p>Now that we have implemented Struts2 Validation framework in our example, we know how exactly struts2 validation is handled. Also we know different types of validators like field-validators and non-field. In <a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html"><strong>next part</strong></a> we will study Tiles framework and implement it in our application.</p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" title="Introduction to Struts 2 Framework">Introduction to Struts 2 Framework</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html" title="Creating &#038; Parsing JSON data with Java Servlet/Struts/JSP">Creating &#038; Parsing JSON data with Java Servlet/Struts/JSP</a></li><li><a href="http://viralpatel.net/blogs/2009/01/struts-validation-framework-tutorial-example-validator-struts-validation-form-validation.html" title="Struts Validation Framework tutorial with example.">Struts Validation Framework tutorial with example.</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html&amp;title=Struts2 Validation Framework Tutorial with Example&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html&amp;title=Struts2 Validation Framework Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html&amp;title=Struts2 Validation Framework Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html&amp;title=Struts2 Validation Framework Tutorial with Example" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Tutorial: Create Struts 2 Application in Eclipse</title>
		<link>http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html</link>
		<comments>http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html#comments</comments>
		<pubDate>Wed, 23 Dec 2009 08:00:28 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[struts2-series]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1932</guid>
		<description><![CDATA[
Welcome to the Part 2 of 7-part series where we will explore the world of Struts 2 Framework. In previous  article we went through the basics of Struts2, its Architecture diagram, the request processing lifecycle and a brief comparison of Struts1 and Struts2. If you have not gone through the previous article, I highly [...]]]></description>
			<content:encoded><![CDATA[<p><img class="aligncenter size-full wp-image-1933" title="struts2-hello-world" src="http://img.viralpatel.net/2009/12/struts2-hello-world.png" alt="struts2-hello-world" width="589" height="158" /><br />
Welcome to the Part 2 of 7-part series where we will explore the world of Struts 2 Framework. In <a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" target="_blank">previous  article</a> we went through the basics of Struts2, its Architecture diagram, the request processing lifecycle and a brief comparison of Struts1 and Struts2. If you have not gone through the previous article, I highly recommend you to do that before starting hands-on today.</p>
<style type="text/css">#struts { color:#222222; width: 98%; background-color: #EEFF99; padding:5px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }#struts h3 { font-size: 18px; text-decoration:underline; }#struts ul { list-style:none; }#struts ul li { padding:3px; }</style><div id="struts"><h3>Struts 2 Tutorials</h3><ul>	<li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1: Introduction to Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Part 2: Create Hello World Application in Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">Part 6: Struts 2 File Upload and Save Example</a></li>	<li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html">Part 7: Struts 2 Ajax Tutorial with Example</a></li></ul></div>
<h2>Things We Need</h2>
<p>Before we starts with our first Hello World Struts 2 Example, we will need few tools.</p>
<ol>
<li>JDK 1.5 above (<a rel="nofollow" href="http://java.sun.com/javase/downloads/index.jsp" target="_new">download</a>)</li>
<li>Tomcat 5.x above or any other container (Glassfish, JBoss, Websphere, Weblogic etc) (<a rel="nofollow" href="http://tomcat.apache.org/download-55.cgi" target="_new">download</a>)</li>
<li>Eclipse 3.2.x above (<a rel="nofollow" href="http://www.eclipse.org/downloads/" target="_new">download</a>)</li>
<li>Apache Struts2 JAR files:(<a rel="nofollow" href="http://mirror.switch.ch/mirror/apache/dist/struts/library/struts-2.0.14-lib.zip">download</a>). Following are the list of JAR files required for this application.
<ul>
<li>commons-logging-1.0.4.jar</li>
<li>freemarker-2.3.8.jar</li>
<li>ognl-2.6.11.jar</li>
<li>struts2-core-2.0.12.jar</li>
<li>xwork-2.0.6.jar</li>
</ul>
<p>Note that depending on the current version of Struts2, the version number of above jar files may change.
</li>
</ol>
<h2>Our Goal</h2>
<p>Our goal is to create a basic Struts2 application with a Login page. User will enter login credential and if authenticated successfully she will be redirected to a Welcome page which will display message &#8221;	<i>Howdy, &lt;username&gt;&#8230;!</i>&#8220;. If user is not authenticated, she will be redirected back to the login page.<br />
<img src="http://img.viralpatel.net/2009/02/struts2-application-login-page.png" alt="struts2-application-login-page" title="struts2-application-login-page" width="471" height="255" class="aligncenter size-full wp-image-1939" /></p>
<h2>Getting Started</h2>
<p>Let us start with our first Struts2 based application.<br />
Open Eclipse and goto File -> New -> Project and select <strong>Dynamic Web Project</strong> in the New Project wizard screen.<br />
<img class="alignnone size-full wp-image-294" title="eclipse-new-project-struts-example" src="http://img.viralpatel.net/2008/12/eclipse-new-project-struts-example.png" alt="Dynamic Web Project in Eclipse" width="369" height="365" /></p>
<p>After selecting Dynamic Web Project, press <strong>Next</strong>.<br />
<img class="alignnone size-full wp-image-296" title="eclipse-new-dynamic-web-project-struts" src="http://img.viralpatel.net/2008/12/eclipse-new-dynamic-web-project-struts.png" alt="Eclipse Struts2 Project" width="471" height="511" /></p>
<p>Write the name of the project. For example <strong>StrutsHelloWorld</strong>. Once this is done, select the target runtime environment (e.g. Apache Tomcat v6.0). This is to run the project inside Eclipse environment. After this press <strong>Finish</strong>.</p>
<p>Once the project is created, you can see its structure in Project Explorer.<br />
<img class="alignnone size-full wp-image-297" title="new-struts-application-created" src="http://img.viralpatel.net/2008/12/new-struts-application-created.png" alt="Eclipse Project Explorer: Struts2 Example" width="500" height="458" /></p>
<p>Now copy all the required JAR files in WebContent -> WEB-INF -> lib folder. Create this folder if it does not exists.<br />
<img src="http://img.viralpatel.net/2009/02/struts2-webinf-jars.png" alt="struts2-webinf-jars" title="struts2-webinf-jars" width="208" height="123" class="aligncenter size-full wp-image-1940" /></p>
<h2>Mapping Struts2 in WEB.xml</h2>
<p>As discussed in the previous article (<a target="_blank" href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Introduction to Struts2</a>), the entry point of Struts2 application will be the Filter define in deployment descriptor (web.xml). Hence we will define an entry of <strong>org.apache.struts2.dispatcher.FilterDispatcher</strong> class in web.xml.  </p>
<p>Open web.xml file which is under WEB-INF folder and copy paste following code.</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app id=&quot;WebApp_9&quot; version=&quot;2.4&quot;
	xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;&gt;

	&lt;display-name&gt;Struts2 Application&lt;/display-name&gt;
	&lt;filter&gt;
		&lt;filter-name&gt;struts2&lt;/filter-name&gt;
		&lt;filter-class&gt;
			org.apache.struts2.dispatcher.FilterDispatcher
		&lt;/filter-class&gt;
	&lt;/filter&gt;
	&lt;filter-mapping&gt;
		&lt;filter-name&gt;struts2&lt;/filter-name&gt;
		&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
	&lt;/filter-mapping&gt;
	&lt;welcome-file-list&gt;
		&lt;welcome-file&gt;Login.jsp&lt;/welcome-file&gt;
	&lt;/welcome-file-list&gt;

&lt;/web-app&gt;
</pre>
<p>The above code in web.xml will map Struts2 filter with url /*. The default url mapping for struts2 application will be /*.action. Also note that we have define <code>Login.jsp</code> as welcome file.</p>
<h2>The Action Class</h2>
<p>We will need an Action class that will authenticate our user and holds the value for username and password. For this we will create a package <strong>net.viralpatel.struts2</strong> in the source folder. This package will contain the action file.<br />
<img src="http://img.viralpatel.net/2009/02/struts2-source-package.png" alt="struts2-source-package" title="struts2-source-package" width="204" height="72" class="aligncenter size-full wp-image-1941" /><br />
Create a class called <strong>LoginAction</strong> in net.viralpatel.struts2 package with following content.</p>
<pre class="brush: java;">
package net.viralpatel.struts2;

public class LoginAction {
	private String username;
	private String password;

	public String execute() {

		if (this.username.equals(&quot;admin&quot;)
				&amp;&amp; this.password.equals(&quot;admin123&quot;)) {
			return &quot;success&quot;;
		} else {
			return &quot;error&quot;;
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
</pre>
<p>Note that, above action class contains two fields, username and password which will hold the values from form and also contains an <code>execute()</code> method that will authenticate the user. In this simple example, we are checking if username is <em>admin</em> and password is <em>admin123</em>.</p>
<p>Also note that unlike Action class in Struts1, Struts2 action class is a simple POJO class with required attributes and method.</p>
<p>The <code>execute()</code> method returns a String value which will determine the result page. Also, in Struts2 the name of the method is not fixed. In this example we have define method execute(). You may want to define a method <em>authenticate()</em> instead. </p>
<h2>The ResourceBundle</h2>
<p>ResourceBundle is very useful Java entity that helps in putting the static content away from the source file. Most of the application define a resource bundle file such as ApplicationResources.properties file which contains static messages such as Username or Password and include this with the application.</p>
<p>ResourceBundle comes handy when we want to add Internationalization (I18N) support to an application. </p>
<p>We will define an ApplicationResources.properties file for our application. This property file should be present in WEB-INF/classes folders when the source is compiled. Thus we will create a source folder called <strong>resources</strong> and put the ApplicationResources.properties file in it.</p>
<p>To create a source folder, right click on your project in Project Explorer and select <strong>New -&gt; Source Folder</strong>.<br />
<img src="http://img.viralpatel.net/2009/02/struts2-resource-folder.png" alt="struts2-resource-folder" title="struts2-resource-folder" width="607" height="242" class="aligncenter size-full wp-image-1942" /><br />
Specify folder name <strong>resources</strong> and press <strong>Finish</strong>.</p>
<p>Create a file <strong>ApplicationResources.properties</strong> under resources folder.<br />
<img src="http://img.viralpatel.net/2009/02/struts-2-application-resources-properties.png" alt="struts-2-application-resources-properties" title="struts-2-application-resources-properties" width="257" height="90" class="aligncenter size-full wp-image-1943" /><br />
Copy following content in ApplicationResources.properties. </p>
<pre class="brush: xml;">
label.username= Username
label.password= Password
label.login= Login
</pre>
<h2>The JSP</h2>
<p>We will create two JSP files to render the output to user. <strong>Login.jsp</strong> will be the starting point of our application which will contain a simple login form with username and password. On successful authentication, user will be redirected to <strong>Welcome.jsp</strong> which will display a simple welcome message.</p>
<p>Create two JSP files Login.jsp and Welcome.jsp in WebContent folder of your project. Copy following content into it.</p>
<h3>Login.jsp</h3>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Struts 2 - Login Application | ViralPatel.net&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
&lt;h2&gt;Struts 2 - Login Application&lt;/h2&gt;
&lt;s:actionerror /&gt;
&lt;s:form action=&quot;login.action&quot; method=&quot;post&quot;&gt;
	&lt;s:textfield name=&quot;username&quot; key=&quot;label.username&quot; size=&quot;20&quot; /&gt;
	&lt;s:password name=&quot;password&quot; key=&quot;label.password&quot; size=&quot;20&quot; /&gt;
	&lt;s:submit method=&quot;execute&quot; key=&quot;label.login&quot; align=&quot;center&quot; /&gt;
&lt;/s:form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>Welcome.jsp</h3>
<pre class="brush: xml;">
&lt;%@ page contentType=&quot;text/html; charset=UTF-8&quot;%&gt;
&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Welcome&lt;/title&gt;
&lt;/head&gt;

&lt;body&gt;
	&lt;h2&gt;Howdy, &lt;s:property value=&quot;username&quot; /&gt;...!&lt;/h2&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Note that we have used struts2 &lt;s:&gt; tag to render the textboxes and labels. Struts2 comes with a powerful built-in tag library to render UI elements more efficiently.</p>
<h2>The struts.xml file</h2>
<p>Struts2 reads the configuration and class definition from an xml file called <strong>struts.xml</strong>. This file is loaded from the classpath of the project. We will define struts.xml file in the <strong>resources</strong> folder. Create file struts.xml in resources folder.<br />
<img src="http://img.viralpatel.net/2009/02/struts2-struts-xml.png" alt="struts2-struts-xml" title="struts2-struts-xml" width="257" height="122" class="aligncenter size-full wp-image-1944" /><br />
Copy following content into struts.xml.</p>
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE struts PUBLIC
    &quot;-//Apache Software Foundation//DTD Struts Configuration 2.0//EN&quot;
    &quot;http://struts.apache.org/dtds/struts-2.0.dtd&quot;&gt;

&lt;struts&gt;
	&lt;constant name=&quot;struts.enable.DynamicMethodInvocation&quot;
		value=&quot;false&quot; /&gt;
	&lt;constant name=&quot;struts.devMode&quot; value=&quot;false&quot; /&gt;
	&lt;constant name=&quot;struts.custom.i18n.resources&quot;
		value=&quot;ApplicationResources&quot; /&gt;

	&lt;package name=&quot;default&quot; extends=&quot;struts-default&quot; namespace=&quot;/&quot;&gt;
		&lt;action name=&quot;login&quot;
			class=&quot;net.viralpatel.struts2.LoginAction&quot;&gt;
			&lt;result name=&quot;success&quot;&gt;Welcome.jsp&lt;/result&gt;
			&lt;result name=&quot;error&quot;&gt;Login.jsp&lt;/result&gt;
		&lt;/action&gt;
	&lt;/package&gt;
&lt;/struts&gt;
</pre>
<p>Note that in above configuration file, we have defined Login action of our application. Two result paths are mapped with LoginAction depending on the outcome of <code>execute()</code> method. If execute() method returns success, user will be redirected to Welcome.jsp else to Login.jsp.</p>
<p>Also note that a constant is specified with name <strong>struts.custom.i18n.resources</strong>. This constant specify the resource bundle file that we created in above steps. We just have to specify name of resource bundle file without extension (ApplicationResources without .properties).</p>
<p>Our LoginAction contains the method execute() which is the default method getting called by Sturts2. If the name of method is different, e.g. authenticate(); then we should specify the method name in <code>&lt;action&gt;</code> tag.</p>
<pre class="brush: xml;">
	&lt;action name=&quot;login&quot; method=&quot;authenticate&quot;
		class=&quot;net.viralpatel.struts2.LoginAction&quot;&gt;
</pre>
<h2>Almost Done</h2>
<p>We are almost done with the application. You may want to run the application now and see the result yourself. I assume you have already configured Tomcat in eclipse. All you need to do:<br />
Open Server view from Windows -> Show View -> Server. Right click in this view and select New -> Server and add your server details.<br />
To run the project, right click on Project name from Project Explorer and select Run as -> Run on Server (Shortcut: Alt+Shift+X, R)</p>
<p>But there is one small problem. Our application runs perfectly fine at this point. But when user enters wrong credential, she is redirected to Login page. But no error message is displayed. User does not know what just happened. A good application always show proper error messages to user. So we must display an error message <em>Invalid Username/Password. Please try again</em> when user authentication is failed.</p>
<h2>Final Touch</h2>
<p>To add this functionality first we will add the error message in our ResourceBundle file.<br />
Open ApplicationResources.properties and add an entry for <strong>error.login</strong> in it. The final ApplicationResources.properties will look like:</p>
<pre class="brush: xml;">
label.username= Username
label.password= Password
label.login= Login
error.login= Invalid Username/Password. Please try again.
</pre>
<p>Also we need to add logic in LoginAction to add error message if user is not authenticated. But there is one problem. Our error message is specified in ApplicationResources.properties file. We must specify key error.login in LoginAction and the message should be displayed on JSP page.</p>
<p>For this we must implement <code>com.opensymphony.xwork2.TextProvider</code> interface which provides method <code>getText()</code>. This method returns String value from resource bundle file. We just have to pass the key value as argument to getText() method. The TextProvider interface defines several method that we must implement in order to get hold on getText() method. But we don&#8217;t want to spoil our code by adding all those methods which we do not intend to use. There is a good way of dealing with this problem.</p>
<p>Struts2 comes with a very useful class <code>com.opensymphony.xwork2.ActionSupport</code>. We just have to extend our LoginAction class with this class and directly use methods such as getText(), addActionErrors() etc. Thus we will extend the LoginAction class with ActionSupport class and add the logic for error reporting into it. The final code in LoginAction must look like:</p>
<pre class="brush: java;">
package net.viralpatel.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class LoginAction extends ActionSupport {
	private String username;
	private String password;

	public String execute() {

		if (this.username.equals(&quot;admin&quot;)
				&amp;&amp; this.password.equals(&quot;admin123&quot;)) {
			return &quot;success&quot;;
		} else {
			addActionError(getText(&quot;error.login&quot;));
			return &quot;error&quot;;
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
</pre>
<p>And that&#8217;s it. Our first Hello World Struts2 Application is now ready.</p>
<h2>That&#8217;s All Folks</h2>
<p>Execute the application in Eclipse and run it in your favorite browser.<br />
<strong>Login page</strong><br />
<img src="http://img.viralpatel.net/2009/02/struts2-application-login-page.png" alt="struts2-application-login-page" title="struts2-application-login-page" width="471" height="255" class="aligncenter size-full wp-image-1939" /></p>
<p><strong>Welcome page</strong><br />
<img src="http://img.viralpatel.net/2009/02/struts2-welcome-page.png" alt="struts2-welcome-page" title="struts2-welcome-page" width="471" height="255" class="aligncenter size-full wp-image-1945" /></p>
<p><strong>Login page with error</strong><br />
<img src="http://img.viralpatel.net/2009/02/struts2-login-page-error.png" alt="struts2-login-page-error" title="struts2-login-page-error" width="471" height="275" class="aligncenter size-full wp-image-1946" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (9KB).</strong></a></p>
<h2>Moving On</h2>
<p>Now that we have created our first webapp using Struts2 framework, we know how the request flows in Struts2. We also know the use of struts.xml and properties file. In this application we implemented a preliminary form of validation. In <a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html"><strong>next part</strong></a> we will learn more about Validation Framework in Struts2 and implement it in our example.</p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" title="Introduction to Struts 2 Framework">Introduction to Struts 2 Framework</a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html" title="Struts 2 File Upload and Save Tutorial with Example">Struts 2 File Upload and Save Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html" title="Struts2 Interceptors Tutorial with Example">Struts2 Interceptors Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html" title="Struts 2 Tiles Plugin Tutorial with Example in Eclipse">Struts 2 Tiles Plugin Tutorial with Example in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2010/02/create-url-shortner-in-java-struts2-hibernate.html" title="Writing a URL Shortner in Java Struts2 &#038; Hibernate ">Writing a URL Shortner in Java Struts2 &#038; Hibernate </a></li><li><a href="http://viralpatel.net/blogs/2010/02/generate-pie-chart-bar-graph-in-pdf-using-itext-jfreechart.html" title="Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart">Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html&amp;title=Tutorial: Create Struts 2 Application in Eclipse&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html&amp;title=Tutorial: Create Struts 2 Application in Eclipse" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html&amp;title=Tutorial: Create Struts 2 Application in Eclipse" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html&amp;title=Tutorial: Create Struts 2 Application in Eclipse" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html/feed</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Introduction to Struts 2 Framework</title>
		<link>http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html</link>
		<comments>http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html#comments</comments>
		<pubDate>Tue, 22 Dec 2009 08:00:39 +0000</pubDate>
		<dc:creator>Viral Patel</dc:creator>
				<category><![CDATA[Struts 2]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[J2EE]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[struts2 architecture]]></category>
		<category><![CDATA[struts2-series]]></category>

		<guid isPermaLink="false">http://viralpatel.net/blogs/?p=1934</guid>
		<description><![CDATA[
Lot of times I have been asked by users on this site to write tutorial about Struts 2 Framework. My previous tutorial on Creating Struts Application in Eclipse is one of the most viewed article on this site.
So lets begin Part 1 of 7-parts series tutorials on Struts 2 Framework. In these tutorials we will [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/2009/12/struts-2-introduction.png" alt="struts-2-introduction" title="struts-2-introduction" width="598" height="156" class="aligncenter" border="0"/><br />
Lot of times I have been asked by users on this site to write tutorial about Struts 2 Framework. My previous tutorial on <a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html" target="_blank">Creating Struts Application in Eclipse</a> is one of the most viewed article on this site.</p>
<p>So lets begin Part 1 of 7-parts series tutorials on Struts 2 Framework. In these tutorials we will discuss the Introduction of Struts2 framework, validation framework, the interceptors in struts 2, tiles plugin and its application with example, a file upload example and struts2 ajax example.</p>
<style type="text/css">#struts { color:#222222; width: 98%; background-color: #EEFF99; padding:5px; -moz-border-radius: 10px; -webkit-border-radius: 10px; }#struts h3 { font-size: 18px; text-decoration:underline; }#struts ul { list-style:none; }#struts ul li { padding:3px; }</style><div id="struts"><h3>Struts 2 Tutorials</h3><ul>	<li><a href="http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html">Part 1: Introduction to Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Part 2: Create Hello World Application in Struts 2</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-tiles-plugin-tutorial-with-example-in-eclipse.html">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts2-interceptors-tutorial-with-example.html">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>	<li><a href="http://viralpatel.net/blogs/2009/12/struts-2-file-upload-save-tutorial-with-example.html">Part 6: Struts 2 File Upload and Save Example</a></li>	<li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html">Part 7: Struts 2 Ajax Tutorial with Example</a></li></ul></div>
<h2>Introduction of Struts 2 Framework</h2>
<p>Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready Java web applications. The framework is designed to streamline the full development cycle, from building, to deploying, to maintaining applications over time.</p>
<p>Apache Struts2 was originally known as WebWork 2. After working independently for several years, the WebWork and Struts communities joined forces to create Struts2. This new version of Struts is simpler to use and closer to how Struts was always meant to be. </p>
<p>Struts 2 is a pull-MVC framework. i.e. the data that is to be displayed to user has to be pulled from the Action. </p>
<p>Struts2 supports annotation based configurations which are easy to create and more intuitive. Action class in Struts 2 act as the model in the web application. Unlike Struts, Struts 2 Action class are plain POJO objects thus simplifying the testing of the code. Struts2 also comes with power APIs to configure Interceptors that reduce greatly the coupling in application. The view part of Struts 2 is highly configurable and it supports different result-types such as Velocity, FreeMarker, JSP, etc.</p>
<h2>Architecture of Struts 2</h2>
<p>Struts 2 Architecture is based on WebWork 2 framework. It leverages the standard JEE technologies such as Java Filters, JavaBeans, ResourceBundles, Locales, XML etc in its architecture.<br />
Following is its framework diagram.<br />
<img src="http://struts.apache.org/2.x/docs/architecture.data/Struts2-Architecture.png" width="80%" height="80%" title="struts 2 architecture" alt="struts 2 architecture" class="aligncenter"/><br />
Image Courtesy: <a href="http://struts.apache.org/2.x/docs/architecture.html" target="_blank" rel="nofollow">struts.apache.org</a></p>
<ol>
<li>The normal lifecycle of struts begins when the request is sent from client. This results invoke the servlet container which in turn is passed through standard filter chain.</li>
<li>The <code>FilterDispatcher</code> filter is called which consults the <strong>ActionMapper</strong> to determine whether an <strong>Action</strong> should be invoked.</li>
<li>If ActionMapper finds an Action to be invoked, the FilterDispatcher delegates control to <strong>ActionProxy</strong>. </li>
<li>ActionProxy reads the configuration file such as struts.xml. ActionProxy creates an instance of <strong>ActionInvocation</strong> class and delegates the control. </li>
<li>ActionInvocation is responsible for command pattern implementation. It invokes the Interceptors one by one (if required) and then invoke the Action.</li>
<li>Once the Action returns, the <strong>ActionInvocation</strong> is responsible for looking up the proper result associated with the Action result code mapped in <code>struts.xml</code>.</li>
<li>The Interceptors are executed again in reverse order and the response is returned to the Filter (In most cases to <code>FilterDispatcher</code>). And the result is then sent to the servlet container which in turns send it back to client.</li>
</ol>
<h2>Request Processing Lifecycle</h2>
<p><img src="http://img.viralpatel.net/2009/12/struts-2-request-cycle.png" alt="" title="struts-2-request-cycle" width="481" height="184" class="aligncenter size-full wp-image-1937" /><br />
The request processing lifecycle of Struts2 framework is pretty much discussed in above section where we saw the architecture of Struts 2 framework.</p>
<ol>
<li>Request is generated by user and sent to Servlet container. </li>
<li>Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.</li>
<li>One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.</li>
<li>Action is executed and the Result is generated by Action.</li>
<li>The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.</li>
</ol>
<h2>AJAX Support in Struts 2</h2>
<p>AJAX is a well known term in web development. It is now possible to write desktop like web2.0 application using AJAX. Untill Struts 1.x, developer had to write and maintain the code in javascript to add AJAX support.<br />
But now Struts 2 gives you Ajax ‘out of the box’. No writing of javascript, no debugging against various browsers; just configure and go. </p>
<p>Struts 2 comes with highly configurable AJAX tag library which can be used directly without writing JavaScript code. Struts 2 also support Dojo library. Its now very easy to add AJAX enabled feature such as <a target="_blank" href="http://viralpatel.net/blogs/2009/06/tutorial-create-autocomplete-feature-with-java-jsp-jquery.html">Autocomplete</a> to your web application.<br />
<strong>Related:</strong> <a target="_blank" href="http://viralpatel.net/blogs/2009/02/introduction-to-dojo-toolkit-javascript-framework.html">Introduction to DOJO Toolkit</a></p>
<h2>Comparison of Struts 1 and Struts 2</h2>
<p>Let us see the basic difference between Struts 1 and 2 framework.</p>
<ol>
<li>Unlike Struts 1, Struts 2 does not need to implement Action class. The Action in Struts 2 is a POJO object. Thus making it easy to unit test the code.</li>
<li>Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. </li>
<li>Struts 1 Actions have dependencies on the servlet API since the <code>HttpServletRequest</code> and <code>HttpServletResponse</code> is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation.</li>
<li>Struts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties.</li>
<li>Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called &#8220;Object Graph Notation Language&#8221; (OGNL).</li>
<li>Struts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a &#8220;ValueStack&#8221; technology so that the taglibs can access values without coupling your view to the object type it is rendering.</li>
<li>Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.</li>
</ol>
<h2>Moving On</h2>
<p>Now that we have idea about architecture of Struts 2 framework and its lifecycle, in <a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html">the next part</a> we will create a working Struts 2 Hello World application from scratch.</p>
<div id="relatedpost" style="background-color:#FFF1A8; padding:3px;"><h2  class="related_post_title">See also:</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2009/12/struts2-validation-framework-tutorial-example.html" title="Struts2 Validation Framework Tutorial with Example">Struts2 Validation Framework Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html" title="Tutorial: Create Struts 2 Application in Eclipse">Tutorial: Create Struts 2 Application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2008/12/implement-ldap-authentication-in-tomcat-jboss-server-for-java-app.html" title="Implement LDAP authentication in Tomcat &#038; JBoss server for Java app">Implement LDAP authentication in Tomcat &#038; JBoss server for Java app</a></li><li><a href="http://viralpatel.net/blogs/2010/02/generate-pie-chart-bar-graph-in-pdf-using-itext-jfreechart.html" title="Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart">Generate Pie Chart/Bar Graph in PDF using iText &#038; JFreeChart</a></li><li><a href="http://viralpatel.net/blogs/2010/02/most-useful-java-best-practice-quotes-java-developers.html" title="10 Most Useful Java Best Practice Quotes for Java Developers">10 Most Useful Java Best Practice Quotes for Java Developers</a></li><li><a href="http://viralpatel.net/blogs/2010/01/r-i-p-sun-james-gosling-paying-respects.html" title="R.I.P Sun: James Gosling paying Respects">R.I.P Sun: James Gosling paying Respects</a></li><li><a href="http://viralpatel.net/blogs/2010/01/struts-2-ajax-tutorial-example-drop-down.html" title="Struts 2 Ajax Tutorial with Example">Struts 2 Ajax Tutorial with Example</a></li><li><a href="http://viralpatel.net/blogs/2010/01/configuring-mdp-and-controlling-it-with-and-without-jmx.html" title="Configuring MDP and Controlling it With and Without JMX">Configuring MDP and Controlling it With and Without JMX</a></li></ul></div><a href="http://www.facebook.com/share.php?u=http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html" target="_blank"><img src="http://img.viralpatel.net/facebook-ico.png" alt="Facebook" border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://twitter.com/home?status=http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html target="_blank"><img src="http://img.viralpatel.net/twitter-ico.png" alt="Twitter"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://digg.com/submit?url=http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html&amp;title=Introduction to Struts 2 Framework&amp;bodytext=&amp;media=&amp;topic=" target="_blank"><img src="http://img.viralpatel.net/digg-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://reddit.com/submit?url=http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html&amp;title=Introduction to Struts 2 Framework" target="_blank"><img src="http://img.viralpatel.net/reddit-ico.png" alt=""  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://www.stumbleupon.com/submit?url=http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html&amp;title=Introduction to Struts 2 Framework" target="_blank"><img src="http://img.viralpatel.net/stumble-upon-ico.png" alt="Stumbleupon"  border="0" width="47" height="48"/></a>&nbsp;&nbsp;<a href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html&amp;title=Introduction to Struts 2 Framework" target="_blank"><img src="http://img.viralpatel.net/delicious-ico.png" alt="Delicious" border="0" width="47" height="48"/></a></div>]]></content:encoded>
			<wfw:commentRss>http://viralpatel.net/blogs/2009/12/introduction-to-struts-2-framework.html/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
