<?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; Struts</title> <atom:link href="http://viralpatel.net/blogs/category/struts/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>Tue, 24 Jan 2012 13:45:10 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts</title><link>http://viralpatel.net/blogs/2009/06/struts-displaytag-tutorial-sort-pagination-data-displaytag-struts.html</link> <comments>http://viralpatel.net/blogs/2009/06/struts-displaytag-tutorial-sort-pagination-data-displaytag-struts.html#comments</comments> <pubDate>Tue, 09 Jun 2009 11:53:03 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Struts]]></category> <category><![CDATA[displaytags]]></category> <category><![CDATA[displaytags sorting]]></category> <category><![CDATA[pagination]]></category> <category><![CDATA[struts displaytag]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=1385</guid> <description><![CDATA[Struts display tag library is an open source suite of custom tags that provide high-level web presentation patterns which will work in an MVC model. The library provides a significant amount of functionality while still being easy to use. Displaytag can handle column display, sorting, paging, cropping, grouping, exporting, smart linking and decoration of a [...]]]></description> <content:encoded><![CDATA[<p>Struts display tag library is an open source suite of custom tags that provide high-level web presentation patterns which will work in an MVC model. The library provides a significant amount of functionality while still being easy to use. Displaytag can handle column display, sorting, paging, cropping, grouping, exporting, smart linking and decoration of a table in a customizable XHTML style.</p><p>In the following example we will see how to dispaly data using display tag and to do pagination and sorting. We will use Eclipse as an IDE for our example.</p><h2>Step 1: Create Eclipse dynamic web project and copy JAR files</h2><p>Start Eclipse and goto File -> New -> Project -> Dynamic Web Project<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>Following is the list of required JAR files to be added in Java Class Path of your project. Download displaytag JAR files from <a rel="nofollow" target="_new" href="http://displaytag.sourceforge.net/1.2/download.html">http://displaytag.sourceforge.net/1.2/download.html</a>.</p><p><img src="http://img.viralpatel.net/2009/06/displaytag-jar-file-list.png" alt="displaytag-jar-file-list" title="displaytag-jar-file-list" width="210" height="195" class="aligncenter size-full wp-image-1390" /></p><h2>Step 2: Create Action, Form and Bean class</h2><p>Once the project is created, create 3 java files <strong>ForbesData</strong>, <strong>UserAction</strong> and <strong>UserForm</strong> in package <strong>net.viralpatel.struts.displaytag</strong>.<br /> <img src="http://img.viralpatel.net/2009/06/struts-displaytag-new-java.png" alt="struts-displaytag-new-java" title="struts-displaytag-new-java" width="237" height="122" class="aligncenter size-full wp-image-1387" /></p><p>Copy following content into ForbesData.java file.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.displaytag;

import java.util.ArrayList;

public class ForbesData {
	private int rank;
	private String name;
	private int age;
	private double netWorth;

	public ForbesData() {

	}

	public ForbesData(int rank, String name, int age, double netWorth) {
		this.rank = rank;
		this.name = name;
		this.age = age;
		this.netWorth = netWorth;
	}
	public ArrayList&lt;ForbesData&gt; loadData() {
		ArrayList&lt;ForbesData&gt; userList = new ArrayList&lt;ForbesData&gt;();
		userList.add(new ForbesData(1, &quot;William Gates III&quot;, 53, 40.0));
		userList.add(new ForbesData(2, &quot;Warren Buffett&quot;, 78, 37));
		userList.add(new ForbesData(3, &quot;Carlos Slim Helu &amp;amp; family&quot;, 69, 35));
		userList.add(new ForbesData(4, &quot;Lawrence Ellison&quot;, 64, 22.5));
		userList.add(new ForbesData(5, &quot;Ingvar Kamprad &amp;amp; family&quot;, 83, 22));
		userList.add(new ForbesData(6, &quot;Karl Albrecht&quot;, 89, 21.5));
		userList.add(new ForbesData(7, &quot;Mukesh Ambani&quot;, 51, 19.5));
		userList.add(new ForbesData(8, &quot;Lakshmi Mittal&quot;, 58, 19.3));
		userList.add(new ForbesData(9, &quot;Theo Albrecht&quot;, 87, 18.8));
		userList.add(new ForbesData(10, &quot;Amancio Ortega&quot;, 73, 18.3));
		userList.add(new ForbesData(11, &quot;Jim Walton&quot;, 61, 17.8));
		userList.add(new ForbesData(12, &quot;Alice Walton&quot;, 59, 17.6));
		userList.add(new ForbesData(12, &quot;Christy Walton &amp;amp; family&quot;, 54, 17.6));
		userList.add(new ForbesData(12, &quot;S Robson Walton&quot;, 65, 17.6));
		userList.add(new ForbesData(15, &quot;Bernard Arnault&quot;, 60, 16.5));
		userList.add(new ForbesData(16, &quot;Li Ka-shing&quot;, 80, 16.2));
		userList.add(new ForbesData(17, &quot;Michael Bloomberg&quot;, 67, 16));
		userList.add(new ForbesData(18, &quot;Stefan Persson&quot;, 61, 14.5));
		userList.add(new ForbesData(19, &quot;Charles Koch&quot;, 73, 14));
		userList.add(new ForbesData(19, &quot;David Koch&quot;, 68, 14));
		userList.add(new ForbesData(21, &quot;Liliane Bettencourt&quot;, 86, 13.4));
		userList.add(new ForbesData(22, &quot;Prince Alwaleed Bin Talal Alsaud&quot;, 54, 13.3));
		return userList;
	}
	public int getRank() {
		return rank;
	}
	public void setRank(int rank) {
		this.rank = rank;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public double getNetWorth() {
		return netWorth;
	}
	public void setNetWorth(double netWorth) {
		this.netWorth = netWorth;
	}
}
</pre><p>Copy following content into UserForm.java</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.displaytag;

import java.util.ArrayList;

public class UserForm extends org.apache.struts.action.ActionForm {

	private ArrayList&lt;ForbesData&gt; forbesList;

	public ArrayList&lt;ForbesData&gt; getForbesList() {
		return forbesList;
	}

	public void setForbesList(ArrayList&lt;ForbesData&gt; forbesList) {
		this.forbesList = forbesList;
	}
}
</pre><p>Copy following content into UserAction.java</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.displaytag;

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

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

public class UserAction extends Action {

    private final static String SUCCESS = &quot;success&quot;;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        UserForm userForm = (UserForm) form;
        ForbesData actorData = new ForbesData();
        userForm.setForbesList(actorData.loadData());
        return mapping.findForward(SUCCESS);
    }

}
</pre><h2>Step 3: Create JSPs, struts-config.xml and web.xml</h2><p>Create index.jsp and user.jsp in WebContent folder and struts-config.xml and web.xml in WebContent/WEB-INF folder.<br /> <img src="http://img.viralpatel.net/2009/06/struts-displaytag-web-xml-jsp1.png" alt="struts-displaytag-web-xml-jsp" title="struts-displaytag-web-xml-jsp" width="206" height="110" class="aligncenter size-full wp-image-1389" /></p><p>Copy following content into appropriate files.</p><h3>index.jsp</h3><pre class="brush: xml; title: ; notranslate">
&lt;%@page contentType=&quot;text/html&quot;%&gt;
&lt;%@page pageEncoding=&quot;UTF-8&quot;%&gt;

&lt;jsp:forward page=&quot;userAction.do&quot;/&gt;
</pre><h3>user.jsp</h3><pre class="brush: xml; title: ; notranslate">
&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;%@taglib uri=&quot;http://displaytag.sf.net&quot; prefix=&quot;display&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;The World's Billionaires 2009&lt;/title&gt;
        &lt;link href=&quot;css/style.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;/head&gt;
    &lt;body&gt;
    &lt;h2&gt;The World's Billionaires 2009 - Forbes List&lt;/h2&gt;
        &lt;display:table export=&quot;true&quot;  id=&quot;data&quot;
        			name=&quot;sessionScope.UserForm.forbesList&quot;
        			requestURI=&quot;/userAction.do&quot; pagesize=&quot;10&quot; &gt;
            &lt;display:column property=&quot;rank&quot; title=&quot;Rank&quot; sortable=&quot;true&quot;   /&gt;
            &lt;display:column property=&quot;name&quot; title=&quot;Name&quot; sortable=&quot;true&quot;  /&gt;
            &lt;display:column property=&quot;age&quot; title=&quot;Age&quot; sortable=&quot;true&quot;  /&gt;
            &lt;display:column property=&quot;netWorth&quot; title=&quot;Net worth ($BIL)&quot;
            		sortable=&quot;true&quot;  /&gt;
        &lt;/display:table&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre><h3>struts-config.xml</h3><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;

&lt;!DOCTYPE struts-config PUBLIC
          &quot;-//Apache Software Foundation//DTD Struts Configuration 1.2//EN&quot;
          &quot;http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd&quot;&gt;

&lt;struts-config&gt;
    &lt;form-beans&gt;
        &lt;form-bean name=&quot;UserForm&quot;
        	type=&quot;net.viralpatel.struts.displaytag.UserForm&quot;/&gt;
    &lt;/form-beans&gt;

    &lt;global-exceptions&gt;

    &lt;/global-exceptions&gt;

    &lt;global-forwards&gt;
        &lt;forward name=&quot;welcome&quot;  path=&quot;/Welcome.do&quot;/&gt;
    &lt;/global-forwards&gt;

    &lt;action-mappings&gt;
        &lt;action input=&quot;/&quot; name=&quot;UserForm&quot; path=&quot;/userAction&quot;
        	scope=&quot;session&quot; type=&quot;net.viralpatel.struts.displaytag.UserAction&quot;&gt;
            &lt;forward name=&quot;success&quot; path=&quot;/user.jsp&quot; /&gt;
        &lt;/action&gt;
        &lt;action path=&quot;/Welcome&quot; forward=&quot;/welcomeStruts.jsp&quot;/&gt;
    &lt;/action-mappings&gt;

    &lt;message-resources parameter=&quot;com/vaannila/ApplicationResource&quot;/&gt;

&lt;/struts-config&gt;
</pre><h3>web.xml</h3><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;2.5&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot;
	xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;
	&lt;servlet&gt;
		&lt;servlet-name&gt;action&lt;/servlet-name&gt;
		&lt;servlet-class&gt;
			org.apache.struts.action.ActionServlet
		&lt;/servlet-class&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;config&lt;/param-name&gt;
			&lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt;
		&lt;/init-param&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;debug&lt;/param-name&gt;
			&lt;param-value&gt;2&lt;/param-value&gt;
		&lt;/init-param&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;detail&lt;/param-name&gt;
			&lt;param-value&gt;2&lt;/param-value&gt;
		&lt;/init-param&gt;
		&lt;load-on-startup&gt;2&lt;/load-on-startup&gt;
	&lt;/servlet&gt;
	&lt;servlet-mapping&gt;
		&lt;servlet-name&gt;action&lt;/servlet-name&gt;
		&lt;url-pattern&gt;*.do&lt;/url-pattern&gt;
	&lt;/servlet-mapping&gt;
	&lt;session-config&gt;
		&lt;session-timeout&gt;30&lt;/session-timeout&gt;
	&lt;/session-config&gt;
	&lt;welcome-file-list&gt;
		&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
	&lt;/welcome-file-list&gt;
&lt;/web-app&gt;
</pre><h2>Step 4: Execute the project</h2><p>We are done with the project. Now execute the project in eclipse or create a WAR file and run it in Tomcat.</p><p><img src="http://img.viralpatel.net/2009/06/struts-displaytag-example.png" alt="struts-displaytag-example" title="struts-displaytag-example" width="500" height="498" class="aligncenter size-full wp-image-1386" /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</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/03/tutorial-creating-dynaactionform-example-in-struts-dynaactionform-struts.html" title="Tutorial: Creating DynaActionForm example in Struts">Tutorial: Creating DynaActionForm example in Struts</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>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/06/struts-displaytag-tutorial-sort-pagination-data-displaytag-struts.html/feed</wfw:commentRss> <slash:comments>84</slash:comments> </item> <item><title>Tutorial: Creating DynaActionForm example in Struts</title><link>http://viralpatel.net/blogs/2009/03/tutorial-creating-dynaactionform-example-in-struts-dynaactionform-struts.html</link> <comments>http://viralpatel.net/blogs/2009/03/tutorial-creating-dynaactionform-example-in-struts-dynaactionform-struts.html#comments</comments> <pubDate>Wed, 11 Mar 2009 13:43:04 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Struts]]></category> <category><![CDATA[ActionForm]]></category> <category><![CDATA[DynaActionForm]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=946</guid> <description><![CDATA[We learned in this tutorial about creating a basic web application in Struts, We had used Struts Frameworks ActionForm to manage the form data. Let us see how to use DynaActionForm to manage the form data. DynaActionForm is also called as Dynamic Form Bean. These are extensions of Form Beans that allow you to specify [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/apache-struts-logo-150x119.jpg" alt="apache-struts-logo" title="apache-struts-logo" width="150" height="119" class="alignright size-thumbnail wp-image-951" /><br /> We learned in <a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html">this tutorial</a> about creating a basic web application in Struts, We had used Struts Frameworks ActionForm to manage the form data. Let us see how to use DynaActionForm to manage the form data.</p><p><strong>DynaActionForm</strong> is also called as Dynamic Form Bean. These are extensions of Form Beans that allow you to specify their properties inside the struts configuration file instead of having to create a concrete class.</p><p>To create a DynaActionForm, we have to make following entry in struts-config.xml file.</p><pre class="brush: xml; title: ; notranslate">
&lt;form-beans&gt;
	&lt;form-bean name=&quot;LoginForm&quot;
		type=&quot;org.apache.struts.action.DynaActionForm&quot;&gt;
		&lt;form-property name=&quot;username&quot; type=&quot;java.lang.String&quot;
			initial=&quot;UserName&quot;/&gt;
		&lt;form-property name=&quot;password&quot; type=&quot;java.lang.String&quot;
			initial=&quot;Password&quot;/&gt;
	&lt;/form-bean&gt;
&lt;/form-beans&gt;
</pre><p>While using ActionForm, we create an entry in struts-config.xml with &lt;form-bean&gt; tag. We specify the class name of ActionForm class.<br /> In case of DynaActionForm, we create a dynamic form bean by specifying properties in struts-config.xml itself. In above code snippet we have created a login form with two properties: username and password. We have also provided its initial values.</p><p>Once you have define an entry for Form bean in struts-config.xml, you can use this form in any of your action using normal &lt;action&gt; tag.</p><pre class="brush: xml; title: ; notranslate">
&lt;action path=&quot;/login&quot; name=&quot;LoginForm&quot; validate=&quot;true&quot; input=&quot;/index.jsp&quot;
             type=&quot;net.viralpatel.struts.helloworld.action.LoginAction&quot;&gt;
</pre><p>Hence when the login action will be called, the form data will be populated in DynaActionForm and bean object will be passed to execute() method of LoginAction.</p><p>To fetch the form data from Form object use get() method of DynaActionForm class.</p><pre class="brush: java; title: ; notranslate">
public ActionForward execute(ActionMapping mapping, ActionForm form,
             HttpServletRequest request, HttpServletResponse response)
             throws Exception {  

	DynaActionForm dynaForm = (DynaActionForm)form;
	String userName = (String)dynaForm.get(&quot;username&quot;);
	String password = (String)dynaForm.get(&quot;password&quot;);
...
...
}
</pre><div id="relatedpost"><h2  class="related_post_title">Related Posts</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/06/struts-displaytag-tutorial-sort-pagination-data-displaytag-struts.html" title="Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts">Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts</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>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/03/tutorial-creating-dynaactionform-example-in-struts-dynaactionform-struts.html/feed</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>Creating &amp; Parsing JSON data with Java Servlet/Struts/JSP</title><link>http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html</link> <comments>http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html#comments</comments> <pubDate>Thu, 19 Feb 2009 10:34:07 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Struts]]></category> <category><![CDATA[json]]></category> <category><![CDATA[JSONObject]]></category> <category><![CDATA[servlet]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=836</guid> <description><![CDATA[JSON (JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). The JSON format is specified in RFC 4627 by Douglas Crockford. The official Internet media type for JSON is application/json. The JSON format is often used for transmitting [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/java-logo2-150x150.gif" alt="java logo" title="java-logo2" width="150" height="150" class="alignleft size-thumbnail wp-image-840" /><br /> JSON (JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects). The JSON format is specified in <a rel="nofollow" target="_new" href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a> by Douglas Crockford. The official Internet media type for JSON is <strong>application/json</strong>.</p><p>The JSON format is often used for transmitting structured data over a network connection in a process called serialization. Its main application is in AJAX web application programming, where it serves as an alternative to the traditional use of the XML format.</p><h2>Supported data types</h2><ol><li>Number (integer, real, or floating point)</li><li>String (double-quoted Unicode with backslash escapement)</li><li>Boolean (true and false)</li><li>Array (an ordered sequence of values, comma-separated and enclosed in square brackets)</li><li>Object (collection of key/value pairs, comma-separated and enclosed in curly brackets)</li><li>null</li></ol><h2>Syntax</h2><p>The following example shows the JSON representation of an object that describes a person. The object has string fields for first name and last name, contains an object representing the person&#8217;s address, and contains a list of phone numbers (an array).</p><pre class="brush: jscript; title: ; notranslate">
{
    &quot;firstName&quot;: &quot;John&quot;,
    &quot;lastName&quot;: &quot;Smith&quot;,
    &quot;address&quot;: {
        &quot;streetAddress&quot;: &quot;21 2nd Street&quot;,
        &quot;city&quot;: &quot;New York&quot;,
        &quot;state&quot;: &quot;NY&quot;,
        &quot;postalCode&quot;: 10021
    },
    &quot;phoneNumbers&quot;: [
        &quot;212 732-1234&quot;,
        &quot;646 123-4567&quot;
    ]
}
</pre><h2>Creating JSON data in Java</h2><p><a href="http://json.org/java/" rel="nofollow" target="_new">JSON.org</a> has provided libraries to create/parse JSON data through Java code. These libraries can be used in any Java/J2EE project including Servlet, Struts, JSF, JSP etc and JSON data can be created.</p><p>Download JAR file <a href="http://viralpatel.net/blogs/download/json/json-rpc-1.0.jar">json-rpc-1.0.jar (75 kb)</a></p><p>Use JSONObject class to create JSON data in Java. A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get()  and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.</p><pre class="brush: java; title: ; notranslate">
import org.json.JSONObject;

...
...

JSONObject json = new JSONObject();
json.put(&quot;city&quot;, &quot;Mumbai&quot;);
json.put(&quot;country&quot;, &quot;India&quot;);

...

String output = json.toString();

...
</pre><p>Thus by using toString() method you can get the output in JSON format.</p><h2>JSON Array in Java</h2><p>A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having get and opt  methods for accessing the values by index, and put methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.</p><p>The constructor can convert a JSON text into a Java object. The toString method converts to JSON text.</p><p>JSONArray class can also be used to convert a collection of Java beans into JSON data. Similar to JSONObject, JSONArray has a put() method that can be used to put a collection into JSON object.</p><p>Thus by using JSONArray you can handle any type of data and convert corresponding JSON output.</p><h2>Using json-lib library</h2><p>JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back again to beans and DynaBeans.</p><p>Json-lib comes in two flavors, depending on the jdk compatibility. json-lib-x.x-jdk13 is compatible with JDK 1.3.1 and upwards. json-lib-x.x-jdk15 is compatible with JDK 1.5, includes support for Enums in JSONArray and JSONObject.</p><p>Download: <a rel="nofollow" href="http://sourceforge.net/projects/json-lib/files/json-lib/">json-lib.jar</a></p><p>Json-lib requires (at least) the following dependencies in your classpath:</p><ol><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-lang/commons-lang/2.5/commons-lang-2.5.jar">jakarta commons-lang 2.5</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-beanutils/commons-beanutils/1.8.1/commons-beanutils-1.8.1.jar">jakarta commons-beanutils 1.8.0</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-collections/commons-collections/3.2.1/commons-collections-3.2.1.jar">jakarta commons-collections 3.2.1</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar">jakarta commons-logging 1.1.1</a></li><li><a rel="nofollow" href="http://repo1.maven.org/maven2/net/sf/ezmorph/ezmorph/1.0.6/ezmorph-1.0.6.jar">ezmorph 1.0.6</a></li></ol><h3>Example</h3><pre class="brush: java; title: ; notranslate">
package net.viralpatel.java;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

public class JsonMain {
	public static void main(String[] args) {

		Map&lt;String, Long&gt; map = new HashMap&lt;String, Long&gt;();
		map.put(&quot;A&quot;, 10L);
		map.put(&quot;B&quot;, 20L);
		map.put(&quot;C&quot;, 30L);

		JSONObject json = new JSONObject();
		json.accumulateAll(map);

		System.out.println(json.toString());

		List&lt;String&gt; list = new ArrayList&lt;String&gt;();
		list.add(&quot;Sunday&quot;);
		list.add(&quot;Monday&quot;);
		list.add(&quot;Tuesday&quot;);

		json.accumulate(&quot;weekdays&quot;, list);
		System.out.println(json.toString());
	}
}
</pre><p><strong>Output: </strong></p><pre class="brush: java; gutter: false; title: ; notranslate">
{&quot;A&quot;:10,&quot;B&quot;:20,&quot;C&quot;:30}
{&quot;A&quot;:10,&quot;B&quot;:20,&quot;C&quot;:30,&quot;weekdays&quot;:[&quot;Sunday&quot;,&quot;Monday&quot;,&quot;Tuesday&quot;]}
</pre><p><br/></p><h2>Using Google Gson library</h2><p>Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.</p><p>There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes; something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.</p><h3>Gson Goals</h3><ul><li>Provide simple <code>toJson()</code> and <code>fromJson()</code> methods to convert Java objects to JSON and vice-versa</li><li>Allow pre-existing unmodifiable objects to be converted to and from JSON</li><li>Extensive support of Java Generics</li><li>Allow custom representations for objects</li><li>Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types)</li></ul><h3>Google Gson Example</h3><pre class="brush: java; title: ; notranslate">
import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json =
            &quot;{&quot;
                + &quot;'title': 'Computing and Information systems',&quot;
                + &quot;'id' : 1,&quot;
                + &quot;'children' : 'true',&quot;
                + &quot;'groups' : [{&quot;
                    + &quot;'title' : 'Level one CIS',&quot;
                    + &quot;'id' : 2,&quot;
                    + &quot;'children' : 'true',&quot;
                    + &quot;'groups' : [{&quot;
                        + &quot;'title' : 'Intro To Computing and Internet',&quot;
                        + &quot;'id' : 3,&quot;
                        + &quot;'children': 'false',&quot;
                        + &quot;'groups':[]&quot;
                    + &quot;}]&quot;
                + &quot;}]&quot;
            + &quot;}&quot;;

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List&lt;Data&gt; groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List&lt;Data&gt; getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List&lt;Data&gt; groups) { this.groups = groups; }

    public String toString() {
        return String.format(&quot;title:%s,id:%d,children:%s,groups:%s&quot;, title, id, children, groups);
    }
</pre><p><br/></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</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/2008/12/tutorial-creating-struts-application-in-eclipse.html" title="Tutorial: Creating Struts application in Eclipse">Tutorial: Creating Struts application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2008/12/calling-rpc-in-javascript-using-json-rpc-java.html" title="RPC in Javascript using JSON-RPC-Java">RPC in Javascript using JSON-RPC-Java</a></li><li><a href="http://viralpatel.net/blogs/2008/11/apostrophe-creating-problem-in-properties-file-in-java-struts.html" title="Apostrophe creating problem in properties file in java/struts">Apostrophe creating problem in properties file in java/struts</a></li><li><a href="http://viralpatel.net/blogs/2008/11/multiple-message-resource-property-file-in-struts.html" title="Multiple message resource property file in Struts">Multiple message resource property file in Struts</a></li><li><a href="http://viralpatel.net/blogs/2012/01/convert-array-to-set-java-arraylist.html" title="Convert Arrays to Set in Java">Convert Arrays to Set in Java</a></li><li><a href="http://viralpatel.net/blogs/2012/01/create-qr-codes-java-servlet-qr-code-java.html" title="How To Create QR Codes in Java &#038; Servlet">How To Create QR Codes in Java &#038; Servlet</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/02/creating-parsing-json-data-with-java-servlet-struts-jsp-json.html/feed</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Struts Validation Framework Tutorial with example.</title><link>http://viralpatel.net/blogs/2009/01/struts-validation-framework-tutorial-example-validator-struts-validation-form-validation.html</link> <comments>http://viralpatel.net/blogs/2009/01/struts-validation-framework-tutorial-example-validator-struts-validation-form-validation.html#comments</comments> <pubDate>Thu, 22 Jan 2009 06:30:47 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Struts]]></category> <category><![CDATA[struts validator]]></category> <category><![CDATA[struts-plugin]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[validation framework]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=682</guid> <description><![CDATA[Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications. Introduction to Struts Validation Framework One of the important features of Struts framework is Struts Validation framework that performs validation on [...]]]></description> <content:encoded><![CDATA[<p><img src="http://img.viralpatel.net/apache-struts-logo.jpg" alt="apache struts logo" title="apache-struts-logo" width="197" height="119" class="alignright size-full wp-image-692" /><br /> Apache Struts has changed the way we develop a Web application. Since its inception as an MVC architecture, Struts has been extensively used in J2EE world to develop robust, extendable and effective web applications.</p><h2>Introduction to Struts Validation Framework</h2><p><div style='margin:0 10px 0 0; display: block; float: left; '><script type="text/javascript"><!--
google_ad_client = "ca-pub-2652062086099003";
/* 250x250, created 9/16/09 */
google_ad_slot = "1602773796";
google_ad_width = 250;
google_ad_height = 250;
//--></script><script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></div> One of the important features of Struts framework is <strong>Struts Validation framework</strong> that performs validation on incoming form data. Validation framework was introduced by <strong>David Winterfeldt</strong> as an external plugin to Struts framework. It&#8217;s functionality has since been split so that validator can serve as the basis for a independant component and is now part of <strong>Jakarta Commons</strong>.</p><p>The Struts framework&#8217;s simple validation interface 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>In order to do form validation without Validator framework, one has to use <strong>validate()</strong> method of the form bean (<strong>ActionForm </strong>class) to perform this task. Also one has to handle error messages during manual validation. Lot of fields that we validate require same logic to validate them, hence code is unneccessarily duplicated (if not managed properly).</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 form validation</strong>. If certain validation is not present, you can create your own validation logic and plug it into validation framework as a re-usable component.</p><p>Validator uses two XML configuration files to determine which validation routines should be installed and how they should be applied for a given application, respectively. 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><p>The second configuration file, validation.xml, defines which validation routines should be applied to which Form Beans. The definitions in this file use the logical names of Form Beans from the struts-config.xml file along with the logical names of validation routines from the validator-rules.xml file to tie the two together.</p><p>Using the Validator framework involves enabling the Validator plug-in, configuring Validator&#8217;s  two configuration files, and  creating Form Beans that extend  the Validator&#8217;s </span><tt>ActionForm</tt><span class="bodycopy"> subclasses. The following sections explain in detail how to configure and use Validator.</p><h2>Create a Struts project</h2><p>Create a struts web application project. I assume you have working environment set for a Struts project. If not then go through the tutorial: <a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html"><strong>Creating Struts application using Eclipse</strong></a> and create a struts project.</p><h2>Create Form Beans</h2><p><img src="http://img.viralpatel.net/struts-validator-form-bean.png" alt="struts validator form bean" title="struts-validator-form-bean" width="275" height="118" class="aligncenter size-full wp-image-686" /><br /> Create a form bean in your project called CustomerForm and copy following code in it.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.validation.form;

import org.apache.struts.validator.ValidatorForm;

public class CustomerForm extends ValidatorForm {

	private String name;
	private String telephone;
	private String email;
	private int age;

	public String getName() {
		return name;
	}

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

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}
</pre><p>We will use this validator plugin to validate this form. Note that the form bean is extended from class <strong>ValidatorForm</strong> and not ActionForm as we generally do in Struts project.</p><h2>Add Validator Plug-in in struts-config.xml</h2><p>In order to use Validator in our project we need to configure it in <strong>struts-config.xml</strong> file. For this add following code in your struts-config.xml file.</p><pre class="brush: xml; title: ; notranslate">
&lt;!-- Validator Configuration --&gt;
&lt;plug-in className=&quot;org.apache.struts.validator.ValidatorPlugIn&quot;&gt;
	&lt;set-property property=&quot;pathnames&quot;
		value=&quot;/WEB-INF/validator-rules.xml,
				/WEB-INF/validation.xml&quot; /&gt;
&lt;/plug-in&gt;
</pre><p>This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property. Each config file&#8217;s path should be specified by use of a Web application-relative path, as shown in the previous example.</p><h2>Define validations for the form</h2><p><img src="http://img.viralpatel.net/validation-xml-file-struts-validator-framework.png" alt="validation.xml file struts validator framework" title="validation-xml-file-struts-validator-framework" width="166" height="151" class="aligncenter size-full wp-image-687" /></p><p>Create a file validation.xml in your applications WEB-INF directory. And copy following content in it.</p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
&lt;!DOCTYPE form-validation PUBLIC
          &quot;-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN&quot;
          &quot;http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd&quot;&gt;
&lt;form-validation&gt;
&lt;global&gt;
	&lt;constant&gt;
	&lt;constant-name&gt;telephoneFormat&lt;/constant-name&gt;
	&lt;constant-value&gt;^\d{5,10}$&lt;/constant-value&gt;
	&lt;/constant&gt;
&lt;/global&gt;
&lt;formset&gt;
	&lt;form name=&quot;CustomerForm&quot;&gt;
		&lt;field property=&quot;name&quot; depends=&quot;required&quot;&gt;
			&lt;arg key=&quot;label.name&quot; /&gt;
		&lt;/field&gt;
		&lt;field property=&quot;age&quot; depends=&quot;required, integer, intRange&quot;&gt;
			&lt;arg0 key=&quot;label.age&quot; /&gt;
			&lt;arg1 key=&quot;${var:min}&quot; resource=&quot;false&quot;/&gt;
			&lt;arg2 key=&quot;${var:max}&quot; resource=&quot;false&quot;/&gt;
			&lt;var&gt;
				&lt;var-name&gt;min&lt;/var-name&gt;
				&lt;var-value&gt;1&lt;/var-value&gt;
			&lt;/var&gt;
			&lt;var&gt;
				&lt;var-name&gt;max&lt;/var-name&gt;
				&lt;var-value&gt;125&lt;/var-value&gt;
			&lt;/var&gt;
		&lt;/field&gt;
		&lt;field property=&quot;telephone&quot; depends=&quot;required, mask&quot;&gt;
			&lt;arg key=&quot;label.telephone&quot; /&gt;
			&lt;arg1 key=&quot;label.telephone&quot; /&gt;
			&lt;var&gt;
				&lt;var-name&gt;mask&lt;/var-name&gt;
				&lt;var-value&gt;${telephoneFormat}&lt;/var-value&gt;
			&lt;/var&gt;
		&lt;/field&gt;
		&lt;field property=&quot;email&quot; depends=&quot;email&quot;&gt;
			&lt;arg0 key=&quot;label.email&quot; /&gt;
			&lt;arg1 key=&quot;label.email&quot; /&gt;
		&lt;/field&gt;
	&lt;/form&gt;
&lt;/formset&gt;
&lt;/form-validation&gt;
</pre><p>In the above xml file, we have defined the rules for form validation. Note that we are validating form CustomerForm and the fields being validated are name, age, telephone and email. &lt;field&gt; tag defines the validation for a property of form. We can specify different rules like required, integer, email, intRange, mask etc in depends attribute of field tag..</p><p>Also you can define constants that can be reused in the validation xml using global constants tag.</p><h2>Struts-config.xml entry for the action</h2><p>Following is the entry in struts-config.xml file which maps the Action to our Validator form.</p><pre class="brush: xml; title: ; notranslate">
&lt;form-beans&gt;
	&lt;form-bean name=&quot;CustomerForm&quot;
		type=&quot;net.viralpatel.struts.validation.form.CustomerForm&quot; /&gt;
&lt;/form-beans&gt;
...
...
...
&lt;action-mappings&gt;
...
	&lt;action path=&quot;/customer&quot; name=&quot;CustomerForm&quot; validate=&quot;true&quot;
		input=&quot;/index.jsp&quot;
		type=&quot;net.viralpatel.struts.validation.action.CustomerAction&quot;&gt;
		&lt;forward name=&quot;success&quot; path=&quot;/Customer.jsp&quot; /&gt;
		&lt;forward name=&quot;failure&quot; path=&quot;/index.jsp&quot; /&gt;
	&lt;/action&gt;
...
&lt;/action-mappings&gt;
</pre><h2>Configuring ApplicationResources.properties</h2><p>Struts validation framework uses externalization of the error messages. The messages are stored in a property file (ApplicationResource.properties) and are referred by the key values. Copy following in your ApplicationResource.properties (or MessageResource.properties).</p><pre class="brush: xml; title: ; notranslate">
label.name= Name
label.email= Email
label.telephone= Telephone
label.age= Age

# general error msgs
errors.header=&lt;font size=&quot;2&quot;&gt;&lt;UL&gt;
errors.prefix=&lt;LI&gt;&lt;span style=&quot;color: red&quot;&gt;
errors.suffix=&lt;/span&gt;&lt;/LI&gt;
errors.footer=&lt;/UL&gt;&lt;/font&gt;
errors.invalid={0} is invalid.
errors.maxlength={0} can not be greater than {1} characters.
errors.minlength={0} can not be less than {1} characters.
errors.range={0} is not in the range {1} through {2}.
errors.required={0} is required.
errors.byte={0} must be an byte.
errors.date={0} is not a date.
errors.double={0} must be an double.
errors.float={0} must be an float.
errors.integer={0} must be an integer.
errors.long={0} must be an long.
errors.short={0} must be an short.
</pre><h2>Create JSP to display the form</h2><p>Create a JSP file called <code>index.jsp</code> and copy following content in it.</p><pre class="brush: xml; title: ; notranslate">
&lt;%@ taglib uri=&quot;http://struts.apache.org/tags-html&quot; prefix=&quot;html&quot;%&gt;
&lt;%@ taglib uri=&quot;http://struts.apache.org/tags-bean&quot; prefix=&quot;bean&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Struts Validation Framework example.&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;html:errors /&gt;
&lt;html:javascript formName=&quot;CustomerForm&quot; /&gt;

&lt;html:form action=&quot;/customer&quot;&gt;

	&lt;bean:message key=&quot;label.name&quot; /&gt;
	&lt;html:text property=&quot;name&quot;&gt;&lt;/html:text&gt;
	&lt;br /&gt;
	&lt;bean:message key=&quot;label.age&quot; /&gt;
	&lt;html:text property=&quot;age&quot;&gt;&lt;/html:text&gt;
	&lt;br /&gt;
	&lt;bean:message key=&quot;label.email&quot; /&gt;
	&lt;html:text property=&quot;email&quot;&gt;&lt;/html:text&gt;
	&lt;br /&gt;
	&lt;bean:message key=&quot;label.telephone&quot; /&gt;
	&lt;html:text property=&quot;telephone&quot;&gt;&lt;/html:text&gt;
	&lt;br /&gt;

	&lt;html:submit value=&quot;Submit&quot;&gt;&lt;/html:submit&gt;

&lt;/html:form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><h2>Running the application</h2><p>We are done with our application. Now execute it from any web container (Tomcat in my case) and open in browser.<br /> <img src="http://img.viralpatel.net/struts-validator-form-screen1.png" alt="struts validator form screen" title="struts-validator-form-screen1" width="500" height="298" class="aligncenter size-full wp-image-688" /></p><p>Enter any invalid value in the form and press submit.</p><p><img src="http://img.viralpatel.net/struts-validator-form-screen2.png" alt="struts-validator-form-screen2" title="struts-validator-form-screen2" width="500" height="298" class="aligncenter size-full wp-image-689" /></p><p>Post your comments / doubts on this tutorial.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</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/02/javaserver-faces-jsf-validation-tutorial-error-handling-jsf-validator.html" title="JavaServer Faces JSF Validation Tutorial: Error Handling in JSF">JavaServer Faces JSF Validation Tutorial: Error Handling in JSF</a></li><li><a href="http://viralpatel.net/blogs/2009/02/tutorial-creating-javaserver-faces-jsf-application-in-eclipse-jsf-project-jsf-tutorial.html" title="Tutorial: Creating JavaServer Faces JSF application in Eclipse">Tutorial: Creating JavaServer Faces JSF application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2009/01/struts-dispatch-action-tutorial-with-example-in-eclipse.html" title="Struts DispatchAction Tutorial with Example in Eclipse.">Struts DispatchAction Tutorial with Example in Eclipse.</a></li><li><a href="http://viralpatel.net/blogs/2008/12/tutorial-struts-file-upload-example.html" title="Tutorial: Struts File Upload Example.">Tutorial: Struts File Upload Example.</a></li><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/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></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/01/struts-validation-framework-tutorial-example-validator-struts-validation-form-validation.html/feed</wfw:commentRss> <slash:comments>76</slash:comments> </item> <item><title>Struts DispatchAction Tutorial with Example in Eclipse.</title><link>http://viralpatel.net/blogs/2009/01/struts-dispatch-action-tutorial-with-example-in-eclipse.html</link> <comments>http://viralpatel.net/blogs/2009/01/struts-dispatch-action-tutorial-with-example-in-eclipse.html#comments</comments> <pubDate>Fri, 16 Jan 2009 11:00:22 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Struts]]></category> <category><![CDATA[DispatchAction]]></category> <category><![CDATA[struts dispatch action]]></category> <category><![CDATA[Tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=641</guid> <description><![CDATA[Are you bugged of creating separate action classes for some common set of functionality in your Struts application? Feeling pain in managing all those hundreds of Action classes in your project? Don&#8217;t worry, cheers..!! DispatchAction is for you. DispatchAction is one of the Struts built-in action that provides a mechanism that facilitates having a set [...]]]></description> <content:encoded><![CDATA[<p>Are you bugged of creating separate action classes for some common set of functionality in your Struts application? Feeling pain in managing all those hundreds of Action classes in your project? Don&#8217;t worry, cheers..!! DispatchAction is for you.</p><p>DispatchAction is one of the Struts built-in action that provides a mechanism that facilitates having a set of related functionality in a single action instead of creating separate independent actions for each function.</p><p>Let us create a sample example that uses DispatchAction and implement certain functionality of our project. Before that, I assume you have working knowledge of Struts application. If you don&#8217;t, Read this tutorial about <a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html"><strong>A Hello World Struts project</strong></a> and get some basics about Struts application.</p><p>Also, I assume you have already got a Struts application and you want to add Dispatch Action into it. So let us start with our example.</p><h3>Step 1: Create DispatchAction class file.</h3><p>Create an Action class called <strong>UserManagementAction</strong> and extend it with class <strong>org.apache.struts.actions.DispatchAction</strong>. Copy following code into it.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.helloworld.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class UserManagementAction extends DispatchAction {

	public ActionForward create(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		request.setAttribute(&quot;message&quot;, &quot;User created successfully&quot;);

		return mapping.findForward(&quot;success&quot;);
	}

	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		request.setAttribute(&quot;message&quot;, &quot;User deleted successfully&quot;);

		return mapping.findForward(&quot;success&quot;);
	}

	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		request.setAttribute(&quot;message&quot;, &quot;User updated successfully&quot;);

		return mapping.findForward(&quot;success&quot;);
	}

	public ActionForward block(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		request.setAttribute(&quot;message&quot;, &quot;User blocked successfully&quot;);

		return mapping.findForward(&quot;success&quot;);
	}
}
</pre><p>In above code, we have created separate methods (create(), delete(), update() and block()) for each functionality. Also note that the method signature of these methods are exactly similar to the execute() method of Action class file.</p><pre class="brush: java; title: ; notranslate">
public ActionForward delete(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
		throws Exception { }
</pre><h3>Step 2: Create a mapping for action in struts-config.xml file.</h3><p>Open your struts-config.xml and copy following action mapping entry in it.</p><pre class="brush: xml; title: ; notranslate">
&lt;action path=&quot;/user&quot; parameter=&quot;parameter&quot;
	type=&quot;net.viralpatel.struts.helloworld.action.UserManagementAction&quot;&gt;
	&lt;forward name=&quot;success&quot; path=&quot;/UserSuccess.jsp&quot; /&gt;
	&lt;forward name=&quot;failure&quot; path=&quot;/UserSuccess.jsp&quot; /&gt;
&lt;/action&gt;
</pre><p>We have added an extra attribute in &lt;action&gt; tag, <strong>parameter=&#8221;parameter&#8221;</strong>. DispatchAction will read a request parameter called &#8220;parameter&#8221; and its value will decide the method to be called. Suppose you have a request parameter &#8220;parameter&#8221; with value &#8220;create&#8221;, Dispatch Action will call create() method from your Action file.</p><h3>Step 3: Create JSPs for viewing the application.</h3><p>Create two JSP files UserManagement.jsp and UserSuccess.jsp and copy following code into it. UserManagement.jsp will display a menu for selecting action to be taken. UserSuccess.jsp will just print the appropriate action taken by the Action class.</p><h4>UserManagement.jsp</h4><pre class="brush: xml; title: ; notranslate">
&lt;%@taglib uri=&quot;http://jakarta.apache.org/struts/tags-html&quot; prefix=&quot;html&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;Dispatch Action Example - viralpatel.net&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h2&gt;User Management (Dispatch Action Example)&lt;/h2&gt;

	&lt;html:link href=&quot;user.do?parameter=create&quot;&gt;Create User&lt;/html:link&gt;
	 |
	&lt;html:link href=&quot;user.do?parameter=delete&quot;&gt;Delete User&lt;/html:link&gt;
	 |
	&lt;html:link href=&quot;user.do?parameter=update&quot;&gt;Update User&lt;/html:link&gt;
	 |
	&lt;html:link href=&quot;user.do?parameter=block&quot;&gt;Block User&lt;/html:link&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre><h4>UserSuccess.jsp</h4><pre class="brush: xml; title: ; notranslate">
&lt;%@taglib uri=&quot;http://jakarta.apache.org/struts/tags-html&quot; prefix=&quot;html&quot;%&gt;
&lt;html&gt;
&lt;head&gt;
	&lt;title&gt;Dispatch Action Example - viralpatel.net&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;h3&gt;User Message (Dispatch Action Example)&lt;/h3&gt;
	&lt;center&gt;
	&lt;font color=&quot;blue&quot;&gt;&lt;h3&gt;&lt;%= request.getAttribute(&quot;message&quot;) %&gt;&lt;/h3&gt;&lt;/font&gt;
	&lt;center&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre><p>In UserManagement.jsp, we have created links using &lt;html:link&gt; tag and passed a parameter &#8220;parameter&#8221; with values create, delete, block etc. This value is fetched by the Dispatch Action and is used to call corresponding method in Action class. Thus if we click <strong>Update User</strong> link, a parameter <strong>update</strong> will be passed to the action class and corresponding update() method will be called by framework.</p><h3>Step 4: Run the application.</h3><p>Compile and Run the project using Eclipse or Ant and open UserManagement.jsp file in your favorite browser.<br /> <img src="http://img.viralpatel.net/struts-dispatchaction-example-user-management.png" alt="Struts Dispatch Action Example Tutorial" title="struts-dispatchaction-example-user-management" width="500" height="238" class="aligncenter size-full wp-image-643" /></p><p>Click the link <strong>Create User</strong> or <strong>Delete User</strong> etc. and see the output.</p><p><img src="http://img.viralpatel.net/struts-dispatchaction-example-create.png" alt="struts-dispatchaction-example-create" title="struts-dispatchaction-example-create" width="480" height="192" class="aligncenter size-full wp-image-644" /></p><p><img src="http://img.viralpatel.net/struts-dispatchaction-example-delete.png" alt="struts-dispatchaction-example-delete" title="struts-dispatchaction-example-delete" width="480" height="192" class="aligncenter size-full wp-image-645" /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><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><li><a href="http://viralpatel.net/blogs/2008/12/tutorial-struts-file-upload-example.html" title="Tutorial: Struts File Upload Example.">Tutorial: Struts File Upload Example.</a></li><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/2008/12/tutorial-creating-struts-application-in-eclipse.html" title="Tutorial: Creating Struts application in Eclipse">Tutorial: Creating Struts application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2008/11/struts-internationalization-i18n.html" title="Struts Internationalization (I18N)">Struts Internationalization (I18N)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/01/spring-roo-implement-masterdetail-forms.html" title="How to implement Master/Detail forms using Spring Roo">How to implement Master/Detail forms using Spring Roo</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2009/01/struts-dispatch-action-tutorial-with-example-in-eclipse.html/feed</wfw:commentRss> <slash:comments>16</slash:comments> </item> <item><title>Tutorial: Struts File Upload Example.</title><link>http://viralpatel.net/blogs/2008/12/tutorial-struts-file-upload-example.html</link> <comments>http://viralpatel.net/blogs/2008/12/tutorial-struts-file-upload-example.html#comments</comments> <pubDate>Mon, 22 Dec 2008 09:21:08 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Struts]]></category> <category><![CDATA[struts file upload]]></category> <category><![CDATA[Tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=513</guid> <description><![CDATA[Let us see how we can implement file upload functionality using Apache Struts Framework. I assume you have basic knowledge about Struts and know the flow of a struts application. If you are new to struts, I suggest you to check this tutorial first: Struts Project in Eclipse. First let us download all the required [...]]]></description> <content:encoded><![CDATA[<p>Let us see how we can implement file upload functionality using Apache Struts Framework. I assume you have basic knowledge about Struts and know the flow of a struts application. If you are new to struts, I suggest you to check this tutorial first: <a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html"><strong>Struts Project in Eclipse</strong></a>.</p><p>First let us download all the required JAR files to implement file upload functionality. For this we will need common-fileupload.jar file that comes with common package of Struts.<br /> Download <a href="http://viralpatel.net/blogs/download/struts/commons-fileupload.jar"><strong>common-fileupload.jar</strong></a> (version 1.0, size 20 kb).</p><p>Include this JAR file in your class path variable.</p><p>Now, modify the ActionForm class where you want to add File upload functionality and add following property and its getter and setter methods.</p><pre class="brush: java; title: ; notranslate">
import org.apache.struts.upload.FormFile;
....
....
	private FormFile file;

	public FormFile getFile() {
		return file;
	}

	public void setFile(FormFile file) {
		this.file = file;
	}
....
....
</pre><p>In the above code snippet, we have added an attribute file which is of type org.apache.struts.upload.FormFile. This property will contain file content and other file related information that is being upload from form.</p><p>Now add following code in your JSP page to add a file upload input.</p><pre class="brush: xml; title: ; notranslate">
&lt;html:form action=&quot;/file-upload&quot; method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;
....
....
	&lt;html:file property=&quot;file&quot;&gt;&lt;/html:file&gt;
....
....
&lt;/html:form&gt;
</pre><p>Note that in above code we added method=&#8221;post&#8221; and enctype=&#8221;multipart/form-data&#8221; to the form. Also the name of property is same as what we mentioned in ActionForm class.</p><p>Now in the action file where you normally deal with form data, add following code to get information about the file being submitted.</p><pre class="brush: java; title: ; notranslate">
//Type cast form to FileUploadForm.
FileUploadForm fileForm = (FileUploadForm)form;

//Get the FormFile object from ActionForm.
FormFile file = fileForm.getFile();

//Get file name of uploaded file.
String fileName = file.getFileName();

//Get file size of uploaded file.
Integer fileSize = file.getFileSize();

//The content type of the uploaded file.
String contentType = file.getContentType();

// Get InputStream object of uploaded File.
InputStream inputFile = file.getInputStream();
</pre><p>Once you get InputStream object, you can use normal file I/O to write the file anywhere on server.</p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><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><li><a href="http://viralpatel.net/blogs/2009/01/struts-dispatch-action-tutorial-with-example-in-eclipse.html" title="Struts DispatchAction Tutorial with Example in Eclipse.">Struts DispatchAction Tutorial with Example in Eclipse.</a></li><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/2008/12/tutorial-creating-struts-application-in-eclipse.html" title="Tutorial: Creating Struts application in Eclipse">Tutorial: Creating Struts application in Eclipse</a></li><li><a href="http://viralpatel.net/blogs/2008/11/struts-internationalization-i18n.html" title="Struts Internationalization (I18N)">Struts Internationalization (I18N)</a></li><li><a href="http://viralpatel.net/blogs/2011/11/hibernate-hello-world-example-annotation.html" title="Hibernate Hello World example using Annotation">Hibernate Hello World example using Annotation</a></li><li><a href="http://viralpatel.net/blogs/2011/01/spring-roo-implement-masterdetail-forms.html" title="How to implement Master/Detail forms using Spring Roo">How to implement Master/Detail forms using Spring Roo</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/tutorial-struts-file-upload-example.html/feed</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Tutorial:Struts Spring framework example in Eclipse.</title><link>http://viralpatel.net/blogs/2008/12/tutorial-struts-spring-framework-example-in-eclipse.html</link> <comments>http://viralpatel.net/blogs/2008/12/tutorial-struts-spring-framework-example-in-eclipse.html#comments</comments> <pubDate>Tue, 16 Dec 2008 10:27:13 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Spring]]></category> <category><![CDATA[Struts]]></category> <category><![CDATA[application-context]]></category> <category><![CDATA[JavaEE]]></category> <category><![CDATA[spring injection]]></category> <category><![CDATA[spring ioc]]></category> <category><![CDATA[Tutorial]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=463</guid> <description><![CDATA[Let us see how to add Spring support (Spring IOC) to a Struts application using Eclipse IDE. I will use the hello world struts project that we created in this tutorial as base reference and step by step we will add Spring support to it. In this tutorial we will use Spring IOC (Inversion Of [...]]]></description> <content:encoded><![CDATA[<p>Let us see how to add Spring support (Spring IOC) to a Struts application using Eclipse IDE. I will use the hello world struts project that we created in <a target="_new" href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html"><strong>this tutorial</strong></a> as base reference and step by step we will add Spring support to it.</p><p>In this tutorial we will use Spring IOC (Inversion Of Control) mechanism. There will be a business delegate class that will be used to authenticate user. In Login class we will inject this BusinessDelegate class using Spring Injection. Let us start with tutorial.</p><p>First, Download required JAR file required for setting Spring support to our Struts application. For this we will need Spring.jar.<br /> Download it from <a href="/blogs/download/spring/spring.jar"><strong>here</strong></a> (Spring.jar, version 1.1, 985kb).<br /> You can download latest JAR file from Spring frameworks <a href="http://www.springsource.org/download" rel="nofollow" target="_new">download page.</a></p><p>Copy spring.jar file in WEB-INF/lib folder of our struts project.<br /> <img src="http://img.viralpatel.net/2008/12/spring-jar-in-web-inf-direcotry.png" alt="" title="spring-jar-in-web-inf-direcotry" width="185" height="116" class="alignnone size-full wp-image-464" /></p><p>Now open your struts-config.xml from WEB-INF folder and add following entry for plugin in it. This will add Spring support to your struts project.</p><pre class="brush: xml; title: ; notranslate">
&lt;plug-in className=&quot;org.springframework.web.struts.ContextLoaderPlugIn&quot;&gt;
             &lt;set-property property=&quot;contextConfigLocation&quot;
             	value=&quot;/WEB-INF/ApplicationContext.xml&quot;/&gt;
&lt;/plug-in&gt;
</pre><p>Create an xml file called <strong>ApplicationContext.xml</strong> in WEB-INF directory.<br /> <img src="http://img.viralpatel.net/2008/12/spring-application-context-xml-in-web-inf.png" alt="" title="spring-application-context-xml-in-web-inf" width="175" height="99" class="alignnone size-full wp-image-465" /></p><p>Copy following content in ApplicationContext.xml file.</p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE beans PUBLIC &quot;-//SPRING//DTD BEAN//EN&quot; &quot;http://www.springframework.org/dtd/spring-beans.dtd&quot;&gt;

&lt;beans&gt;
	&lt;!-- Business Objects --&gt;
	&lt;bean id=&quot;businessDelegate&quot;
			class=&quot;net.viralpatel.struts.helloworld.business.BusinessDelegate&quot;&gt;
	&lt;/bean&gt;

	&lt;!-- Actions Classes --&gt;
	&lt;bean name=&quot;/login&quot; class=&quot;net.viralpatel.struts.helloworld.action.LoginAction&quot;&gt;
		&lt;property name=&quot;businessDelegate&quot;&gt;&lt;ref local=&quot;businessDelegate&quot;/&gt;&lt;/property&gt;
	&lt;/bean&gt;
&lt;/beans&gt;
</pre><p>Note that in this example we are using Spring framework to instantiate an object of BusinessDelegate class as well as LoginAction class and injecting this object of BusinnessDelegate in LoginAction.<br /> So create a package net.viralpatel.struts.helloworld.business and create a java file BusinessDelegate.java in it.<br /> <img src="http://img.viralpatel.net/2008/12/struts-spring-example-business-delegate.png" alt="" title="struts-spring-example-business-delegate" width="250" height="83" class="alignnone size-full wp-image-466" /></p><p>Copy following code for login validation in BusinessDelegate class.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.helloworld.business;

public class BusinessDelegate {

	public String validateUser(String userName, String password) {
		if(userName.equals(&quot;admin&quot;) &amp;&amp; password.equals(&quot;123&quot;)) {
			return &quot;success&quot;;
		}

		return &quot;failure&quot;;
	}
}
</pre><p>Also add a property for BusinessDelegate class in LoginAction and its getter and setter method. This property will get injected by Spring. Copy/Paste following code in your LoginAction.java file.</p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.helloworld.action;

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

import net.viralpatel.struts.helloworld.business.BusinessDelegate;
import net.viralpatel.struts.helloworld.form.LoginForm;

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

public class LoginAction extends Action {

	private BusinessDelegate businessDelegate;

	public BusinessDelegate getBusinessDeletage() {
		return businessDelegate;
	}

	public void setBusinessDelegate(BusinessDelegate businessDeletage) {
		this.businessDelegate = businessDeletage;
	}

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String target = null;
		LoginForm loginForm = (LoginForm)form; 

		target = businessDelegate.validateUser(loginForm.getUserName(),
												loginForm.getPassword());

		return mapping.findForward(target);
	}
}
</pre><p>Note that LoginAction class is also instantiate using Spring. Hence we will modify <action> entry in struts-config.xml.</p><pre class="brush: xml; title: ; notranslate">
	&lt;action-mappings&gt;
		&lt;action path=&quot;/login&quot; name=&quot;LoginForm&quot; validate=&quot;true&quot;
			input=&quot;/index.jsp&quot;
			type=&quot;org.springframework.web.struts.DelegatingActionProxy&quot;&gt;
			&lt;forward name=&quot;success&quot; path=&quot;/welcome.jsp&quot; /&gt;
			&lt;forward name=&quot;failure&quot; path=&quot;/index.jsp&quot; /&gt;
		&lt;/action&gt;
	&lt;/action-mappings&gt;
</pre><p>In type attribute, instead of LoginAction, we have used org.springframework.web.struts.DelegatingActionProxy. This is spring framework class that will delegate the call to action to specific class in ApplicationContext.xml file. Note that path=&#8221;/login&#8221; should match to name=&#8221;/login&#8221; entry that we made in ApplicationContext.xml file.</p><p>And that&#8217;s it. We have just implemented Spring support to our struts application.</p><p>You can download war file of struts-spring application with full source here. <a href="/blogs/download/spring/Struts-Spring-HelloWorld.war"><strong>SOURCE CODE</strong></a></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2205/change-spring-servlet-filename-configuration" title="Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)">Change spring-servlet.xml Filename (Spring Web Contenxt Configuration Filename)</a></li><li><a href="http://viralpatel.net/blogs/2011/01/spring-roo-implement-masterdetail-forms.html" title="How to implement Master/Detail forms using Spring Roo">How to implement Master/Detail forms using Spring Roo</a></li><li><a href="http://viralpatel.net/blogs/2010/06/tutorial-spring-3-mvc-introduction-spring-mvc-framework.html" title="Spring 3 MVC – Introduction to Spring 3 MVC Framework">Spring 3 MVC – Introduction to Spring 3 MVC Framework</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><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><li><a href="http://viralpatel.net/blogs/2009/01/struts-dispatch-action-tutorial-with-example-in-eclipse.html" title="Struts DispatchAction Tutorial with Example in Eclipse.">Struts DispatchAction Tutorial with Example in Eclipse.</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></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/tutorial-struts-spring-framework-example-in-eclipse.html/feed</wfw:commentRss> <slash:comments>16</slash:comments> </item> <item><title>Tutorial: Struts Tiles plugin example in Eclipse</title><link>http://viralpatel.net/blogs/2008/12/tutorial-struts-tiles-plugin-example-in-eclipse.html</link> <comments>http://viralpatel.net/blogs/2008/12/tutorial-struts-tiles-plugin-example-in-eclipse.html#comments</comments> <pubDate>Mon, 08 Dec 2008 07:08:42 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Struts]]></category> <category><![CDATA[struts-plugin]]></category> <category><![CDATA[tiles]]></category> <category><![CDATA[tiles-plugin]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=349</guid> <description><![CDATA[In the previous tutorials about Creating Struts application in Eclipse, we saw step by step how we can create a Struts project. In this tutorial we will explore Tiles plugin in struts. Introduction of Tiles Plugin Nowadays, website are generally divided into pieces of reusable template that are being rendered among different web pages. For [...]]]></description> <content:encoded><![CDATA[<p>In the previous tutorials about <a href="http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html">Creating Struts application in Eclipse</a>, we saw step by step how we can create a Struts project. In this tutorial we will explore <strong>Tiles plugin</strong> in struts.</p><h2>Introduction of Tiles Plugin</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 “Tile”) 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.</p><h2>Installing Tiles</h2><p>The Tiles installation process depends on the Struts version you use. If you start a new project,<br /> use the latest Struts version. Tiles can also be used without Struts.</p><p>Add following entry of plug-in tag to your struts-config.xml in order to configure Tiles.</p><pre class="brush: xml; title: ; notranslate">
&lt;plug-in className=&quot;org.apache.struts.tiles.TilesPlugin&quot;&gt;
	&lt;set-property property=&quot;definitions-config&quot;
		value=&quot;/WEB-INF/tiles-definitions.xml&quot; /&gt;
	&lt;set-property property=&quot;moduleAware&quot; value=&quot;true&quot; /&gt;
&lt;/plug-in&gt;
</pre><p>In this entry you can see definitions-config parameter which is set to the value <strong>/WEB-INF/tiles-definitions.xml</strong>. So we have to create a file called tiles-definitions.xml in WEB-INF directory.<br /> <img src="http://img.viralpatel.net/2008/12/creating-tiles-definition.png" alt="" title="creating-tiles-definition" width="215" height="188" class="alignnone size-full wp-image-351" /></p><h2>Creating Application</h2><p>We will create a Header and a Footer that we will integrate with our sturts application. We will render this header and footer using Tiles.<br /> Create two JSPs, Header.jsp and Footer.jsp and copy following content in it.</p><p><strong>Header.jsp</strong></p><pre class="brush: xml; title: ; notranslate">
&lt;div style=&quot;width: 100%; height: 200px; background-color: #ABBAF3&quot;&gt;
	&lt;h3&gt;Tiles Plugin Example using Struts &amp;amp;amp;amp;amp; Eclipse&lt;/h3&gt;
&lt;/div&gt;
</pre><p><strong>Footer.jsp</strong></p><pre class="brush: xml; title: ; notranslate">
&lt;div style=&quot;width: 100%; height: 50px; background-color: #ABBAF3&quot;&gt;
	Copyright &amp;amp;amp;amp;amp;copy viralpatel.net
&lt;/div&gt;
</pre><p>Also, create a Layout.jsp file in your WebContent folder and copy following code in it.</p><pre class="brush: xml; title: ; notranslate">
&lt;%@ page contentType=&quot;text/html;charset=UTF-8&quot; language=&quot;java&quot;%&gt;
&lt;%@ taglib uri=&quot;http://jakarta.apache.org/struts/tags-html&quot; prefix=&quot;html&quot;%&gt;
&lt;%@ taglib uri=&quot;http://jakarta.apache.org/struts/tags-tiles&quot; prefix=&quot;tiles&quot;%&gt;
&lt;tiles:importAttribute /&gt;
&lt;HTML&gt;
&lt;HEAD&gt;
		&lt;TITLE&gt;&lt;tiles:getAsString name=&quot;title&quot; /&gt;&lt;/TITLE&gt;
&lt;/HEAD&gt;
&lt;BODY&gt;
&lt;TABLE width=&quot;100%&quot; height=&quot;100%&quot; border=&quot;0&quot;&gt;
	&lt;TR&gt;
		&lt;TD valign=&quot;top&quot; height=&quot;10px&quot;&gt;
			&lt;tiles:insert name=&quot;header&quot; attribute=&quot;header&quot; /&gt;
		&lt;/TD&gt;
	&lt;/TR&gt;
	&lt;TR&gt;
		&lt;TD  valign=&quot;middle&quot; align=&quot;center&quot;&gt;
			&lt;tiles:insert name=&quot;body&quot; attribute=&quot;body&quot; /&gt;
		&lt;/TD&gt;
	&lt;/TR&gt;
	&lt;TR&gt;
		&lt;TD height=&quot;10px&quot;&gt;
			&lt;tiles:insert name=&quot;footer&quot; attribute=&quot;footer&quot; /&gt;
		&lt;/TD&gt;
	&lt;/TR&gt;
&lt;/TABLE&gt;
&lt;/BODY&gt;
&lt;/HTML&gt;
</pre><p>Layout.jsp file will define overall layout of web page. I have used a table based layout here. You can use a DIV based layout and align all the components using CSS.<br /> Note that we have used a tag <code>&lt;tile:insert&gt;</code> in order to place the respective elements on this page. This will be more clear once you create tiles-definitions.xml file.</p><p>Now copy following code in tiles-plugins.xml file.</p><pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot; ?&gt;
&lt;!DOCTYPE tiles-definitions PUBLIC
       &quot;-//Apache Software Foundation//DTD Tiles Configuration 1.3//EN&quot;
       &quot;http://struts.apache.org/dtds/tiles-config_1_3.dtd&quot;&gt;

&lt;tiles-definitions&gt;
	&lt;definition name=&quot;layout&quot; page=&quot;/Layout.jsp&quot;&gt;
		&lt;put name=&quot;header&quot; value=&quot;/Header.jsp&quot; /&gt;
		&lt;put name=&quot;body&quot; value=&quot;&quot; /&gt;
		&lt;put name=&quot;footer&quot; value=&quot;/Footer.jsp&quot; /&gt;
	&lt;/definition&gt;

	&lt;definition name=&quot;/tiles.home&quot; extends=&quot;layout&quot;&gt;
		&lt;put name=&quot;title&quot; value=&quot;Welcome: Tiles Plugin Sturts Tutorial&quot; /&gt;
		&lt;put name=&quot;body&quot; value=&quot;/wome.jsp&quot; /&gt;
	&lt;/definition&gt;
&lt;/tiles-definitions&gt;
</pre><p>Here we have replace names like title, body, header, footer etc with the content of the JSPs. Hence tiles will replace the tag <code>&lt;tile:insert&gt;</code> with appropriate content in Layout.jsp.</p><p><img src="http://img.viralpatel.net/2008/12/struts-tiles-examples-screen.png" alt="" title="struts-tiles-examples-screen" width="500" height="357" class="alignnone size-full wp-image-352" /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><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/07/spring-3-mvc-tiles-plugin-tutorial-example-eclipse.html" title="Spring 3 MVC: Tiles Plugin Tutorial with Example in Eclipse">Spring 3 MVC: Tiles Plugin Tutorial with Example in Eclipse</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><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/2009/06/struts-displaytag-tutorial-sort-pagination-data-displaytag-struts.html" title="Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts">Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts</a></li></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/tutorial-struts-tiles-plugin-example-in-eclipse.html/feed</wfw:commentRss> <slash:comments>12</slash:comments> </item> <item><title>Tutorial: Creating Struts application in Eclipse</title><link>http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html</link> <comments>http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html#comments</comments> <pubDate>Thu, 04 Dec 2008 13:35:47 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Featured]]></category> <category><![CDATA[Struts]]></category> <category><![CDATA[framework]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Tutorial]]></category> <category><![CDATA[webapp]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=293</guid> <description><![CDATA[Note: If you looking for tutorial &#8220;Create Struts2 Application in Eclipse&#8221; Click here. In this tutorial we will create a hello world Struts application in Eclipse editor. First let us see what are the tools required to create our hello world Struts application. JDK 1.5 above (download) Tomcat 5.x above or any other container (Glassfish, [...]]]></description> <content:encoded><![CDATA[<p>Note: If you looking for tutorial &#8220;<strong>Create Struts2 Application in Eclipse</strong>&#8221; <a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example">Click here.</a><br /> In this tutorial we will create a hello world Struts application in Eclipse editor. First let us see what are the tools required to create our hello world Struts application.</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 Struts JAR files:(<a rel="nofollow" href="http://struts.apache.org/1.2.7/userGuide/installation.html" target="_new">download</a>). Following are the list of JAR files required for this application.<ul><li>struts.jar</li><li>common-logging.jar</li><li>common-beanutils.jar</li><li>common-collections.jar</li><li>common-digester.jar</li></ul></li></ol><p>We will implement a web application using Struts framework which will have a login screen. Once the user is authenticated, (s)he will be redirected to a welcome page.</p><p>Let us start with our first struts based web application.</p><p>Open Eclipse and goto File -&gt; New -&gt; Project and select <strong>Dynamic Web Project</strong> in the New Project wizard screen.</p><p><a href="http://img.viralpatel.net/2008/12/eclipse-new-project-struts-example.png"><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="" width="369" height="365" /></a></p><p>After selecting Dynamic Web Project, press <strong>Next</strong>.</p><p><a href="http://img.viralpatel.net/2008/12/eclipse-new-dynamic-web-project-struts.png"><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="" width="471" height="511" /></a></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.</p><p><a href="http://img.viralpatel.net/2008/12/new-struts-application-created.png"><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="" width="500" height="458" /></a></p><p>Now copy all the required JAR files in WebContent -&gt; WEB-INF -&gt; <strong>lib </strong>folder. Create this folder if it does not exists.<br /> <br /> <a href="http://img.viralpatel.net/2008/12/struts-jar-in-lib-folder.png"><img class="alignnone size-full wp-image-298" title="struts-jar-in-lib-folder" src="http://img.viralpatel.net/2008/12/struts-jar-in-lib-folder.png" alt="" width="222" height="137" /></a></p><p>Next step is to create a servlet entry in web.xml which points to <strong>org.apache.struts.action.ActionServlet</strong> class of struts framework. Open web.xml file which is there under WEB-INF folder and copy paste following code.</p><pre class="brush: xml; title: ; notranslate">&lt;servlet&gt;
		&lt;servlet-name&gt;action&lt;/servlet-name&gt;
		&lt;servlet-class&gt;
			org.apache.struts.action.ActionServlet
		&lt;/servlet-class&gt;
		&lt;init-param&gt;
			&lt;param-name&gt;config&lt;/param-name&gt;
			&lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt;
		&lt;/init-param&gt;
		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
&lt;/servlet&gt;
&lt;servlet-mapping&gt;
	&lt;servlet-name&gt;action&lt;/servlet-name&gt;
	&lt;url-pattern&gt;*.do&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre><p><a href="http://img.viralpatel.net/2008/12/struts-actionservlet-entry-in-web-xml.png"><img class="alignnone size-full wp-image-299" title="struts-actionservlet-entry-in-web-xml" src="http://img.viralpatel.net/2008/12/struts-actionservlet-entry-in-web-xml.png" alt="" width="500" height="308" /></a></p><p>Here we have mapped url *.do with the ActionServlet, hence all the requests from *.do url will be routed to ActionServlet; which will handle the flow of Struts after that.</p><p>We will create package strutcures for your project source. Here we will create two packages, one for Action classes (net.viralpatel.struts.helloworld.action) and other for Form  beans(net.viralpatel.struts.helloworld.action).</p><p><a href="http://img.viralpatel.net/2008/12/package-structure-in-struts-hello-world.png"><img class="alignnone size-full wp-image-301" title="package-structure-in-struts-hello-world" src="http://img.viralpatel.net/2008/12/package-structure-in-struts-hello-world.png" alt="" width="289" height="86" /></a></p><p>Also create a class <strong>LoginForm</strong> in net.viralpatel.struts.helloworld.action with following content.<br /></p><pre class="brush: java; title: ; notranslate">
package net.viralpatel.struts.helloworld.form;

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

public class LoginForm extends ActionForm {

	private String userName;
	private String password;

	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {

		ActionErrors actionErrors = new ActionErrors();

		if(userName == null || userName.trim().equals(&quot;&quot;)) {
			actionErrors.add(&quot;userName&quot;, new ActionMessage(&quot;error.username&quot;));
		}
		try {
		if(password == null || password.trim().equals(&quot;&quot;)) {
			actionErrors.add(&quot;password&quot;, new ActionMessage(&quot;error.password&quot;));
		}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return actionErrors ;
	}

	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>LoginForm is a bean class which extends ActionForm class of struts framework. This class will have the string properties like userName and password and their getter and setter methods. This class will act as a bean and will help in carrying values too and fro from JSP to Action class.<br /> Let us create an Action class that will handle the request and will process the authentication. Create a class named LoginAction in net.viralpatel.struts.helloworld.action package. Copy paste following code in LoginAction class.</p><pre class="brush: java; title: ; notranslate">package net.viralpatel.struts.helloworld.action;

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

import net.viralpatel.struts.helloworld.form.LoginForm;

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

public class LoginAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String target = null;
		LoginForm loginForm = (LoginForm)form; 

		if(loginForm.getUserName().equals(&quot;admin&quot;)
				&amp;&amp; loginForm.getPassword().equals(&quot;admin123&quot;)) {
			target = &quot;success&quot;;
			request.setAttribute(&quot;message&quot;, loginForm.getPassword());
		}
		else {
			target = &quot;failure&quot;;
		}

		return mapping.findForward(target);
	}
}
</pre><p>In action class, we have a method called <strong>execute()</strong> which will be called by struts framework when this action will gets called. The parameter passed to this method are ActionMapping, ActionForm, HttpServletRequest and HttpServletResponse. In execute() method we check if username equals admin and password is equal to admin123, user will be redirected to Welcome page. If username and password are not proper, then user will be redirected to login page again.</p><p>We will use the internationalization (i18n) support of struts to display text on our pages. Hence we will create a MessagesResources properties file which will contain all our text data. Create a folder <strong>resource</strong> under src (Right click on src and select New -&gt; Source Folder). Now create a text file called MessageResource.properties under resources folder.</p><p><a href="http://img.viralpatel.net/2008/12/message-resource-property-file-in-struts.png"><img class="alignnone size-full wp-image-306" title="message-resource-property-file-in-struts" src="http://img.viralpatel.net/2008/12/message-resource-property-file-in-struts.png" alt="" width="327" height="134" /></a></p><p>Copy the following content in your <strong>Upadate:</strong><span style="text-decoration: line-through;">struts-config.xml</span> MessageResource.properties file.<br /></p><pre class="brush: xml; title: ; notranslate">label.username = Login Detail
label.password = Password
label.welcome = Welcome

error.username =Username is not entered.</pre><p>Create two JSP files, index.jsp and welcome.jsp with the following content in your WebContent folder.</p><p><strong>index.jsp</strong></p><pre class="brush: xml; title: ; notranslate">&lt;%@taglib uri=&quot;http://jakarta.apache.org/struts/tags-html&quot; prefix=&quot;html&quot;%&gt;
&lt;%@taglib uri=&quot;http://jakarta.apache.org/struts/tags-bean&quot; prefix=&quot;bean&quot; %&gt;

&lt;html&gt;
	&lt;head&gt;
		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
		&lt;title&gt;Login page | Hello World Struts application in Eclipse&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
	&lt;h1&gt;Login&lt;/h1&gt;
	&lt;html:form action=&quot;login&quot;&gt;
		 &lt;bean:message key=&quot;label.username&quot; /&gt;
		 &lt;html:text property=&quot;userName&quot;&gt;&lt;/html:text&gt;
		 &lt;html:errors property=&quot;userName&quot; /&gt;
		 &lt;br/&gt;
		 &lt;bean:message key=&quot;label.password&quot;/&gt;
		&lt;html:password property=&quot;password&quot;&gt;&lt;/html:password&gt;
		 &lt;html:errors property=&quot;password&quot;/&gt;
		&lt;html:submit/&gt;
		&lt;html:reset/&gt;
	&lt;/html:form&gt;
	&lt;/body&gt;
&lt;/html&gt;</pre><p><strong>welcome.jsp</strong></p><pre class="brush: xml; title: ; notranslate">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
    pageEncoding=&quot;ISO-8859-1&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=ISO-8859-1&quot;&gt;
		&lt;title&gt;Welcome page | Hello World Struts application in Eclipse&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
	&lt;%
		String message = (String)request.getAttribute(&quot;message&quot;);
	%&gt;
		&lt;h1&gt;Welcome &lt;%= message %&gt;&lt;/h1&gt;

	&lt;/body&gt;
&lt;/html&gt;</pre><p>Now create a file called <strong>struts-config.xml</strong> in WEB-INF folder. Also note that in web.xml file we have passed an argument with name config to ActionServlet class with value /WEB-INF/struts-config.xml.</p><p><a href="http://img.viralpatel.net/2008/12/struts-config-xml-in-web-inf.png"><img class="alignnone size-full wp-image-300" title="struts-config-xml-in-web-inf" src="http://img.viralpatel.net/2008/12/struts-config-xml-in-web-inf.png" alt="" width="173" height="116" /></a></p><p>Following will be the content of struts-config.xml file:</p><pre class="brush: xml; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot; ?&gt;

&lt;!DOCTYPE struts-config PUBLIC
          &quot;-//Apache Software Foundation//DTD Struts Configuration 1.2//EN&quot;
          &quot;http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd&quot;&gt;

&lt;struts-config&gt;
	&lt;form-beans&gt;
		&lt;form-bean name=&quot;LoginForm&quot;
			type=&quot;net.viralpatel.struts.helloworld.form.LoginForm&quot; /&gt;
	&lt;/form-beans&gt;

	&lt;global-exceptions&gt;
	&lt;/global-exceptions&gt;
	&lt;global-forwards&gt;&lt;/global-forwards&gt;

	&lt;action-mappings&gt;
		&lt;action path=&quot;/login&quot; name=&quot;LoginForm&quot; validate=&quot;true&quot; input=&quot;/index.jsp&quot;
			type=&quot;net.viralpatel.struts.helloworld.action.LoginAction&quot;&gt;
			&lt;forward name=&quot;success&quot; path=&quot;/welcome.jsp&quot; /&gt;
			&lt;forward name=&quot;failure&quot; path=&quot;/index.jsp&quot; /&gt;
		&lt;/action&gt;
	&lt;/action-mappings&gt;

	&lt;message-resources parameter=&quot;resource.MessageResource&quot;&gt;&lt;/message-resources&gt;

&lt;/struts-config&gt;</pre><p><br /> And, that&#8217;s it <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .. We are done with our application and now its turn to run it. I hope you have already configured Tomcat in eclipse. If not then:<br /> <a href="http://img.viralpatel.net/2008/12/configuring-tomcat-server-in-eclipse.png"><img src="http://img.viralpatel.net/2008/12/configuring-tomcat-server-in-eclipse.png" alt="" title="configuring-tomcat-server-in-eclipse" width="444" height="341" class="alignnone size-full wp-image-309" /></a><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)<br /> <a href="http://img.viralpatel.net/2008/12/run-struts-web-project-in-eclipse.png"><img src="http://img.viralpatel.net/2008/12/run-struts-web-project-in-eclipse.png" alt="" title="run-struts-web-project-in-eclipse" width="500" height="350" class="alignnone size-full wp-image-310" /></a></p><p><strong>Login Page</strong><br /> <a href="http://img.viralpatel.net/2008/12/login-page-struts-application-eclipse.png"><img src="http://img.viralpatel.net/2008/12/login-page-struts-application-eclipse.png" alt="" title="login-page-struts-application-eclipse" width="383" height="249" class="alignnone size-full wp-image-311" /></a></p><p><strong>Welcome Page</strong><br /> <a href="http://img.viralpatel.net/2008/12/welcome-page-struts-application-eclipse.png"><img src="http://img.viralpatel.net/2008/12/welcome-page-struts-application-eclipse.png" alt="" title="welcome-page-struts-application-eclipse" width="383" height="249" class="alignnone size-full wp-image-312" /></a><br /> <strong>Related:</strong> <strong><a href="http://viralpatel.net/blogs/2009/12/tutorial-create-struts-2-application-eclipse-example.html">Create Struts 2 Application in Eclipse</a></strong><br /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</h2><ul class="related_post"><li><a href="http://viralpatel.net/blogs/2010/06/tutorial-spring-3-mvc-introduction-spring-mvc-framework.html" title="Spring 3 MVC – Introduction to Spring 3 MVC Framework">Spring 3 MVC – Introduction to Spring 3 MVC Framework</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/10/inner-classes-in-java.html" title="Inner classes in Java, the mystery within.">Inner classes in Java, the mystery within.</a></li><li><a href="http://viralpatel.net/blogs/2009/06/restful-web-service-tutorial-introduction-rest-restful.html" title="RESTful Web Service tutorial: An Introduction for beginners">RESTful Web Service tutorial: An Introduction for beginners</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/02/tutorial-creating-javaserver-faces-jsf-application-in-eclipse-jsf-project-jsf-tutorial.html" title="Tutorial: Creating JavaServer Faces JSF application in Eclipse">Tutorial: Creating JavaServer Faces JSF application in Eclipse</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>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/tutorial-creating-struts-application-in-eclipse.html/feed</wfw:commentRss> <slash:comments>215</slash:comments> </item> <item><title>Implementing Clean URL in Struts</title><link>http://viralpatel.net/blogs/2008/12/implementing-clean-url-in-struts.html</link> <comments>http://viralpatel.net/blogs/2008/12/implementing-clean-url-in-struts.html#comments</comments> <pubDate>Tue, 02 Dec 2008 06:35:54 +0000</pubDate> <dc:creator>Viral Patel</dc:creator> <category><![CDATA[Struts]]></category><guid isPermaLink="false">http://viralpatel.net/blogs/?p=268</guid> <description><![CDATA[The web application created by using Struts framework can be easily identified by the URL patterns. Mostly all the Struts application have *.do or *.action URL depending on the version of Struts being used and the best practices that are followed. These URLs are less  search engine friendly as they reveal very little about the [...]]]></description> <content:encoded><![CDATA[<p>The web application created by using Struts framework can be easily identified by the URL patterns. Mostly all the Struts application have <strong>*.do</strong> or <strong>*.action</strong> URL depending on the version of Struts being used and the best practices that are followed.</p><p>These URLs are less  search engine friendly as they reveal very little about the content. Hence it can be useful to implement a web application with clean URLs pattern such as /custormer/add or /profile/william.</p><p>This can be achieved in Struts by modifying Web.xml and struts-config.xml files. Following is the ActionServlet entry that is normally made in Web.xml file in order to configure struts.</p><pre class="brush: xml; title: ; notranslate">
&lt;servlet&gt;
&lt;servlet-name&gt;action&lt;/servlet-name&gt;
&lt;servlet-class&gt;org.apache.struts.action.ActionServlet&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;config&lt;/param-name&gt;
&lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
&lt;param-name&gt;debug&lt;/param-name&gt;
&lt;param-value&gt;2&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
&lt;param-name&gt;detail&lt;/param-name&gt;
&lt;param-value&gt;2&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;load-on-startup&gt;2&lt;/load-on-startup&gt;
&lt;/servlet&gt;

&lt;servlet-mapping&gt;
&lt;servlet-name&gt;action&lt;/servlet-name&gt;
&lt;url-pattern&gt;*.do&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre><p><!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:TrackMoves /> <w:TrackFormatting /> <w:PunctuationKerning /> <w:ValidateAgainstSchemas /> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:DoNotPromoteQF /> <w:LidThemeOther>EN-US</w:LidThemeOther> <w:LidThemeAsian>X-NONE</w:LidThemeAsian> <w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript> <w:Compatibility> <w:BreakWrappedTables /> <w:SnapToGridInCell /> <w:WrapTextWithPunct /> <w:UseAsianBreakRules /> <w:DontGrowAutofit /> <w:SplitPgBreakAndParaMark /> <w:DontVertAlignCellWithSp /> <w:DontBreakConstrainedForcedTables /> <w:DontVertAlignInTxbx /> <w:Word11KerningPairs /> <w:CachedColBalance /> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> <m:mathPr> <m:mathFont m:val="Cambria Math" /> <m:brkBin m:val="before" /> <m:brkBinSub m:val="&#45;-" /> <m:smallFrac m:val="off" /> <m:dispDef /> <m:lMargin m:val="0" /> <m:rMargin m:val="0" /> <m:defJc m:val="centerGroup" /> <m:wrapIndent m:val="1440" /> <m:intLim m:val="subSup" /> <m:naryLim m:val="undOvr" /> </m:mathPr></w:WordDocument> </xml><![endif]--><!--[if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" DefUnhideWhenUsed="true"   DefSemiHidden="true" DefQFormat="false" DefPriority="99"   LatentStyleCount="267"> <w:LsdException Locked="false" Priority="0" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Normal" /> <w:LsdException Locked="false" Priority="9" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="heading 1" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 2" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 3" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 4" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 5" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 6" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 7" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 8" /> <w:LsdException Locked="false" Priority="9" QFormat="true" Name="heading 9" /> <w:LsdException Locked="false" Priority="39" Name="toc 1" /> <w:LsdException Locked="false" Priority="39" Name="toc 2" /> <w:LsdException Locked="false" Priority="39" Name="toc 3" /> <w:LsdException Locked="false" Priority="39" Name="toc 4" /> <w:LsdException Locked="false" Priority="39" Name="toc 5" /> <w:LsdException Locked="false" Priority="39" Name="toc 6" /> <w:LsdException Locked="false" Priority="39" Name="toc 7" /> <w:LsdException Locked="false" Priority="39" Name="toc 8" /> <w:LsdException Locked="false" Priority="39" Name="toc 9" /> <w:LsdException Locked="false" Priority="35" QFormat="true" Name="caption" /> <w:LsdException Locked="false" Priority="10" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Title" /> <w:LsdException Locked="false" Priority="1" Name="Default Paragraph Font" /> <w:LsdException Locked="false" Priority="11" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Subtitle" /> <w:LsdException Locked="false" Priority="22" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Strong" /> <w:LsdException Locked="false" Priority="20" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Emphasis" /> <w:LsdException Locked="false" Priority="59" SemiHidden="false"    UnhideWhenUsed="false" Name="Table Grid" /> <w:LsdException Locked="false" UnhideWhenUsed="false" Name="Placeholder Text" /> <w:LsdException Locked="false" Priority="1" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="No Spacing" /> <w:LsdException Locked="false" Priority="60" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Shading" /> <w:LsdException Locked="false" Priority="61" SemiHidden="false"    UnhideWhenUsed="false" Name="Light List" /> <w:LsdException Locked="false" Priority="62" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Grid" /> <w:LsdException Locked="false" Priority="63" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 1" /> <w:LsdException Locked="false" Priority="64" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 2" /> <w:LsdException Locked="false" Priority="65" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 1" /> <w:LsdException Locked="false" Priority="66" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 2" /> <w:LsdException Locked="false" Priority="67" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 1" /> <w:LsdException Locked="false" Priority="68" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 2" /> <w:LsdException Locked="false" Priority="69" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 3" /> <w:LsdException Locked="false" Priority="70" SemiHidden="false"    UnhideWhenUsed="false" Name="Dark List" /> <w:LsdException Locked="false" Priority="71" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Shading" /> <w:LsdException Locked="false" Priority="72" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful List" /> <w:LsdException Locked="false" Priority="73" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Grid" /> <w:LsdException Locked="false" Priority="60" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Shading Accent 1" /> <w:LsdException Locked="false" Priority="61" SemiHidden="false"    UnhideWhenUsed="false" Name="Light List Accent 1" /> <w:LsdException Locked="false" Priority="62" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Grid Accent 1" /> <w:LsdException Locked="false" Priority="63" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 1 Accent 1" /> <w:LsdException Locked="false" Priority="64" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 2 Accent 1" /> <w:LsdException Locked="false" Priority="65" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 1 Accent 1" /> <w:LsdException Locked="false" UnhideWhenUsed="false" Name="Revision" /> <w:LsdException Locked="false" Priority="34" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="List Paragraph" /> <w:LsdException Locked="false" Priority="29" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Quote" /> <w:LsdException Locked="false" Priority="30" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Intense Quote" /> <w:LsdException Locked="false" Priority="66" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 2 Accent 1" /> <w:LsdException Locked="false" Priority="67" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 1 Accent 1" /> <w:LsdException Locked="false" Priority="68" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 2 Accent 1" /> <w:LsdException Locked="false" Priority="69" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 3 Accent 1" /> <w:LsdException Locked="false" Priority="70" SemiHidden="false"    UnhideWhenUsed="false" Name="Dark List Accent 1" /> <w:LsdException Locked="false" Priority="71" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Shading Accent 1" /> <w:LsdException Locked="false" Priority="72" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful List Accent 1" /> <w:LsdException Locked="false" Priority="73" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Grid Accent 1" /> <w:LsdException Locked="false" Priority="60" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Shading Accent 2" /> <w:LsdException Locked="false" Priority="61" SemiHidden="false"    UnhideWhenUsed="false" Name="Light List Accent 2" /> <w:LsdException Locked="false" Priority="62" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Grid Accent 2" /> <w:LsdException Locked="false" Priority="63" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 1 Accent 2" /> <w:LsdException Locked="false" Priority="64" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 2 Accent 2" /> <w:LsdException Locked="false" Priority="65" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 1 Accent 2" /> <w:LsdException Locked="false" Priority="66" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 2 Accent 2" /> <w:LsdException Locked="false" Priority="67" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 1 Accent 2" /> <w:LsdException Locked="false" Priority="68" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 2 Accent 2" /> <w:LsdException Locked="false" Priority="69" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 3 Accent 2" /> <w:LsdException Locked="false" Priority="70" SemiHidden="false"    UnhideWhenUsed="false" Name="Dark List Accent 2" /> <w:LsdException Locked="false" Priority="71" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Shading Accent 2" /> <w:LsdException Locked="false" Priority="72" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful List Accent 2" /> <w:LsdException Locked="false" Priority="73" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Grid Accent 2" /> <w:LsdException Locked="false" Priority="60" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Shading Accent 3" /> <w:LsdException Locked="false" Priority="61" SemiHidden="false"    UnhideWhenUsed="false" Name="Light List Accent 3" /> <w:LsdException Locked="false" Priority="62" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Grid Accent 3" /> <w:LsdException Locked="false" Priority="63" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 1 Accent 3" /> <w:LsdException Locked="false" Priority="64" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 2 Accent 3" /> <w:LsdException Locked="false" Priority="65" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 1 Accent 3" /> <w:LsdException Locked="false" Priority="66" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 2 Accent 3" /> <w:LsdException Locked="false" Priority="67" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 1 Accent 3" /> <w:LsdException Locked="false" Priority="68" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 2 Accent 3" /> <w:LsdException Locked="false" Priority="69" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 3 Accent 3" /> <w:LsdException Locked="false" Priority="70" SemiHidden="false"    UnhideWhenUsed="false" Name="Dark List Accent 3" /> <w:LsdException Locked="false" Priority="71" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Shading Accent 3" /> <w:LsdException Locked="false" Priority="72" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful List Accent 3" /> <w:LsdException Locked="false" Priority="73" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Grid Accent 3" /> <w:LsdException Locked="false" Priority="60" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Shading Accent 4" /> <w:LsdException Locked="false" Priority="61" SemiHidden="false"    UnhideWhenUsed="false" Name="Light List Accent 4" /> <w:LsdException Locked="false" Priority="62" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Grid Accent 4" /> <w:LsdException Locked="false" Priority="63" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 1 Accent 4" /> <w:LsdException Locked="false" Priority="64" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 2 Accent 4" /> <w:LsdException Locked="false" Priority="65" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 1 Accent 4" /> <w:LsdException Locked="false" Priority="66" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 2 Accent 4" /> <w:LsdException Locked="false" Priority="67" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 1 Accent 4" /> <w:LsdException Locked="false" Priority="68" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 2 Accent 4" /> <w:LsdException Locked="false" Priority="69" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 3 Accent 4" /> <w:LsdException Locked="false" Priority="70" SemiHidden="false"    UnhideWhenUsed="false" Name="Dark List Accent 4" /> <w:LsdException Locked="false" Priority="71" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Shading Accent 4" /> <w:LsdException Locked="false" Priority="72" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful List Accent 4" /> <w:LsdException Locked="false" Priority="73" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Grid Accent 4" /> <w:LsdException Locked="false" Priority="60" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Shading Accent 5" /> <w:LsdException Locked="false" Priority="61" SemiHidden="false"    UnhideWhenUsed="false" Name="Light List Accent 5" /> <w:LsdException Locked="false" Priority="62" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Grid Accent 5" /> <w:LsdException Locked="false" Priority="63" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 1 Accent 5" /> <w:LsdException Locked="false" Priority="64" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 2 Accent 5" /> <w:LsdException Locked="false" Priority="65" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 1 Accent 5" /> <w:LsdException Locked="false" Priority="66" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 2 Accent 5" /> <w:LsdException Locked="false" Priority="67" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 1 Accent 5" /> <w:LsdException Locked="false" Priority="68" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 2 Accent 5" /> <w:LsdException Locked="false" Priority="69" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 3 Accent 5" /> <w:LsdException Locked="false" Priority="70" SemiHidden="false"    UnhideWhenUsed="false" Name="Dark List Accent 5" /> <w:LsdException Locked="false" Priority="71" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Shading Accent 5" /> <w:LsdException Locked="false" Priority="72" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful List Accent 5" /> <w:LsdException Locked="false" Priority="73" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Grid Accent 5" /> <w:LsdException Locked="false" Priority="60" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Shading Accent 6" /> <w:LsdException Locked="false" Priority="61" SemiHidden="false"    UnhideWhenUsed="false" Name="Light List Accent 6" /> <w:LsdException Locked="false" Priority="62" SemiHidden="false"    UnhideWhenUsed="false" Name="Light Grid Accent 6" /> <w:LsdException Locked="false" Priority="63" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 1 Accent 6" /> <w:LsdException Locked="false" Priority="64" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Shading 2 Accent 6" /> <w:LsdException Locked="false" Priority="65" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 1 Accent 6" /> <w:LsdException Locked="false" Priority="66" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium List 2 Accent 6" /> <w:LsdException Locked="false" Priority="67" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 1 Accent 6" /> <w:LsdException Locked="false" Priority="68" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 2 Accent 6" /> <w:LsdException Locked="false" Priority="69" SemiHidden="false"    UnhideWhenUsed="false" Name="Medium Grid 3 Accent 6" /> <w:LsdException Locked="false" Priority="70" SemiHidden="false"    UnhideWhenUsed="false" Name="Dark List Accent 6" /> <w:LsdException Locked="false" Priority="71" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Shading Accent 6" /> <w:LsdException Locked="false" Priority="72" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful List Accent 6" /> <w:LsdException Locked="false" Priority="73" SemiHidden="false"    UnhideWhenUsed="false" Name="Colorful Grid Accent 6" /> <w:LsdException Locked="false" Priority="19" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Subtle Emphasis" /> <w:LsdException Locked="false" Priority="21" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Intense Emphasis" /> <w:LsdException Locked="false" Priority="31" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Subtle Reference" /> <w:LsdException Locked="false" Priority="32" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Intense Reference" /> <w:LsdException Locked="false" Priority="33" SemiHidden="false"    UnhideWhenUsed="false" QFormat="true" Name="Book Title" /> <w:LsdException Locked="false" Priority="37" Name="Bibliography" /> <w:LsdException Locked="false" Priority="39" QFormat="true" Name="TOC Heading" /> </w:LatentStyles> </xml><![endif]--><!--[if gte mso 10]> <mce:style><!   /* Style Definitions */  table.MsoNormalTable 	{mso-style-name:"Table Normal"; 	mso-tstyle-rowband-size:0; 	mso-tstyle-colband-size:0; 	mso-style-noshow:yes; 	mso-style-priority:99; 	mso-style-qformat:yes; 	mso-style-parent:""; 	mso-padding-alt:0in 5.4pt 0in 5.4pt; 	mso-para-margin:0in; 	mso-para-margin-bottom:.0001pt; 	mso-pagination:widow-orphan; 	font-size:11.0pt; 	font-family:"Calibri","sans-serif"; 	mso-ascii-font-family:Calibri; 	mso-ascii-theme-font:minor-latin; 	mso-hansi-font-family:Calibri; 	mso-hansi-theme-font:minor-latin;} --> <!--[endif]--></p><p>Thus, whenever the client request comes, the container match the pattern *.do in the URL and invokes the ActionServlet class which handles the rest of flow in Struts application. In order to use clean URL, make following entry for ActionServlet in your Web.xml file.</p><pre class="brush: xml; title: ; notranslate">
&lt;servlet&gt;
&lt;servlet-name&gt;action&lt;/servlet-name&gt;
&lt;servlet-class&gt;
org.apache.struts.action.ActionServlet
&lt;/servlet-class&gt;
&lt;init-param&gt;
&lt;param-name&gt;config&lt;/param-name&gt;
&lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
&lt;param-name&gt;debug&lt;/param-name&gt;
&lt;param-value&gt;2&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
&lt;param-name&gt;detail&lt;/param-name&gt;
&lt;param-value&gt;2&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;init-param&gt;
&lt;param-name&gt;chainConfig&lt;/param-name&gt;
&lt;param-value&gt;
org/apache/struts/tiles/chain-config.xml
&lt;/param-value&gt;
&lt;/init-param&gt;
&lt;load-on-startup&gt;2&lt;/load-on-startup&gt;
&lt;/servlet&gt;

&lt;!-- Extension mappings to static content --&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;url-pattern&gt;*.css&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;url-pattern&gt;*.js&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;url-pattern&gt;*.png&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;url-pattern&gt;*.jpg&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;default&lt;/servlet-name&gt;
&lt;url-pattern&gt;/index.jsp&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
&lt;servlet-mapping&gt;
&lt;servlet-name&gt;action&lt;/servlet-name&gt;
&lt;url-pattern&gt;/&lt;/url-pattern&gt;
&lt;/servlet-mapping&gt;
</pre><p>Please note that here the URL pattern that is mapped to ActionServlet class is not <strong>*.do</strong> and is <strong>/</strong> i.e. all the requests that comes will be routed to ActionServlet by the container. Also, URL patterns such as *.js, *.jpg, *.png, *.css etc are mapped to a servlet called <strong>default</strong>. This ensures that the static content are served to client without getting redirected to ActionServlet. Thus if you have other static content in your website, don&#8217;t forget to make an entry here and map it to default servlet. For example, I may have some *.zip files that I want to my users to download. Hence I will create an entry for *.zip and map it to default servlet in Web.xml file.</p><p>Once this is done, all the requests (except for static content) will get routed to ActionServlet.</p><p>Now, we will make normal entries for Action class in struts-config.xml file. Each entry will have a unique URL pattern that maps to an Action class.</p><pre class="brush: xml; title: ; notranslate">
&lt;action path=&quot;/login&quot; name=&quot;userBean&quot; scope=&quot;request&quot;
validate=&quot;true&quot; input=&quot;/index.jsp&quot;
type=&quot;net.viralpatel.sturts.cleanurl.LoginAction&quot;&gt;
&lt;forward name=&quot;success&quot; path=&quot;/home&quot; /&gt;
&lt;forward name=&quot;fail&quot; path=&quot;/index.jsp&quot; /&gt;
&lt;/action&gt;
&lt;action path=&quot;/home&quot; name=&quot;userBean&quot; scope=&quot;request&quot;
validate=&quot;true&quot; input=&quot;/index.jsp&quot;
type=&quot;net.viralpatel.sturts.cleanurl.HomeAction&quot;&gt;
&lt;forward name=&quot;success&quot; path=&quot;/home.jsp&quot; /&gt;
&lt;forward name=&quot;fail&quot; path=&quot;/home.jsp&quot; /&gt;
&lt;/action&gt;
&lt;action path=&quot;/profile/save&quot; name=&quot;profileForm&quot; scope=&quot;request&quot;
validate=&quot;false&quot; input=&quot;/profile.jsp&quot;
type=&quot;net.viralpatel.sturts.cleanurl.ProfileAction&quot;&gt;
&lt;forward name=&quot;success&quot; path=&quot;/profile.jsp&quot; /&gt;
&lt;forward name=&quot;fail&quot; path=&quot;/profile.jsp&quot; /&gt;
&lt;/action&gt;
</pre><p>Thus, whenever client request for a URL /login, LoginAction will be invoked by Struts framework. It is sometimes desirable to achieve clean url where request parameters are passed. For example, in some application <strong>/profile/john</strong> will point to Profile page of user John and <strong>/profile/william</strong> will point to that of William.</p><p>This can be achieved by using parametrized struts-config entries for actions. For example.</p><pre class="brush: xml; title: ; notranslate">
&lt;action path=&quot;/profile/*&quot;
type=&quot;net.viralpatel.struts.cleanurl.ProfileAction&quot;
parameter=&quot;{1}&quot;&gt;
&lt;forward name=&quot;success&quot; path=&quot;/profile.jsp&quot; /&gt;
&lt;forward name=&quot;fail&quot; path=&quot;/profile.jsp&quot; /&gt;
&lt;/action&gt;
</pre><p>We have mapped a URL pattern /profile/* to ProfileAction. Thus whenever client will request for pages such as /profile/john or /profile/william, ProfileAction will gets invoked by Struts. Also note that we have used a <strong>parameter=&#8221;{1}&#8221; </strong>attribute in &lt;action&gt; tag. This will pass whatever string that comes as * in /profile/* to Action class. This parameter can be fetched in Action class from <strong>mapping </strong>object of <strong>ActionMapping </strong>class which is passed as method argument in <strong>execute()</strong> method of Action.</p><pre class="brush: java; title: ; notranslate">
public ActionForward process(ActionMapping mapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response)
throws NoRecordFoundException {

String parameter = mapping.getParameter();
...
}
</pre><p>Also, more than one parameter can be passed into the action for URLs like /profile/john/friends or /profile/john/groups. Thus to acheive this, URL <strong>/profile/*/*</strong> is mapped to Action and <strong>parameter=&#8221;{1}${2}&#8221;</strong> attribute will be added to action tag. Once the parameter is retrived in Action class using mapping.getParameter(), it has to split using $ separator as $ is used to concatenate {1} and {2} arguments.</p><p>Comments and queries invited <img src='http://viralpatel.net/blogs/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /></p><div id="relatedpost"><h2  class="related_post_title">Related Posts</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/06/struts-displaytag-tutorial-sort-pagination-data-displaytag-struts.html" title="Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts">Struts displaytag tutorial: Sort / Pagination data using displaytag in Struts</a></li><li><a href="http://viralpatel.net/blogs/2009/03/tutorial-creating-dynaactionform-example-in-struts-dynaactionform-struts.html" title="Tutorial: Creating DynaActionForm example in Struts">Tutorial: Creating DynaActionForm example in Struts</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></ul></div>]]></content:encoded> <wfw:commentRss>http://viralpatel.net/blogs/2008/12/implementing-clean-url-in-struts.html/feed</wfw:commentRss> <slash:comments>7</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced

Served from: viralpatel.net @ 2012-02-09 02:41:28 -->
