<?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>Latest-Tutorial &#187; Java</title>
	<atom:link href="http://latest-tutorial.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://latest-tutorial.com</link>
	<description>Best Tutorials for Beginners of Java,Android,JavaScript,Asp.net,Objective C,C-Sharp and many other topics.We have experts tutorial material against these topics.</description>
	<lastBuildDate>Wed, 22 May 2013 08:39:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Read / Write CSV file in Java</title>
		<link>http://latest-tutorial.com/2013/05/21/read-write-csv-file-in-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=read-write-csv-file-in-java</link>
		<comments>http://latest-tutorial.com/2013/05/21/read-write-csv-file-in-java/#comments</comments>
		<pubDate>Tue, 21 May 2013 09:13:15 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Java Tutorials]]></category>
		<category><![CDATA[China]]></category>
		<category><![CDATA[Comma-separated values]]></category>
		<category><![CDATA[create csv file in Java]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[languages]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[read csv file in Java]]></category>
		<category><![CDATA[Reading]]></category>
		<category><![CDATA[United States]]></category>
		<category><![CDATA[Write CSV file in Java]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=3219</guid>
		<description><![CDATA[If you want to work with Comma-separated Files (CSV) in Java, here’s a quick API for you. As Java doesn’t support parsing of CSV files natively, we have to rely on third party library. Opencsv is one of the best library available for this purpose. It’s open source and is shipped with Apache 2.0 licence [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><div style="padding-left:5px; padding-right:5px; padding-bottom:5px; padding-top:5px; margin-left:auto; margin-right:auto; ">
<script type="text/javascript"><!--
google_ad_client = "pub-1265735558479661";
google_ad_width = 468;
google_ad_height = 60;
google_color_border = "FFFFFF";
google_color_link = "E895CC";
google_color_text = "000000";
google_color_bg = "FFFFFF";
google_color_url = "0066CC";
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<div>
<p><a href="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/random-text.jpg"><img class="alignright" title="random-text" alt="random-text" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/random-text.jpg?resize=120%2C180" data-recalc-dims="1" /></a>If you want to work with Comma-separated Files (CSV) in Java, here’s a quick API for you.</p>
<p>As Java doesn’t support parsing of CSV files natively, we have to rely on third party library. <a href="http://opencsv.sourceforge.net/" target="_new" rel="nofollow">Opencsv</a> is one of the best library available for this purpose. It’s open source and is shipped with Apache 2.0 licence which makes it possible for commercial use.</p>
<p>Let’s us see different APIs to parse CSV file. Before that we will need certain tools for this example:</p>
<p><b>Tools &amp; Technologies</b></p>
<ol>
<li>Java JDK 1.5 or above</li>
<li>OpenCSV library v1.8 or above (<a href="http://sourceforge.net/projects/opencsv/files/opencsv/" target="_new" rel="nofollow">download</a>)</li>
<li>Eclipse 3.2 above (optional)</li>
</ol>
<p>Let’s get started.</p>
<h2>1. Reading CSV file in Java</h2>
<p>We will use following CSV sample file for this example:<br />
File: sample.csv</p>
<div>
<div id="highlighter_301139">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>COUNTRY,CAPITAL,POPULATION</code></div>
<div><code>India,New Delhi, 1.21B</code></div>
<div><code>People's republic of China,Beijing, 1.34B</code></div>
<div><code>United States,Washington D.C., 0.31B</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Read CSV file line by line:</p>
<div>
<div id="highlighter_953717">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>String csvFilename = </code><code>"C:\sample.csv"</code><code>;</code></div>
<div><code>CSVReader csvReader = </code><code>new</code> <code>CSVReader(</code><code>new</code> <code>FileReader(csvFilename));</code></div>
<div><code>String[] row = </code><code>null</code><code>;</code></div>
<div><code>while</code><code>((row = csvReader.readNext()) != </code><code>null</code><code>) {</code></div>
<div><code>    </code><code>System.out.println(row[</code><code>0</code><code>]</code></div>
<div><code>              </code><code>+ </code><code>" # "</code> <code>+ row[</code><code>1</code><code>]</code></div>
<div><code>              </code><code>+ </code><code>" #  "</code> <code>+ row[</code><code>2</code><code>]);</code></div>
<div><code>}</code></div>
<div><code>//...</code></div>
<div><code>csvReader.close();</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>In above code snippet, we use <code>readNext()</code> method of <code>CSVReader</code> class to read CSV file line by line. It returns a String array for each value in row.</p>
<p>It is also possible to read full CSV file once. The <code>readAll()</code> method of CSVReader class comes handy for this.</p>
<div>
<div id="highlighter_107706">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>String[] row = </code><code>null</code><code>;</code></div>
<div><code>String csvFilename = </code><code>"C:\work\sample.csv"</code><code>;</code></div>
<div></div>
<div><code>CSVReader csvReader = </code><code>new</code> <code>CSVReader(</code><code>new</code> <code>FileReader(csvFilename));</code></div>
<div><code>List content = csvReader.readAll();</code></div>
<div></div>
<div><code>for</code> <code>(Object object : content) {</code></div>
<div><code>    </code><code>row = (String[]) object;</code></div>
<div><code>    </code></div>
<div><code>    </code><code>System.out.println(row[</code><code>0</code><code>]</code></div>
<div><code>               </code><code>+ </code><code>" # "</code> <code>+ row[</code><code>1</code><code>]</code></div>
<div><code>               </code><code>+ </code><code>" #  "</code> <code>+ row[</code><code>2</code><code>]);</code></div>
<div><code>}</code></div>
<div><code>//...</code></div>
<div><code>csvReader.close();</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>The <code>readAll()</code> method returns a <code>List</code> of <code>String[]</code> for given CSV file.</p>
<p>Both of the above code snippet prints output:<br />
<strong>Output</strong></p>
<div>
<div id="highlighter_747143">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>COUNTRY # CAPITAL #  POPULATION</code></div>
<div><code>India # New Delhi #   1.21B</code></div>
<div><code>People's republic of China # Beijing #   1.34B</code></div>
<div><code>United States # Washington D.C. #   0.31B</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p><b>Use different separator and quote characters</b><br />
If you want to parse a file with other delimiter like semicolon (;) or hash (#), you can do so by calling a different constructor of CSVReader class:</p>
<div>
<div id="highlighter_387534">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>CSVReader reader = </code><code>new</code> <code>CSVReader(</code><code>new</code> <code>FileReader(file), </code><code>';'</code><code>)</code></div>
<div><code>//or</code></div>
<div><code>CSVReader reader = </code><code>new</code> <code>CSVReader(</code><code>new</code> <code>FileReader(file), </code><code>'#'</code><code>)</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Also if your CSV file’s value is quoted with single quote (‘) instead of default double quote (“), then you can specify it in constructor:</p>
<div>
<div id="highlighter_528385">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>CSVReader reader = </code><code>new</code> <code>CSVReader(</code><code>new</code> <code>FileReader(file), </code><code>','</code><code>, </code><code>'''</code><code>)</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Also it is possible to skip certain lines from the top of CSV while parsing. You can provide how many lines to skip in CSVReader’s constructor. For example the below reader will skip 5 lines from top of CSV and starts processing at line 6.</p>
<div>
<div id="highlighter_730303">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>CSVReader reader = </code><code>new</code> <code>CSVReader(</code><code>new</code> <code>FileReader(file), </code><code>','</code><code>, </code><code>'''</code><code>, </code><code>5</code><code>);</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<h2>2. Writing CSV file in Java</h2>
<p>Creating a CSV file is as simple as reading one. All you have to do is it create the data list and write using <code>CSVWriter</code> class.</p>
<p>Below is the code snippet where we write one line in CSV file.</p>
<div>
<div id="highlighter_819169">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>String csv = </code><code>"C:\output.csv"</code><code>;</code></div>
<div><code>CSVWriter writer = </code><code>new</code> <code>CSVWriter(</code><code>new</code> <code>FileWriter(csv));</code></div>
<div></div>
<div><code>String [] country = </code><code>"India#China#United States"</code><code>.split(</code><code>"#"</code><code>);</code></div>
<div></div>
<div><code>writer.writeNext(country);</code></div>
<div></div>
<div><code>writer.close();</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>We created object of class <code>CSVWriter</code> and called its <code>writeNext()</code> method. The <code>writeNext()</code> methods takes <code>String []</code> as argument.</p>
<p>You can also write a List of String[] to CSV directly. Following is code snippet for that.</p>
<div>
<div id="highlighter_973131">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>String csv = </code><code>"C:\output2.csv"</code><code>;</code></div>
<div><code>CSVWriter writer = </code><code>new</code> <code>CSVWriter(</code><code>new</code> <code>FileWriter(csv));</code></div>
<div></div>
<div><code>List&lt;String[]&gt; data = </code><code>new</code> <code>ArrayList&lt;String[]&gt;();</code></div>
<div><code>data.add(</code><code>new</code> <code>String[] {</code><code>"India"</code><code>, </code><code>"New Delhi"</code><code>});</code></div>
<div><code>data.add(</code><code>new</code> <code>String[] {</code><code>"United States"</code><code>, </code><code>"Washington D.C"</code><code>});</code></div>
<div><code>data.add(</code><code>new</code> <code>String[] {</code><code>"Germany"</code><code>, </code><code>"Berlin"</code><code>});</code></div>
<div></div>
<div><code>writer.writeAll(data);</code></div>
<div></div>
<div><code>writer.close();</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>We used <code>writeAll()</code> method of class CSVWriter to write a List of String[] as CSV file.</p>
<h2>3. Mapping CSV with Java beans</h2>
<p>In above examples we saw how to parse CSV file and read the data in it. We retrieved the data as String array. Each record got mapped to String.</p>
<p>It is possible to map the result to a Java bean object. For example we created a Java bean to store Country information.</p>
<p>Country.java – The bean object to store Countries information.</p>
<div>
<div id="highlighter_393799">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>package</code> <code>net.viralpatel.java;</code></div>
<div></div>
<div><code>public</code> <code>class</code> <code>Country {</code></div>
<div><code>    </code><code>private</code> <code>String countryName;</code></div>
<div><code>    </code><code>private</code> <code>String capital;</code></div>
<div></div>
<div><code>    </code><code>public</code> <code>String getCountryName() {</code></div>
<div><code>        </code><code>return</code> <code>countryName;</code></div>
<div><code>    </code><code>}</code></div>
<div></div>
<div><code>    </code><code>public</code> <code>void</code> <code>setCountryName(String countryName) {</code></div>
<div><code>        </code><code>this</code><code>.countryName = countryName;</code></div>
<div><code>    </code><code>}</code></div>
<div></div>
<div><code>    </code><code>public</code> <code>String getCapital() {</code></div>
<div><code>        </code><code>return</code> <code>capital;</code></div>
<div><code>    </code><code>}</code></div>
<div></div>
<div><code>    </code><code>public</code> <code>void</code> <code>setCapital(String capital) {</code></div>
<div><code>        </code><code>this</code><code>.capital = capital;</code></div>
<div><code>    </code><code>}</code></div>
<div><code>}</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Now we can map this bean with Opencsv and read the CSV file. Check out below example:</p>
<div>
<div id="highlighter_234141">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>ColumnPositionMappingStrategy strat = </code><code>new</code> <code>ColumnPositionMappingStrategy();</code></div>
<div><code>strat.setType(Country.</code><code>class</code><code>);</code></div>
<div><code>String[] columns = </code><code>new</code> <code>String[] {</code><code>"countryName"</code><code>, </code><code>"capital"</code><code>}; </code><code>// the fields to bind do in your JavaBean</code></div>
<div><code>strat.setColumnMapping(columns);</code></div>
<div></div>
<div><code>CsvToBean csv = </code><code>new</code> <code>CsvToBean();</code></div>
<div></div>
<div><code>String csvFilename = </code><code>"C:\sample.csv"</code><code>;</code></div>
<div><code>CSVReader csvReader = </code><code>new</code> <code>CSVReader(</code><code>new</code> <code>FileReader(csvFilename));</code></div>
<div></div>
<div><code>List list = csv.parse(strat, csvReader);</code></div>
<div><code>for</code> <code>(Object object : list) {</code></div>
<div><code>    </code><code>Country country = (Country) object;</code></div>
<div><code>    </code><code>System.out.println(country.getCapital());</code></div>
<div><code>}</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Check how we mapped <code>Country</code> class using <code>ColumnPositionMappingStrategy</code>. Also the method <code>setColumnMapping</code> is used to map individual property of Java bean to the CSV position. In this example we map first CSV value to <code>countryName</code> attribute and next to <code>capital</code>.</p>
<h2>4. Dumping SQL Table as CSV</h2>
<p>OpenCSV also provides support to dump data from SQL table directly to CSV. For this we need ResultSet object. Following API can be used to write data to CSV from ResultSet.</p>
<div>
<div id="highlighter_103560">
<table border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>
<div>
<div><code>java.sql.ResultSet myResultSet = getResultSetFromSomewhere();</code></div>
<div><code>writer.writeAll(myResultSet, includeHeaders);</code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<p>The <code>writeAll(ResultSet, boolean)</code> method is utilized for this. The first argument is the ResultSet which you want to write to CSV file. And the second argument is boolean which represents whether you want to write header columns (table column names) to file or not.</p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel-net-tutorials.googlecode.com/files/ReadWrite_CSV_Java_example.zip"><strong>ReadWrite_CSV_Java_example.zip (356 KB)</strong></a></p>
</div>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i2.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
<script type="text/javascript"><!--
google_ad_client = "pub-1265735558479661";
google_ad_width = 468;
google_ad_height = 60;
google_color_border = "FFFFFF";
google_color_link = "E895CC";
google_color_text = "000000";
google_color_bg = "FFFFFF";
google_color_url = "0066CC";
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/05/21/read-write-csv-file-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Load ImageView with bitmap from internet</title>
		<link>http://latest-tutorial.com/2013/05/15/load-imageview-with-bitmap-from-internet/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=load-imageview-with-bitmap-from-internet</link>
		<comments>http://latest-tutorial.com/2013/05/15/load-imageview-with-bitmap-from-internet/#comments</comments>
		<pubDate>Wed, 15 May 2013 06:16:39 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Android Posts]]></category>
		<category><![CDATA[Android Tutorials]]></category>
		<category><![CDATA[Android]]></category>
		<category><![CDATA[Bitmap]]></category>
		<category><![CDATA[Data Formats]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Markup Languages]]></category>
		<category><![CDATA[Pixel]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=3105</guid>
		<description><![CDATA[It&#8217;s a simple way to load ImageView with a bitmap from internet, via http connection. In order to load something from internet, the AndroidManifest.xml have to be modified to grand permission for internet access. &#60;?xml version="1.0" encoding="utf-8"?&#62; &#60;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.exercise.AndroidWebImage" android:versionCode="1" android:versionName="1.0"&#62; &#60;application android:icon="@drawable/icon" android:label="@string/app_name"&#62; &#60;activity android:name=".AndroidWebImage" android:label="@string/app_name"&#62; &#60;intent-filter&#62; &#60;action android:name="android.intent.action.MAIN" /&#62; &#60;category android:name="android.intent.category.LAUNCHER" /&#62; [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><p>It&#8217;s a simple way to load ImageView with a bitmap from internet, via http connection.</p>
<p><a href="http://i0.wp.com/3.bp.blogspot.com/_C5a2qH8Y_jk/TBmVxMJ396I/AAAAAAAAAdU/c_v3FdcDGos/s1600/AndroidWebImage_01.png"><img class="aligncenter" id="BLOGGER_PHOTO_ID_5483578693609060258" title="Load ImageView with bitmap from internet" alt="Load ImageView with bitmap from internet" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/AndroidWebImage_01.png?resize=185%2C271" border="0" data-recalc-dims="1" /></a></p>
<p>In order to load something from internet, the AndroidManifest.xml have to be modified to grand permission for internet access.</p>
<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.exercise.AndroidWebImage"
     android:versionCode="1"
     android:versionName="1.0"&gt;
   &lt;application android:icon="@drawable/icon" android:label="@string/app_name"&gt;
       &lt;activity android:name=".AndroidWebImage"
                 android:label="@string/app_name"&gt;
           &lt;intent-filter&gt;
               &lt;action android:name="android.intent.action.MAIN" /&gt;
               &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
           &lt;/intent-filter&gt;
       &lt;/activity&gt;

   &lt;/application&gt;
   &lt;uses-sdk android:minSdkVersion="4" /&gt;
 &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
&lt;/manifest&gt;
</code></pre>
<p>Modify main.xml to include a ImageView</p>
<pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   &gt;
&lt;TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   /&gt;
&lt;ImageView
   android:id="@+id/image"
   android:scaleType="center"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/&gt;
&lt;/LinearLayout&gt;
</code></pre>
<p>java code:</p>
<pre><code>package com.exercise.AndroidWebImage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidWebImage extends Activity {

String image_URL=
 "http://4.bp.blogspot.com/_C5a2qH8Y_jk/StYXDpZ9-WI/AAAAAAAAAJQ/sCgPx6jfWPU/S1600-R/android.png";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       ImageView bmImage = (ImageView)findViewById(R.id.image);
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    Bitmap bm = LoadImage(image_URL, bmOptions);
    bmImage.setImageBitmap(bm);
   }

   private Bitmap LoadImage(String URL, BitmapFactory.Options options)
   {       
    Bitmap bitmap = null;
    InputStream in = null;       
       try {
           in = OpenHttpConnection(URL);
           bitmap = BitmapFactory.decodeStream(in, null, options);
           in.close();
       } catch (IOException e1) {
       }
       return bitmap;               
   }

private InputStream OpenHttpConnection(String strURL) throws IOException{
 InputStream inputStream = null;
 URL url = new URL(strURL);
 URLConnection conn = url.openConnection();

 try{
  HttpURLConnection httpConn = (HttpURLConnection)conn;
  httpConn.setRequestMethod("GET");
  httpConn.connect();

  if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
   inputStream = httpConn.getInputStream();
  }
 }
 catch (Exception ex)
 {
 }
 return inputStream;
}

}</code></pre>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i1.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/05/15/load-imageview-with-bitmap-from-internet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Struts 2 Tutorial: Struts 2 Interceptors Tutorial with Example</title>
		<link>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-interceptors-tutorial-with-example/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=struts-2-tutorial-struts-2-interceptors-tutorial-with-example</link>
		<comments>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-interceptors-tutorial-with-example/#comments</comments>
		<pubDate>Mon, 06 May 2013 10:17:13 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Java Tutorials]]></category>
		<category><![CDATA[JavaScript Posts]]></category>
		<category><![CDATA[Apache Struts]]></category>
		<category><![CDATA[Capital punishment]]></category>
		<category><![CDATA[Interceptor aircraft]]></category>
		<category><![CDATA[Interceptor pattern]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaServer Pages]]></category>
		<category><![CDATA[Logging]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2955</guid>
		<description><![CDATA[Struts 2 Interceptors: Basics Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc. [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><h2>Struts 2 Interceptors: Basics</h2>
<p>Struts2 provides very powerful mechanism of controlling a request using Interceptors. Interceptors are responsible for most of the request processing. They are invoked by the controller before and after invoking action, thus they sits between the controller and action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.<br />
<img title="struts2 request processing lifecycle" alt="struts2 request processing lifecycle" src="http://i0.wp.com/img.viralpatel.net/2009/12/struts-2-request-cycle.png?resize=481%2C184" data-recalc-dims="1" /><br />
The request processing lifecycle of Struts2 framework is pretty much discussed Part 1 – Introduction to Struts2 Framework.</p>
<ol>
<li>Request is generated by user and sent to Servlet container.</li>
<li>Servlet container invokes FilterDispatcher filter which in turn determines appropriate action.</li>
<li>One by one Intercetors are applied before calling the Action. Interceptors performs tasks such as Logging, Validation, File Upload, Double-submit guard etc.</li>
<li>Action is executed and the Result is generated by Action.</li>
<li>The output of Action is rendered in the view (JSP, Velocity, etc) and the result is returned to the user.</li>
</ol>
<p>Thus the Struts2 Interceptors removes cross cutting tasks such as logging from action components and create cleaner separation of MVC.</p>
<p>Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file. We can create our own custom Interceptors and plugin into a Struts2 based web application.</p>
<p>Framework creates an object of <strong>ActionInvocation</strong> that encapsulates the action and all the interceptors configured for that action. Each interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in reverse order to perform post processing work. Interceptors can alter the workflow of action. It may prevent the execution of action.</p>
<h2>Our Goal</h2>
<p>Our goal will be to create a customer interceptor <strong>MyLoggingInterceptor</strong>, which will log the request before any action is called. Also it will prints the Action class name and execution time of action in milliseconds.</p>
<h2>Create Logging Interceptor</h2>
<p>Create a java class MyLoggingInterceptor in package net.viralpatel.struts2.interceptors and copy following content into it.<br />
<img title="struts2-logging-interceptors" alt="struts2-logging-interceptors" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-logging-interceptors.png?resize=260%2C105" data-recalc-dims="1" /></p>
<div id="highlighter_625099">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-57#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-57#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-57#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>package</code> <code>net.viralpatel.struts2.interceptor;</code></div>
<div><code>02.</code></div>
<div><code>03.</code><code>import</code> <code>com.opensymphony.xwork2.ActionInvocation;</code></div>
<div><code>04.</code><code>import</code> <code>com.opensymphony.xwork2.interceptor.Interceptor;</code></div>
<div><code>05.</code></div>
<div><code>06.</code><code>public</code> <code>class</code> <code>MyLoggingInterceptor </code><code>implements</code> <code>Interceptor{</code></div>
<div><code>07.</code></div>
<div><code>08.</code><code>private</code> <code>static</code> <code>final</code> <code>long</code> <code>serialVersionUID = 1L;</code></div>
<div><code>09.</code></div>
<div><code>10.</code><code>public</code> <code>String intercept(ActionInvocation invocation) </code><code>throws</code> <code>Exception {</code></div>
<div><code>11.</code></div>
<div><code>12.</code><code>String className = invocation.getAction().getClass().getName();</code></div>
<div><code>13.</code><code>long</code> <code>startTime = System.currentTimeMillis();</code></div>
<div><code>14.</code><code>System.out.println(</code><code>"Before calling action: "</code> <code>+ className);</code></div>
<div><code>15.</code></div>
<div><code>16.</code><code>String result = invocation.invoke();</code></div>
<div><code>17.</code></div>
<div><code>18.</code><code>long</code> <code>endTime = System.currentTimeMillis();</code></div>
<div><code>19.</code><code>System.out.println(</code><code>"After calling action: "</code> <code>+ className</code></div>
<div><code>20.</code><code>+ </code><code>" Time taken: "</code> <code>+ (endTime - startTime) + </code><code>" ms"</code><code>);</code></div>
<div><code>21.</code></div>
<div><code>22.</code><code>return</code> <code>result;</code></div>
<div><code>23.</code><code>}</code></div>
<div><code>24.</code></div>
<div><code>25.</code><code>public</code> <code>void</code> <code>destroy() {</code></div>
<div><code>26.</code><code>System.out.println(</code><code>"Destroying MyLoggingInterceptor..."</code><code>);</code></div>
<div><code>27.</code><code>}</code></div>
<div><code>28.</code><code>public</code> <code>void</code> <code>init() {</code></div>
<div><code>29.</code><code>System.out.println(</code><code>"Initializing MyLoggingInterceptor..."</code><code>);</code></div>
<div><code>30.</code><code>}</code></div>
<div><code>31.</code><code>}</code></div>
</div>
</div>
<h2>Configuring Interceptor in struts.xml</h2>
<p>Once we have created an interceptor class, all we need to do is to configure it in struts.xml file and use it with actions.</p>
<p>To configure newly created interceptor, add following code in struts.xml</p>
<div id="highlighter_767697">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-57#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-57#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-57#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;</code><code>interceptors</code><code>&gt;</code></div>
<div><code>02.</code><code>&lt;</code><code>interceptor</code> <code>name</code><code>=</code><code>"mylogging"</code></div>
<div><code>03.</code></div>
<div><code>04.</code><code>class</code><code>=</code><code>"net.viralpatel.struts2.interceptor.MyLoggingInterceptor"</code><code>&gt;</code></div>
<div><code>05.</code><code>&lt;/</code><code>interceptor</code><code>&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>interceptor-stack</code> <code>name</code><code>=</code><code>"loggingStack"</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>interceptor-ref</code> <code>name</code><code>=</code><code>"mylogging"</code> <code>/&gt;</code></div>
<div><code>08.</code></div>
<div><code>09.</code><code>&lt;</code><code>interceptor-ref</code> <code>name</code><code>=</code><code>"defaultStack"</code> <code>/&gt;</code></div>
<div><code>10.</code><code>&lt;/</code><code>interceptor-stack</code><code>&gt;</code></div>
<div><code>11.</code><code>&lt;/</code><code>interceptors</code><code>&gt;</code></div>
</div>
</div>
<p>This code has to be added after &lt;result-types &gt; tag in &lt;package &gt;&lt;/package&gt;<br />
Here we have configured a new interceptor mylogging with tag &lt;interceptor &gt;. Also note that we have defined an <strong>interceptor-stack</strong> with name loggingStack. This is to make sure Sturts2 calls all the default interceptors as well while calling our custom interceptor. This is very important as the validation logic will not work in our struts2 application if we ignore the default stack of interceptors.</p>
<p>We can make the new loggingStack as default interceptor stack or can configure it at each action level. In order to make it default stack, we should add following in struts.xml</p>
<div id="highlighter_738131">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-57#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-57#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-57#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;</code><code>default-interceptor-ref</code> <code>name</code><code>=</code><code>"loggingStack"</code><code>&gt;&lt;/</code><code>default-interceptor-ref</code><code>&gt;</code></div>
</div>
</div>
<p>Once we add above code in Struts.xml, the logginStack will be applied to all the actions in that package.</p>
<p>Also we may want to apply the custom interceptor stack to only certain actions. To do so, we must add interceptor-ref tag in action.</p>
<div id="highlighter_408589">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-57#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-57#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-57#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"login"</code></div>
<div><code>2.</code><code>class</code><code>=</code><code>"net.viralpatel.struts2.LoginAction"</code><code>&gt;</code></div>
<div><code>3.</code><code>&lt;</code><code>interceptor-ref</code> <code>name</code><code>=</code><code>"loggingStack"</code><code>&gt;&lt;/</code><code>interceptor-ref</code><code>&gt;</code></div>
<div><code>4.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/welcome.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>5.</code></div>
<div><code>6.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"error"</code><code>&gt;Login.jsp&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>7.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
</div>
</div>
<h2>That’s All Folks</h2>
<p>If we execute our StrutsHelloWorld application in Eclipse and see the console logs, we will find the log statements that we print in our interceptor.</p>
<div id="highlighter_428033">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-57#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-57#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-57#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>Initializing MyLoggingInterceptor...</code></div>
<div><code>02.</code><code>..</code></div>
<div><code>03.</code><code>..</code></div>
<div><code>04.</code><code>..</code></div>
<div><code>05.</code><code>Before calling action: net.viralpatel.struts2.LoginAction</code></div>
<div><code>06.</code><code>..</code></div>
<div><code>07.</code><code>..</code></div>
<div><code>08.</code><code>After calling action: net.viralpatel.struts2.LoginAction Time taken: 313 ms</code></div>
<div><code>09.</code><code>..</code></div>
<div><code>10.</code><code>..</code></div>
<div><code>11.</code><code>..</code></div>
<div><code>12.</code><code>Destroying MyLoggingInterceptor...</code></div>
</div>
</div>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-5-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (17KB)</strong></a></p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i2.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-interceptors-tutorial-with-example/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Struts 2 Tutorial: Struts 2 Tiles Plugin Tutorial with Example in Eclipse</title>
		<link>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-tiles-plugin-tutorial-with-example-in-eclipse/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=struts-2-tutorial-struts-2-tiles-plugin-tutorial-with-example-in-eclipse</link>
		<comments>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-tiles-plugin-tutorial-with-example-in-eclipse/#comments</comments>
		<pubDate>Mon, 06 May 2013 10:11:15 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Java Tutorials]]></category>
		<category><![CDATA[Configuration file]]></category>
		<category><![CDATA[Data Formats]]></category>
		<category><![CDATA[Deployment descriptor]]></category>
		<category><![CDATA[JAR (file format)]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Markup Languages]]></category>
		<category><![CDATA[Web application]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2946</guid>
		<description><![CDATA[Introduction to Tiles 2 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 [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><h2>Introduction to Tiles 2</h2>
<p>Nowadays, website are generally divided into pieces of reusable template that are being rendered among different web pages. For example a site containing header, footer, menu etc. This items remains same through out the website and give it a common look and feel. It is very difficult to hard code this in each and every webpage and if later a change is needed than all the pages needs to be modified. Hence we use templatization mechanism. We create a common Header, Footer, Menu page and include this in each page.</p>
<p>Tiles Plugin allow both templating and componentization. In fact, both mechanisms are similar: you<br />
define parts of page (a “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. Tiles is a templating system used to maintain a consistent look and feel across all the web pages of a web application. It increase the reusability of template and reduce code duplication.</p>
<p>A common layout of website is defined in a central configuration file and this layout can be extended across all the webpages of the web application.</p>
<h2>Our Application Layout</h2>
<p>Our goal is to add Header, Footer and Menu to our StrutsHelloWorld application. Following will be the layout of the same.<br />
<img title="struts2-tiles-layout" alt="struts2-tiles-layout" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-tiles-layout1.gif?resize=359%2C321" data-recalc-dims="1" /></p>
<h2>Required JAR files</h2>
<p>In order to add Tiles support to our Struts2 application, we will need few jar files. Following is the list of JARs in our example. Add these JARs in WEB-INF/lib folder.<br />
<img title="struts2-tiles-jar-files" alt="struts2-tiles-jar-files" src="http://i2.wp.com/img.viralpatel.net/2009/12/struts2-tiles-jar-files.png?resize=205%2C240" data-recalc-dims="1" /></p>
<h2>Configuring Tiles in web.xml</h2>
<p>To configure Tiles, an entry for listener has to be made in web.xml. Open the web.xml from WEB-INF folder and add following code into it.</p>
<div id="highlighter_614509">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;</code><code>listener</code><code>&gt;</code></div>
<div><code>02.</code><code>&lt;</code><code>listener-class</code><code>&gt;</code></div>
<div><code>03.</code></div>
<div><code>04.</code><code>org.apache.struts2.tiles.StrutsTilesListener</code></div>
<div><code>05.</code><code>&lt;/</code><code>listener-class</code><code>&gt;</code></div>
<div><code>06.</code><code>&lt;/</code><code>listener</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>context-param</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>param-name</code><code>&gt;tilesDefinitions&lt;/</code><code>param-name</code><code>&gt;</code></div>
<div><code>09.</code><code>&lt;</code><code>param-value</code><code>&gt;/WEB-INF/tiles.xml&lt;/</code><code>param-value</code><code>&gt;</code></div>
<div><code>10.</code></div>
<div><code>11.</code><code>&lt;/</code><code>context-param</code><code>&gt;</code></div>
</div>
</div>
<p>The above code configure Tiles listener in web.xml. An input configuration file /WEB-INF/tiles.xml is passed as argument. This file contains the Tiles definition for our web application.</p>
<p>Create a file <strong>tiles.xml</strong> in WEB-INF folder and copy following code into it.<br />
<img title="struts2-tiles-xml" alt="struts2-tiles-xml" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-tiles-xml1.png?resize=129%2C104" data-recalc-dims="1" /></p>
<div id="highlighter_271982">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;?</code><code>xml</code> <code>version</code><code>=</code><code>"1.0"</code> <code>encoding</code><code>=</code><code>"UTF-8"</code> <code>?&gt;</code></div>
<div><code>02.</code></div>
<div><code>03.</code><code>&lt;!DOCTYPE tiles-definitions PUBLIC</code></div>
<div><code>04.</code><code>"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"</code></div>
<div><code>05.</code><code>"<a href="http://tiles.apache.org/dtds/tiles-config_2_0.dtd">http://tiles.apache.org/dtds/tiles-config_2_0.dtd</a>"&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>tiles-definitions</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"baseLayout"</code> <code>template</code><code>=</code><code>"/BaseLayout.jsp"</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>""</code> <code>/&gt;</code></div>
<div><code>09.</code></div>
<div><code>10.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"header"</code> <code>value</code><code>=</code><code>"/Header.jsp"</code> <code>/&gt;</code></div>
<div><code>11.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"menu"</code> <code>value</code><code>=</code><code>"/Menu.jsp"</code> <code>/&gt;</code></div>
<div><code>12.</code></div>
<div><code>13.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>""</code> <code>/&gt;</code></div>
<div><code>14.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"footer"</code> <code>value</code><code>=</code><code>"/Footer.jsp"</code> <code>/&gt;</code></div>
<div><code>15.</code></div>
<div><code>16.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>17.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"/welcome.tiles"</code> <code>extends</code><code>=</code><code>"baseLayout"</code><code>&gt;</code></div>
<div><code>18.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>"Welcome"</code> <code>/&gt;</code></div>
<div><code>19.</code></div>
<div><code>20.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>"/Welcome.jsp"</code> <code>/&gt;</code></div>
<div><code>21.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>22.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"/customer.tiles"</code> <code>extends</code><code>=</code><code>"baseLayout"</code><code>&gt;</code></div>
<div><code>23.</code></div>
<div><code>24.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>"Customer Form"</code> <code>/&gt;</code></div>
<div><code>25.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>"/Customer.jsp"</code> <code>/&gt;</code></div>
<div><code>26.</code></div>
<div><code>27.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>28.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"/customer.success.tiles"</code> <code>extends</code><code>=</code><code>"baseLayout"</code><code>&gt;</code></div>
<div><code>29.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>"Customer Added"</code> <code>/&gt;</code></div>
<div><code>30.</code></div>
<div><code>31.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>"/SuccessCustomer.jsp"</code> <code>/&gt;</code></div>
<div><code>32.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>33.</code><code>&lt;/</code><code>tiles-definitions</code><code>&gt;</code></div>
</div>
</div>
<p>Here in tiles.xml we have define a template <strong>baseLayout</strong>. This layout contains attributes such as Header, Title, Body, Menu and Footer. The layout is then extended and new definitions for Welcome page and Customer page is defined. We have override the default layout and changed the content for Body and Title.</p>
<h2>Creating JSPs</h2>
<p><img title="struts-2-tiles-layout-jsp" alt="struts-2-tiles-layout-jsp" src="http://i0.wp.com/img.viralpatel.net/2009/12/struts-2-tiles-layout-jsp.png?resize=168%2C193" data-recalc-dims="1" />We will define the template for our webapplication in a JSP file called BaseLayout.jsp. This template will contain different segments of web page (Header, Footer, Menu etc). Create 4 new JSP files BaseLayout.jsp, Header.jsp, Menu.jsp and Footer.jsp and copy following content in each of them.<br />
<strong>BaseLayout.jsp</strong></p>
<div id="highlighter_793740">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;%@ taglib uri="<a href="http://tiles.apache.org/tags-tiles">http://tiles.apache.org/tags-tiles</a>" prefix="tiles"%&gt;</code></div>
<div><code>02.</code><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"</code></div>
<div><code>03.</code></div>
<div><code>04.</code><code>"<a href="http://www.w3.org/TR/html4/loose.dtd">http://www.w3.org/TR/html4/loose.dtd</a>"&gt;</code></div>
<div><code>05.</code><code>&lt;</code><code>html</code><code>&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>head</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>meta</code> <code>http-equiv</code><code>=</code><code>"Content-Type"</code> <code>content</code><code>=</code><code>"text/html; charset=UTF-8"</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>title</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"title"</code> <code>ignore</code><code>=</code><code>"true"</code> <code>/&gt;&lt;/</code><code>title</code><code>&gt;</code></div>
<div><code>09.</code></div>
<div><code>10.</code><code>&lt;/</code><code>head</code><code>&gt;</code></div>
<div><code>11.</code><code>&lt;</code><code>body</code><code>&gt;</code></div>
<div><code>12.</code><code>&lt;</code><code>table</code> <code>border</code><code>=</code><code>"1"</code> <code>cellpadding</code><code>=</code><code>"2"</code> <code>cellspacing</code><code>=</code><code>"2"</code> <code>align</code><code>=</code><code>"center"</code><code>&gt;</code></div>
<div><code>13.</code><code>&lt;</code><code>tr</code><code>&gt;</code></div>
<div><code>14.</code></div>
<div><code>15.</code><code>&lt;</code><code>td</code> <code>height</code><code>=</code><code>"30"</code> <code>colspan</code><code>=</code><code>"2"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"header"</code> <code>/&gt;</code></div>
<div><code>16.</code><code>&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>17.</code><code>&lt;/</code><code>tr</code><code>&gt;</code></div>
<div><code>18.</code></div>
<div><code>19.</code><code>&lt;</code><code>tr</code><code>&gt;</code></div>
<div><code>20.</code><code>&lt;</code><code>td</code> <code>height</code><code>=</code><code>"250"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"menu"</code> <code>/&gt;&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>21.</code><code>&lt;</code><code>td</code> <code>width</code><code>=</code><code>"350"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"body"</code> <code>/&gt;&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>22.</code></div>
<div><code>23.</code><code>&lt;/</code><code>tr</code><code>&gt;</code></div>
<div><code>24.</code><code>&lt;</code><code>tr</code><code>&gt;</code></div>
<div><code>25.</code><code>&lt;</code><code>td</code> <code>height</code><code>=</code><code>"30"</code> <code>colspan</code><code>=</code><code>"2"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"footer"</code> <code>/&gt;</code></div>
<div><code>26.</code></div>
<div><code>27.</code><code>&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>28.</code><code>&lt;/</code><code>tr</code><code>&gt;</code></div>
<div><code>29.</code><code>&lt;/</code><code>table</code><code>&gt;</code></div>
<div><code>30.</code><code>&lt;/</code><code>body</code><code>&gt;</code></div>
<div><code>31.</code><code>&lt;/</code><code>html</code><code>&gt;</code></div>
</div>
</div>
<p><strong>Header.jsp</strong></p>
<div id="highlighter_281186">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>2.</code></div>
<div><code>3.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>4.</code><code>&lt;</code><code>h2</code><code>&gt;Struts2 Example - ViralPatel.net&lt;/</code><code>h2</code><code>&gt;</code></div>
</div>
</div>
<p><strong>Menu.jsp</strong></p>
<div id="highlighter_961501">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>2.</code></div>
<div><code>3.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>4.</code><code>&lt;</code><code>s:a</code> <code>href</code><code>=</code><code>"customer-form"</code><code>&gt;Customer&lt;/</code><code>s:a</code><code>&gt;</code></div>
</div>
</div>
<p><strong>Footer.jsp</strong></p>
<div id="highlighter_804153">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>2.</code></div>
<div><code>3.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>4.</code><code>Copyright &amp;copy; ViralPatel.net</code></div>
</div>
</div>
<h2>Modifications in Struts.xml</h2>
<p>In struts.xml we defined result tag which maps a particular action with a JSP page. Now we will modify it and map the result with Tiles. Following will be the content of struts.xml file.</p>
<div id="highlighter_501419">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;?</code><code>xml</code> <code>version</code><code>=</code><code>"1.0"</code> <code>encoding</code><code>=</code><code>"UTF-8"</code> <code>?&gt;</code></div>
<div><code>02.</code></div>
<div><code>03.</code><code>&lt;!DOCTYPE struts PUBLIC</code></div>
<div><code>04.</code><code>"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"</code></div>
<div><code>05.</code><code>"<a href="http://struts.apache.org/dtds/struts-2.0.dtd">http://struts.apache.org/dtds/struts-2.0.dtd</a>"&gt;</code></div>
<div><code>06.</code></div>
<div><code>07.</code><code>&lt;</code><code>struts</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>constant</code> <code>name</code><code>=</code><code>"struts.enable.DynamicMethodInvocation"</code></div>
<div><code>09.</code><code>value</code><code>=</code><code>"false"</code> <code>/&gt;</code></div>
<div><code>10.</code></div>
<div><code>11.</code><code>&lt;</code><code>constant</code> <code>name</code><code>=</code><code>"struts.devMode"</code> <code>value</code><code>=</code><code>"false"</code> <code>/&gt;</code></div>
<div><code>12.</code><code>&lt;</code><code>constant</code> <code>name</code><code>=</code><code>"struts.custom.i18n.resources"</code></div>
<div><code>13.</code><code>value</code><code>=</code><code>"ApplicationResources"</code> <code>/&gt;</code></div>
<div><code>14.</code></div>
<div><code>15.</code><code>&lt;</code><code>package</code> <code>name</code><code>=</code><code>"default"</code> <code>extends</code><code>=</code><code>"struts-default"</code> <code>namespace</code><code>=</code><code>"/"</code><code>&gt;</code></div>
<div><code>16.</code><code>&lt;</code><code>result-types</code><code>&gt;</code></div>
<div><code>17.</code><code>&lt;</code><code>result-type</code> <code>name</code><code>=</code><code>"tiles"</code></div>
<div><code>18.</code></div>
<div><code>19.</code><code>class</code><code>=</code><code>"org.apache.struts2.views.tiles.TilesResult"</code> <code>/&gt;</code></div>
<div><code>20.</code><code>&lt;/</code><code>result-types</code><code>&gt;</code></div>
<div><code>21.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"login"</code></div>
<div><code>22.</code><code>class</code><code>=</code><code>"net.viralpatel.struts2.LoginAction"</code><code>&gt;</code></div>
<div><code>23.</code></div>
<div><code>24.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/welcome.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>25.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"error"</code><code>&gt;Login.jsp&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>26.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
<div><code>27.</code></div>
<div><code>28.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"customer"</code></div>
<div><code>29.</code><code>class</code><code>=</code><code>"net.viralpatel.struts2.CustomerAction"</code><code>&gt;</code></div>
<div><code>30.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/customer.success.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>31.</code></div>
<div><code>32.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"input"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/customer.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>33.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
<div><code>34.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"customer-form"</code><code>&gt;</code></div>
<div><code>35.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/customer.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>36.</code></div>
<div><code>37.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
<div><code>38.</code><code>&lt;/</code><code>package</code><code>&gt;</code></div>
<div><code>39.</code><code>&lt;/</code><code>struts</code><code>&gt;</code></div>
</div>
</div>
<p>The struts.xml now defines a new Result type for Tiles. This result type is used in &lt;result&gt; tag for different actions. Also note that we have define a new action customer-form. This is just an empty declaration to redirect user to Customer form page when she clicks Customer link from menu.</p>
<h2>That’s All Folks</h2>
<p>Compile and Execute the application in Eclipse and see that the header, menu and footer are properly applied.<br />
<strong>Welcome Page with Tiles</strong><br />
<a href="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts3.png"><img class="alignnone size-medium wp-image-2905" alt="struts3" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts3.png?resize=300%2C282" data-recalc-dims="1" /></a><br />
<strong>Customer Page with Tiles</strong><br />
<a href="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2.png"><img class="alignnone size-medium wp-image-2904" alt="struts2" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2.png?resize=300%2C282" data-recalc-dims="1" /></a><br />
<strong>Customer Success Page with Tiles</strong><br />
<a href="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts1.png"><img class="alignnone size-medium wp-image-2903" alt="struts1" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts1.png?resize=300%2C282" data-recalc-dims="1" /></a></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-4-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (11KB)</strong></a></p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i0.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-tiles-plugin-tutorial-with-example-in-eclipse/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Struts 2 Tutorial: Struts 2 Validation Framework Tutorial with Example</title>
		<link>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-validation-framework-tutorial-with-example/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=struts-2-tutorial-struts-2-validation-framework-tutorial-with-example</link>
		<comments>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-validation-framework-tutorial-with-example/#comments</comments>
		<pubDate>Mon, 06 May 2013 10:07:44 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Java Tutorials]]></category>
		<category><![CDATA[Apache Struts]]></category>
		<category><![CDATA[Enterprise Edition]]></category>
		<category><![CDATA[Field (mathematics)]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[languages]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2934</guid>
		<description><![CDATA[Introduction to Struts2 Validation Framework Struts Action 2 relies on a validation framework provided by XWork to enable the application of input validation rules to your Actions before they are executed. Struts2 Validation Framework allows us to separate the validation logic from actual Java/JSP code, where it can be reviewed and easily modified later. The [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><h2>Introduction to Struts2 Validation Framework</h2>
<p>Struts Action 2 relies on a validation framework provided by XWork to enable the application of input validation rules to your Actions before they are executed. Struts2 Validation Framework allows us to separate the validation logic from actual Java/JSP code, where it can be reviewed and easily modified later.</p>
<p>The Struts2 Validation Framework alleviates much of the headache associated with handling data validation, allowing you to focus on validation code and not on the mechanics of capturing data and redisplaying incomplete or invalid data.</p>
<p>Validation framework comes with set of useful routines to handle form validation automatically and it can handle both <strong>server side</strong> as well as <strong>client side</strong> form validation. If certain validation is not present, you can create your own validation logic by implementing java interface com.opensymphony.xwork2.Validator and plug it into validation framework as a re-usable component.</p>
<p>Validator uses XML configuration files to determine which validation routines should be installed and how they should be applied for a given application. validators.xml file contains all common validators declaration. If validators.xml file is not present in classpath, a default validation file is loaded from path com/opensymphony/xwork2/validator/validators/default.xml.</p>
<p>The first configuration file, validator-rules.xml, declares the validation routines that should be plugged into the framework and provides logical names for each of the validations. The validator-rules.xml file also defines client-side JavaScript code for each validation routine. Validator can be configured to send this JavaScript code to the browser so that validations are performed on the client side as well as on the server side.</p>
<h2>Validators Scope</h2>
<p>There are two types of Validators in Struts2 Validation Framework.</p>
<ol>
<li>Field Validators</li>
<li>Non-field validators</li>
</ol>
<p><strong>Field validators</strong>, as the name indicate, act on single fields accessible through an action. A validator, in contrast, is more generic and can do validations in the full action context, involving more than one field (or even no field at all) in validation rule. Most validations can be defined on per field basis. This should be preferred over non-field validation wherever possible, as field validator messages are bound to the related field and will be presented next to the corresponding input element in the respecting view.</p>
<div id="highlighter_345076">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;</code><code>validators</code><code>&gt;</code></div>
<div><code>2.</code><code>&lt;</code><code>field</code> <code>name</code><code>=</code><code>"bar"</code><code>&gt;</code></div>
<div><code>3.</code><code>&lt;</code><code>field-validator</code> <code>type</code><code>=</code><code>"required"</code><code>&gt;</code></div>
<div><code>4.</code><code>&lt;</code><code>message</code><code>&gt;You must enter a value for bar.&lt;/</code><code>message</code><code>&gt;</code></div>
<div><code>5.</code><code>&lt;/</code><code>field-validator</code><code>&gt;</code></div>
<div><code>6.</code></div>
<div><code>7.</code><code>&lt;/</code><code>field</code><code>&gt;</code></div>
<div><code>8.</code><code>&lt;/</code><code>validators</code><code>&gt;</code></div>
</div>
</div>
<p><strong>Non-field validators</strong> only add action level messages. Non-field validators are mostly domain specific and therefore offer custom implementations. The most important standard non-field validator provided by XWork is ExpressionValidator.</p>
<div id="highlighter_694898">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;</code><code>validators</code><code>&gt;</code></div>
<div><code>2.</code><code>&lt;</code><code>validator</code> <code>type</code><code>=</code><code>"expression"</code><code>&gt;</code></div>
<div><code>3.</code></div>
<div><code>4.</code><code>&lt;</code><code>param</code> <code>name</code><code>=</code><code>"expression"</code><code>&gt;foo lt bar&lt;/</code><code>param</code><code>&gt;</code></div>
<div><code>5.</code><code>&lt;</code><code>message</code><code>&gt;Foo must be greater than Bar.&lt;/</code><code>message</code><code>&gt;</code></div>
<div><code>6.</code><code>&lt;/</code><code>validator</code><code>&gt;</code></div>
<div><code>7.</code><code>&lt;/</code><code>validators</code><code>&gt;</code></div>
</div>
</div>
<h2>Getting Started</h2>
<p>Let us add validation logic to StrutsHelloWorld application that we created in previous article. For this tutorial, we will create an Action class called <strong>CustomerAction</strong> which will contain few fields. Create a file CustomerAction.java in package net.viralpatel.struts2.<br />
<img title="customer-action-struts2" alt="customer-action-struts2" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/customer-action-struts2.png?resize=226%2C106" data-recalc-dims="1" /><br />
Copy following content into it.<br />
<strong>CustomerAction.java</strong></p>
<div id="highlighter_125020">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>package</code> <code>net.viralpatel.struts2;</code></div>
<div><code>02.</code></div>
<div><code>03.</code><code>import</code> <code>com.opensymphony.xwork2.ActionSupport;</code></div>
<div><code>04.</code></div>
<div><code>05.</code><code>public</code> <code>class</code> <code>CustomerAction </code><code>extends</code> <code>ActionSupport{</code></div>
<div><code>06.</code><code>private</code> <code>String name;</code></div>
<div><code>07.</code><code>private</code> <code>Integer age;</code></div>
<div><code>08.</code><code>private</code> <code>String email;</code></div>
<div><code>09.</code><code>private</code> <code>String telephone;</code></div>
<div><code>10.</code></div>
<div><code>11.</code><code>public</code> <code>String addCustomer() {</code></div>
<div><code>12.</code><code>return</code> <code>SUCCESS;</code></div>
<div><code>13.</code><code>}</code></div>
<div><code>14.</code></div>
<div><code>15.</code><code>public</code> <code>String getName() {</code></div>
<div><code>16.</code><code>return</code> <code>name;</code></div>
<div><code>17.</code><code>}</code></div>
<div><code>18.</code><code>public</code> <code>void</code> <code>setName(String name) {</code></div>
<div><code>19.</code><code>this</code><code>.name = name;</code></div>
<div><code>20.</code><code>}</code></div>
<div><code>21.</code><code>public</code> <code>Integer getAge() {</code></div>
<div><code>22.</code><code>return</code> <code>age;</code></div>
<div><code>23.</code><code>}</code></div>
<div><code>24.</code><code>public</code> <code>void</code> <code>setAge(Integer age) {</code></div>
<div><code>25.</code><code>this</code><code>.age = age;</code></div>
<div><code>26.</code><code>}</code></div>
<div><code>27.</code><code>public</code> <code>String getEmail() {</code></div>
<div><code>28.</code><code>return</code> <code>email;</code></div>
<div><code>29.</code><code>}</code></div>
<div><code>30.</code><code>public</code> <code>void</code> <code>setEmail(String email) {</code></div>
<div><code>31.</code><code>this</code><code>.email = email;</code></div>
<div><code>32.</code><code>}</code></div>
<div><code>33.</code><code>public</code> <code>String getTelephone() {</code></div>
<div><code>34.</code><code>return</code> <code>telephone;</code></div>
<div><code>35.</code><code>}</code></div>
<div><code>36.</code><code>public</code> <code>void</code> <code>setTelephone(String telephone) {</code></div>
<div><code>37.</code><code>this</code><code>.telephone = telephone;</code></div>
<div><code>38.</code><code>}</code></div>
<div><code>39.</code><code>}</code></div>
</div>
</div>
<p>Note that CustomerAction class has fields name, email, telephone and age. Also it has a method called addCustomer() which doesn’t have any logic, it just return SUCCESS.</p>
<p>Now we will add entry for this new action class in <strong>struts.xml</strong> file. Open the struts.xml file which will be present under resources folder. And add following content between &lt;package&gt;&lt;/package&gt; tag.</p>
<div id="highlighter_132516">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"customer"</code></div>
<div><code>2.</code><code>class</code><code>=</code><code>"net.viralpatel.struts2.CustomerAction"</code><code>&gt;</code></div>
<div><code>3.</code></div>
<div><code>4.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code><code>&gt;SuccessCustomer.jsp&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>5.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"input"</code><code>&gt;Customer.jsp&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>6.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
</div>
</div>
<p>Note that we are mapping the CustomerAction class with name customer. Also on success user will be redirected to SuccessCustomer.jsp page. Notice that there is another result tag with name input. Whenever the validation logic encounter some validation error, it redirects the user back to page specified as input. Thus in our example, user will be redirected back to Customer.jsp in case of any errors.</p>
<p>Create two new JSPs Customer.jsp (which will contain Customer form) and SuccessCustomer.jsp (which will be displayed on success).<br />
<img title="struts2-validation-jsp-files" alt="struts2-validation-jsp-files" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-validation-jsp-files.png?resize=170%2C121" data-recalc-dims="1" /><br />
<strong>Customer.jsp</strong></p>
<div id="highlighter_376811">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>02.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>03.</code></div>
<div><code>04.</code><code>&lt;</code><code>html</code><code>&gt;</code></div>
<div><code>05.</code><code>&lt;</code><code>head</code><code>&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>title</code><code>&gt;Customer Form - Struts2 Demo | ViralPatel.net&lt;/</code><code>title</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;/</code><code>head</code><code>&gt;</code></div>
<div><code>08.</code></div>
<div><code>09.</code><code>&lt;</code><code>body</code><code>&gt;</code></div>
<div><code>10.</code><code>&lt;</code><code>h2</code><code>&gt;Customer Form&lt;/</code><code>h2</code><code>&gt;</code></div>
<div><code>11.</code></div>
<div><code>12.</code><code>&lt;</code><code>s:form</code> <code>action</code><code>=</code><code>"customer.action"</code> <code>method</code><code>=</code><code>"post"</code><code>&gt;</code></div>
<div><code>13.</code><code>&lt;</code><code>s:textfield</code> <code>name</code><code>=</code><code>"name"</code> <code>key</code><code>=</code><code>"name"</code> <code>size</code><code>=</code><code>"20"</code> <code>/&gt;</code></div>
<div><code>14.</code></div>
<div><code>15.</code><code>&lt;</code><code>s:textfield</code> <code>name</code><code>=</code><code>"age"</code> <code>key</code><code>=</code><code>"age"</code> <code>size</code><code>=</code><code>"20"</code> <code>/&gt;</code></div>
<div><code>16.</code><code>&lt;</code><code>s:textfield</code> <code>name</code><code>=</code><code>"email"</code> <code>key</code><code>=</code><code>"email"</code> <code>size</code><code>=</code><code>"20"</code> <code>/&gt;</code></div>
<div><code>17.</code></div>
<div><code>18.</code><code>&lt;</code><code>s:textfield</code> <code>name</code><code>=</code><code>"telephone"</code> <code>key</code><code>=</code><code>"telephone"</code> <code>size</code><code>=</code><code>"20"</code> <code>/&gt;</code></div>
<div><code>19.</code><code>&lt;</code><code>s:submit</code> <code>method</code><code>=</code><code>"addCustomer"</code> <code>key</code><code>=</code><code>"label.add.customer"</code> <code>align</code><code>=</code><code>"center"</code> <code>/&gt;</code></div>
<div><code>20.</code></div>
<div><code>21.</code><code>&lt;/</code><code>s:form</code><code>&gt;</code></div>
<div><code>22.</code><code>&lt;/</code><code>body</code><code>&gt;</code></div>
<div><code>23.</code><code>&lt;/</code><code>html</code><code>&gt;</code></div>
</div>
</div>
<p><strong>SuccessCustomer.jsp</strong></p>
<div id="highlighter_129814">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>02.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>03.</code></div>
<div><code>04.</code><code>&lt;</code><code>html</code><code>&gt;</code></div>
<div><code>05.</code><code>&lt;</code><code>head</code><code>&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>title</code><code>&gt;Customer Page - Struts2 Demo | ViralPatel.net&lt;/</code><code>title</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;/</code><code>head</code><code>&gt;</code></div>
<div><code>08.</code></div>
<div><code>09.</code><code>&lt;</code><code>body</code><code>&gt;</code></div>
<div><code>10.</code><code>&lt;</code><code>h2</code><code>&gt;Customer Added Successfully.&lt;/</code><code>h2</code><code>&gt;</code></div>
<div><code>11.</code></div>
<div><code>12.</code><code>&lt;/</code><code>body</code><code>&gt;</code></div>
<div><code>13.</code><code>&lt;/</code><code>html</code><code>&gt;</code></div>
</div>
</div>
<p>We have created Customer.jsp file which will display Customer form. But we don’t have link to this page from our web application. So we will create a link to Customer.jsp from Welcome.jsp page. Open Welcome.jsp page and add following link code into it.</p>
<div id="highlighter_823737">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;</code><code>s:a</code> <code>href</code><code>=</code><code>"Customer.jsp"</code><code>&gt;Add Customer&lt;/</code><code>s:a</code><code>&gt;</code></div>
</div>
</div>
<p>Now open the ApplicationResources.properties file from /resources folder and add following key/values in it.</p>
<div id="highlighter_626298">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>name= Name</code></div>
<div><code>02.</code><code>age= Age</code></div>
<div><code>03.</code><code>email= Email</code></div>
<div><code>04.</code><code>telephone= Telephone</code></div>
<div><code>05.</code><code>label.add.customer=Add Customer</code></div>
<div><code>06.</code></div>
<div><code>07.</code><code>errors.invalid=${getText(fieldName)} is invalid.</code></div>
<div><code>08.</code><code>errors.required=${getText(fieldName)} is required.</code></div>
<div><code>09.</code><code>errors.number=${getText(fieldName)} must be a number.</code></div>
<div><code>10.</code><code>errors.range=${getText(fieldName)} is not in the range ${min} and ${max}.</code></div>
</div>
</div>
<p>Execute the code in Eclipse and see the output. You will see login page. Enter username=admin and password=admin123 and do login. On welcome page you will see a link to Add Customer page. Click on that link and you will see Customer page.<br />
<img title="struts2-customer-form" alt="struts2-customer-form" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-customer-form.png?resize=412%2C306" data-recalc-dims="1" /></p>
<h2>Adding Validation Logic</h2>
<p>Now we are ready with the basic customer form on which we will add the validation logic. Following will be the validations rules:</p>
<ol>
<li>Name field is mandatory</li>
<li>Age field is mandatory. It should be a number between 1 and 100.</li>
<li>Email field is mandatory. It should be a valid email address.</li>
<li>Telephone is mandatory.</li>
</ol>
<p>In order to define validation logic for particular form, we first have to create an XML file which will hold this data. Struts2 define a specific naming convention in defining validation xml files. The format is <strong>&lt;ActionClassName&gt;-validation.xml</strong>. So for our application we will create a file <strong>CustomerAction-validation.xml</strong>. Note that this file should be present in the same package as of action class.<br />
Create file CustomerAction-validation.xml in package net.viralpatel.struts2. And copy following content into it.<br />
<img title="struts2-validation-xml" alt="struts2-validation-xml" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-validation-xml.png?resize=273%2C130" data-recalc-dims="1" /><br />
<strong>CustomerAction-validation.xml</strong></p>
<div id="highlighter_222075">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;?</code><code>xml</code> <code>version</code><code>=</code><code>"1.0"</code> <code>encoding</code><code>=</code><code>"UTF-8"</code><code>?&gt;</code></div>
<div><code>02.</code></div>
<div><code>03.</code><code>&lt;!DOCTYPE validators PUBLIC</code></div>
<div><code>04.</code><code>"-//OpenSymphony Group//XWork Validator 1.0.2//EN"</code></div>
<div><code>05.</code><code>"<a href="http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd</a>"&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>validators</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>field</code> <code>name</code><code>=</code><code>"name"</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>field-validator</code> <code>type</code><code>=</code><code>"requiredstring"</code><code>&gt;</code></div>
<div><code>09.</code><code>&lt;</code><code>param</code> <code>name</code><code>=</code><code>"trim"</code><code>&gt;true&lt;/</code><code>param</code><code>&gt;</code></div>
<div><code>10.</code></div>
<div><code>11.</code><code>&lt;</code><code>message</code> <code>key</code><code>=</code><code>"errors.required"</code> <code>/&gt;</code></div>
<div><code>12.</code><code>&lt;/</code><code>field-validator</code><code>&gt;</code></div>
<div><code>13.</code><code>&lt;/</code><code>field</code><code>&gt;</code></div>
<div><code>14.</code><code>&lt;</code><code>field</code> <code>name</code><code>=</code><code>"age"</code><code>&gt;</code></div>
<div><code>15.</code><code>&lt;</code><code>field-validator</code> <code>type</code><code>=</code><code>"required"</code><code>&gt;</code></div>
<div><code>16.</code></div>
<div><code>17.</code><code>&lt;</code><code>message</code> <code>key</code><code>=</code><code>"errors.required"</code> <code>/&gt;</code></div>
<div><code>18.</code><code>&lt;/</code><code>field-validator</code><code>&gt;</code></div>
<div><code>19.</code><code>&lt;</code><code>field-validator</code> <code>type</code><code>=</code><code>"int"</code><code>&gt;</code></div>
<div><code>20.</code><code>&lt;</code><code>param</code> <code>name</code><code>=</code><code>"min"</code><code>&gt;1&lt;/</code><code>param</code><code>&gt;</code></div>
<div><code>21.</code></div>
<div><code>22.</code><code>&lt;</code><code>param</code> <code>name</code><code>=</code><code>"max"</code><code>&gt;100&lt;/</code><code>param</code><code>&gt;</code></div>
<div><code>23.</code><code>&lt;</code><code>message</code> <code>key</code><code>=</code><code>"errors.range"</code><code>/&gt;</code></div>
<div><code>24.</code><code>&lt;/</code><code>field-validator</code><code>&gt;</code></div>
<div><code>25.</code><code>&lt;/</code><code>field</code><code>&gt;</code></div>
<div><code>26.</code></div>
<div><code>27.</code><code>&lt;</code><code>field</code> <code>name</code><code>=</code><code>"email"</code><code>&gt;</code></div>
<div><code>28.</code><code>&lt;</code><code>field-validator</code> <code>type</code><code>=</code><code>"requiredstring"</code><code>&gt;</code></div>
<div><code>29.</code><code>&lt;</code><code>message</code> <code>key</code><code>=</code><code>"errors.required"</code> <code>/&gt;</code></div>
<div><code>30.</code><code>&lt;/</code><code>field-validator</code><code>&gt;</code></div>
<div><code>31.</code></div>
<div><code>32.</code><code>&lt;</code><code>field-validator</code> <code>type</code><code>=</code><code>"email"</code><code>&gt;</code></div>
<div><code>33.</code><code>&lt;</code><code>message</code> <code>key</code><code>=</code><code>"errors.invalid"</code> <code>/&gt;</code></div>
<div><code>34.</code><code>&lt;/</code><code>field-validator</code><code>&gt;</code></div>
<div><code>35.</code><code>&lt;/</code><code>field</code><code>&gt;</code></div>
<div><code>36.</code><code>&lt;</code><code>field</code> <code>name</code><code>=</code><code>"telephone"</code><code>&gt;</code></div>
<div><code>37.</code></div>
<div><code>38.</code><code>&lt;</code><code>field-validator</code> <code>type</code><code>=</code><code>"requiredstring"</code><code>&gt;</code></div>
<div><code>39.</code><code>&lt;</code><code>message</code> <code>key</code><code>=</code><code>"errors.required"</code> <code>/&gt;</code></div>
<div><code>40.</code><code>&lt;/</code><code>field-validator</code><code>&gt;</code></div>
<div><code>41.</code><code>&lt;/</code><code>field</code><code>&gt;</code></div>
<div><code>42.</code><code>&lt;/</code><code>validators</code><code>&gt;</code></div>
</div>
</div>
<p>And that’s it. We just added validation logic to our example. Note that the validations xml file contains different field-validators.</p>
<h2>Client Side Validation</h2>
<p>It is very easy to add Client Side validation or JavaScript validation to any form in Struts2. All you have to do is to add <strong>validate=”true”</strong> in form tag in your JSP file. For example open Customer.jsp and add validate=”true” in form tag. Struts2 automatically generates the JavaScript code for client side validation of form.</p>
<div id="highlighter_324770">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-37#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-37#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-37#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;</code><code>s:form</code> <code>action</code><code>=</code><code>"customer.action"</code> <code>method</code><code>=</code><code>"post"</code> <code>validate</code><code>=</code><code>"true"</code><code>&gt;</code></div>
<div><code>2.</code></div>
<div><code>3.</code><code>...</code></div>
<div><code>4.</code><code>&lt;/</code><code>s:form</code><code>&gt;</code></div>
</div>
</div>
<h2>That’s All Folks</h2>
<p>Execute the application and test the Customer form with different values.<br />
<strong>Customer page</strong><br />
<img title="struts2-customer-form" alt="struts2-customer-form" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-customer-form.png?resize=412%2C306" data-recalc-dims="1" /><br />
<strong>Customer page with errors</strong><br />
<img title="customer-page-validation-errors" alt="customer-page-validation-errors" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/customer-page-validation-errors.png?resize=412%2C382" data-recalc-dims="1" /><br />
<strong>Customer page on success</strong><br />
<img title="customer-page-success" alt="customer-page-success" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/customer-page-success.png?resize=426%2C204" data-recalc-dims="1" /></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-3-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (9KB)</strong></a></p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i2.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-validation-framework-tutorial-with-example/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Struts 2 Tutorial</title>
		<link>http://latest-tutorial.com/2013/05/06/struts-2-tutorial/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=struts-2-tutorial</link>
		<comments>http://latest-tutorial.com/2013/05/06/struts-2-tutorial/#comments</comments>
		<pubDate>Mon, 06 May 2013 09:41:38 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Java Tutorials]]></category>
		<category><![CDATA[Apache]]></category>
		<category><![CDATA[Apache Struts]]></category>
		<category><![CDATA[Data Formats]]></category>
		<category><![CDATA[Enterprise Edition]]></category>
		<category><![CDATA[JAR (file format)]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[languages]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2901</guid>
		<description><![CDATA[Struts 2 Tiles Plugin Tutorial with Example in Eclipse Welcome to Part-4 of the 7-part series where we will go through different aspects for Struts2 Framework with some useful examples. In previous part we went through Struts2 Validation Framework. We saw how easy it is to integrate validation in your struts2 application. In this part [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><h1>Struts 2 Tiles Plugin Tutorial with Example in Eclipse</h1>
<p>Welcome to Part-4 of the 7-part series where we will go through different aspects for Struts2 Framework with some useful examples. In previous part we went through <strong>Struts2 Validation Framework</strong>. We saw how easy it is to integrate validation in your struts2 application.</p>
<p>In this part we will discuss about Tiles Framework and its Integration with Struts2. We will add Tiles support to our HelloWorld Struts application that we created in previous parts. I strongly recommend you to go through previous articles and download the source code of our sample application.</p>
<h2>Struts 2 Tutorial List</h2>
<ul>
<li><a href="http://latest-tutorial.com/?p=2902">Part 1: Introduction to Struts 2 Framework</a></li>
<li><a href="http://latest-tutorial.com/?p=2917">Part 2: Create Hello World Application in Struts 2</a></li>
<li><a href="http://latest-tutorial.com/?p=2934">Part 3: Struts 2 Validation Framework Tutorial with Example</a></li>
<li><a href=" http://latest-tutorial.com/?p=2946">Part 4: Struts 2 Tiles Plugin Tutorial with Example</a></li>
<li><a href="http://latest-tutorial.com/?p=2955">Part 5: Struts 2 Interceptors Tutorial with Example</a></li>
<li><a href="http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-file-upload-and-save-tutorial-with-example/">Part 6: Struts 2 File Upload and Save Example</a></li>
<li><a href="http://latest-tutorial.com/2013/05/06/struts-2-tutorial-struts-2-ajax-tutorial-with-example/">Part 7: Struts 2 Ajax Tutorial with Example</a></li>
</ul>
<h2>Introduction to Tiles 2</h2>
<p>Nowadays, website are generally divided into pieces of reusable template that are being rendered among different web pages. For example a site containing header, footer, menu etc. This items remains same through out the website and give it a common look and feel. It is very difficult to hard code this in each and every webpage and if later a change is needed than all the pages needs to be modified. Hence we use templatization mechanism. We create a common Header, Footer, Menu page and include this in each page.</p>
<p>Tiles Plugin allow both templating and componentization. In fact, both mechanisms are similar: you<br />
define parts of page (a “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. Tiles is a templating system used to maintain a consistent look and feel across all the web pages of a web application. It increase the reusability of template and reduce code duplication.</p>
<p>A common layout of website is defined in a central configuration file and this layout can be extended across all the webpages of the web application.</p>
<h2>Our Application Layout</h2>
<p>Our goal is to add Header, Footer and Menu to our StrutsHelloWorld application. Following will be the layout of the same.<br />
<img title="struts2-tiles-layout" alt="struts2-tiles-layout" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-tiles-layout.gif?resize=359%2C321" data-recalc-dims="1" /></p>
<h2>Required JAR files</h2>
<p>In order to add Tiles support to our Struts2 application, we will need few jar files. Following is the list of JARs in our example. Add these JARs in WEB-INF/lib folder.<br />
<img title="struts2-tiles-jar-files" alt="struts2-tiles-jar-files" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-tiles-jar-files.png?resize=205%2C240" data-recalc-dims="1" /></p>
<h2>Configuring Tiles in web.xml</h2>
<p>To configure Tiles, an entry for listener has to be made in web.xml. Open the web.xml from WEB-INF folder and add following code into it.</p>
<div id="highlighter_415951">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;</code><code>listener</code><code>&gt;</code></div>
<div><code>02.</code><code>&lt;</code><code>listener-class</code><code>&gt;</code></div>
<div><code>03.</code></div>
<div><code>04.</code><code>org.apache.struts2.tiles.StrutsTilesListener</code></div>
<div><code>05.</code><code>&lt;/</code><code>listener-class</code><code>&gt;</code></div>
<div><code>06.</code><code>&lt;/</code><code>listener</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>context-param</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>param-name</code><code>&gt;tilesDefinitions&lt;/</code><code>param-name</code><code>&gt;</code></div>
<div><code>09.</code><code>&lt;</code><code>param-value</code><code>&gt;/WEB-INF/tiles.xml&lt;/</code><code>param-value</code><code>&gt;</code></div>
<div><code>10.</code></div>
<div><code>11.</code><code>&lt;/</code><code>context-param</code><code>&gt;</code></div>
</div>
</div>
<p>The above code configure Tiles listener in web.xml. An input configuration file /WEB-INF/tiles.xml is passed as argument. This file contains the Tiles definition for our web application.</p>
<p>Create a file <strong>tiles.xml</strong> in WEB-INF folder and copy following code into it.<br />
<img title="struts2-tiles-xml" alt="struts2-tiles-xml" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2-tiles-xml.png?resize=129%2C104" data-recalc-dims="1" /></p>
<div id="highlighter_297521">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;?</code><code>xml</code> <code>version</code><code>=</code><code>"1.0"</code> <code>encoding</code><code>=</code><code>"UTF-8"</code> <code>?&gt;</code></div>
<div><code>02.</code></div>
<div><code>03.</code><code>&lt;!DOCTYPE tiles-definitions PUBLIC</code></div>
<div><code>04.</code><code>"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"</code></div>
<div><code>05.</code><code>"<a href="http://tiles.apache.org/dtds/tiles-config_2_0.dtd">http://tiles.apache.org/dtds/tiles-config_2_0.dtd</a>"&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>tiles-definitions</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"baseLayout"</code> <code>template</code><code>=</code><code>"/BaseLayout.jsp"</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>""</code> <code>/&gt;</code></div>
<div><code>09.</code></div>
<div><code>10.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"header"</code> <code>value</code><code>=</code><code>"/Header.jsp"</code> <code>/&gt;</code></div>
<div><code>11.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"menu"</code> <code>value</code><code>=</code><code>"/Menu.jsp"</code> <code>/&gt;</code></div>
<div><code>12.</code></div>
<div><code>13.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>""</code> <code>/&gt;</code></div>
<div><code>14.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"footer"</code> <code>value</code><code>=</code><code>"/Footer.jsp"</code> <code>/&gt;</code></div>
<div><code>15.</code></div>
<div><code>16.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>17.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"/welcome.tiles"</code> <code>extends</code><code>=</code><code>"baseLayout"</code><code>&gt;</code></div>
<div><code>18.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>"Welcome"</code> <code>/&gt;</code></div>
<div><code>19.</code></div>
<div><code>20.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>"/Welcome.jsp"</code> <code>/&gt;</code></div>
<div><code>21.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>22.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"/customer.tiles"</code> <code>extends</code><code>=</code><code>"baseLayout"</code><code>&gt;</code></div>
<div><code>23.</code></div>
<div><code>24.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>"Customer Form"</code> <code>/&gt;</code></div>
<div><code>25.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>"/Customer.jsp"</code> <code>/&gt;</code></div>
<div><code>26.</code></div>
<div><code>27.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>28.</code><code>&lt;</code><code>definition</code> <code>name</code><code>=</code><code>"/customer.success.tiles"</code> <code>extends</code><code>=</code><code>"baseLayout"</code><code>&gt;</code></div>
<div><code>29.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"title"</code> <code>value</code><code>=</code><code>"Customer Added"</code> <code>/&gt;</code></div>
<div><code>30.</code></div>
<div><code>31.</code><code>&lt;</code><code>put-attribute</code> <code>name</code><code>=</code><code>"body"</code> <code>value</code><code>=</code><code>"/SuccessCustomer.jsp"</code> <code>/&gt;</code></div>
<div><code>32.</code><code>&lt;/</code><code>definition</code><code>&gt;</code></div>
<div><code>33.</code><code>&lt;/</code><code>tiles-definitions</code><code>&gt;</code></div>
</div>
</div>
<p>Here in tiles.xml we have define a template <strong>baseLayout</strong>. This layout contains attributes such as Header, Title, Body, Menu and Footer. The layout is then extended and new definitions for Welcome page and Customer page is defined. We have override the default layout and changed the content for Body and Title.</p>
<h2>Creating JSPs</h2>
<p><img title="struts-2-tiles-layout-jsp" alt="struts-2-tiles-layout-jsp" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts-2-tiles-layout-jsp.png?resize=168%2C193" data-recalc-dims="1" />We will define the template for our webapplication in a JSP file called BaseLayout.jsp. This template will contain different segments of web page (Header, Footer, Menu etc). Create 4 new JSP files BaseLayout.jsp, Header.jsp, Menu.jsp and Footer.jsp and copy following content in each of them.<br />
<strong>BaseLayout.jsp</strong></p>
<div id="highlighter_137598">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;%@ taglib uri="<a href="http://tiles.apache.org/tags-tiles">http://tiles.apache.org/tags-tiles</a>" prefix="tiles"%&gt;</code></div>
<div><code>02.</code><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"</code></div>
<div><code>03.</code></div>
<div><code>04.</code><code>"<a href="http://www.w3.org/TR/html4/loose.dtd">http://www.w3.org/TR/html4/loose.dtd</a>"&gt;</code></div>
<div><code>05.</code><code>&lt;</code><code>html</code><code>&gt;</code></div>
<div><code>06.</code><code>&lt;</code><code>head</code><code>&gt;</code></div>
<div><code>07.</code><code>&lt;</code><code>meta</code> <code>http-equiv</code><code>=</code><code>"Content-Type"</code> <code>content</code><code>=</code><code>"text/html; charset=UTF-8"</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>title</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"title"</code> <code>ignore</code><code>=</code><code>"true"</code> <code>/&gt;&lt;/</code><code>title</code><code>&gt;</code></div>
<div><code>09.</code></div>
<div><code>10.</code><code>&lt;/</code><code>head</code><code>&gt;</code></div>
<div><code>11.</code><code>&lt;</code><code>body</code><code>&gt;</code></div>
<div><code>12.</code><code>&lt;</code><code>table</code> <code>border</code><code>=</code><code>"1"</code> <code>cellpadding</code><code>=</code><code>"2"</code> <code>cellspacing</code><code>=</code><code>"2"</code> <code>align</code><code>=</code><code>"center"</code><code>&gt;</code></div>
<div><code>13.</code><code>&lt;</code><code>tr</code><code>&gt;</code></div>
<div><code>14.</code></div>
<div><code>15.</code><code>&lt;</code><code>td</code> <code>height</code><code>=</code><code>"30"</code> <code>colspan</code><code>=</code><code>"2"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"header"</code> <code>/&gt;</code></div>
<div><code>16.</code><code>&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>17.</code><code>&lt;/</code><code>tr</code><code>&gt;</code></div>
<div><code>18.</code></div>
<div><code>19.</code><code>&lt;</code><code>tr</code><code>&gt;</code></div>
<div><code>20.</code><code>&lt;</code><code>td</code> <code>height</code><code>=</code><code>"250"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"menu"</code> <code>/&gt;&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>21.</code><code>&lt;</code><code>td</code> <code>width</code><code>=</code><code>"350"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"body"</code> <code>/&gt;&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>22.</code></div>
<div><code>23.</code><code>&lt;/</code><code>tr</code><code>&gt;</code></div>
<div><code>24.</code><code>&lt;</code><code>tr</code><code>&gt;</code></div>
<div><code>25.</code><code>&lt;</code><code>td</code> <code>height</code><code>=</code><code>"30"</code> <code>colspan</code><code>=</code><code>"2"</code><code>&gt;&lt;</code><code>tiles:insertAttribute</code> <code>name</code><code>=</code><code>"footer"</code> <code>/&gt;</code></div>
<div><code>26.</code></div>
<div><code>27.</code><code>&lt;/</code><code>td</code><code>&gt;</code></div>
<div><code>28.</code><code>&lt;/</code><code>tr</code><code>&gt;</code></div>
<div><code>29.</code><code>&lt;/</code><code>table</code><code>&gt;</code></div>
<div><code>30.</code><code>&lt;/</code><code>body</code><code>&gt;</code></div>
<div><code>31.</code><code>&lt;/</code><code>html</code><code>&gt;</code></div>
</div>
</div>
<p><strong>Header.jsp</strong></p>
<div id="highlighter_169137">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>2.</code></div>
<div><code>3.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>4.</code><code>&lt;</code><code>h2</code><code>&gt;Struts2 Example - ViralPatel.net&lt;/</code><code>h2</code><code>&gt;</code></div>
</div>
</div>
<p><strong>Menu.jsp</strong></p>
<div id="highlighter_539457">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>2.</code></div>
<div><code>3.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>4.</code><code>&lt;</code><code>s:a</code> <code>href</code><code>=</code><code>"customer-form"</code><code>&gt;Customer&lt;/</code><code>s:a</code><code>&gt;</code></div>
</div>
</div>
<p><strong>Footer.jsp</strong></p>
<div id="highlighter_45553">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>1.</code><code>&lt;%@ page contentType="text/html; charset=UTF-8"%&gt;</code></div>
<div><code>2.</code></div>
<div><code>3.</code><code>&lt;%@ taglib prefix="s" uri="/struts-tags"%&gt;</code></div>
<div><code>4.</code><code>Copyright &amp;copy; ViralPatel.net</code></div>
</div>
</div>
<h2>Modifications in Struts.xml</h2>
<p>In struts.xml we defined result tag which maps a particular action with a JSP page. Now we will modify it and map the result with Tiles. Following will be the content of struts.xml file.</p>
<div id="highlighter_630968">
<div>
<div><a title="view source" href="http://java.dzone.com/articles/struts2-tutorial-part-47#viewSource">view source</a><a title="print" href="http://java.dzone.com/articles/struts2-tutorial-part-47#printSource">print</a><a title="?" href="http://java.dzone.com/articles/struts2-tutorial-part-47#about">?</a></div>
</div>
<div>
<div><code>01.</code><code>&lt;?</code><code>xml</code> <code>version</code><code>=</code><code>"1.0"</code> <code>encoding</code><code>=</code><code>"UTF-8"</code> <code>?&gt;</code></div>
<div><code>02.</code></div>
<div><code>03.</code><code>&lt;!DOCTYPE struts PUBLIC</code></div>
<div><code>04.</code><code>"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"</code></div>
<div><code>05.</code><code>"<a href="http://struts.apache.org/dtds/struts-2.0.dtd">http://struts.apache.org/dtds/struts-2.0.dtd</a>"&gt;</code></div>
<div><code>06.</code></div>
<div><code>07.</code><code>&lt;</code><code>struts</code><code>&gt;</code></div>
<div><code>08.</code><code>&lt;</code><code>constant</code> <code>name</code><code>=</code><code>"struts.enable.DynamicMethodInvocation"</code></div>
<div><code>09.</code><code>value</code><code>=</code><code>"false"</code> <code>/&gt;</code></div>
<div><code>10.</code></div>
<div><code>11.</code><code>&lt;</code><code>constant</code> <code>name</code><code>=</code><code>"struts.devMode"</code> <code>value</code><code>=</code><code>"false"</code> <code>/&gt;</code></div>
<div><code>12.</code><code>&lt;</code><code>constant</code> <code>name</code><code>=</code><code>"struts.custom.i18n.resources"</code></div>
<div><code>13.</code><code>value</code><code>=</code><code>"ApplicationResources"</code> <code>/&gt;</code></div>
<div><code>14.</code></div>
<div><code>15.</code><code>&lt;</code><code>package</code> <code>name</code><code>=</code><code>"default"</code> <code>extends</code><code>=</code><code>"struts-default"</code> <code>namespace</code><code>=</code><code>"/"</code><code>&gt;</code></div>
<div><code>16.</code><code>&lt;</code><code>result-types</code><code>&gt;</code></div>
<div><code>17.</code><code>&lt;</code><code>result-type</code> <code>name</code><code>=</code><code>"tiles"</code></div>
<div><code>18.</code></div>
<div><code>19.</code><code>class</code><code>=</code><code>"org.apache.struts2.views.tiles.TilesResult"</code> <code>/&gt;</code></div>
<div><code>20.</code><code>&lt;/</code><code>result-types</code><code>&gt;</code></div>
<div><code>21.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"login"</code></div>
<div><code>22.</code><code>class</code><code>=</code><code>"net.viralpatel.struts2.LoginAction"</code><code>&gt;</code></div>
<div><code>23.</code></div>
<div><code>24.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/welcome.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>25.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"error"</code><code>&gt;Login.jsp&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>26.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
<div><code>27.</code></div>
<div><code>28.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"customer"</code></div>
<div><code>29.</code><code>class</code><code>=</code><code>"net.viralpatel.struts2.CustomerAction"</code><code>&gt;</code></div>
<div><code>30.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/customer.success.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>31.</code></div>
<div><code>32.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"input"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/customer.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>33.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
<div><code>34.</code><code>&lt;</code><code>action</code> <code>name</code><code>=</code><code>"customer-form"</code><code>&gt;</code></div>
<div><code>35.</code><code>&lt;</code><code>result</code> <code>name</code><code>=</code><code>"success"</code> <code>type</code><code>=</code><code>"tiles"</code><code>&gt;/customer.tiles&lt;/</code><code>result</code><code>&gt;</code></div>
<div><code>36.</code></div>
<div><code>37.</code><code>&lt;/</code><code>action</code><code>&gt;</code></div>
<div><code>38.</code><code>&lt;/</code><code>package</code><code>&gt;</code></div>
<div><code>39.</code><code>&lt;/</code><code>struts</code><code>&gt;</code></div>
</div>
</div>
<p>The struts.xml now defines a new Result type for Tiles. This result type is used in &lt;result&gt; tag for different actions. Also note that we have define a new action customer-form. This is just an empty declaration to redirect user to Customer form page when she clicks Customer link from menu.</p>
<h2>That’s All Folks</h2>
<p>Compile and Execute the application in Eclipse and see that the header, menu and footer are properly applied.<br />
<strong>Welcome Page with Tiles</strong><br />
<a href="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts3.png"><img class="alignnone size-medium wp-image-2905" alt="struts3" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts3.png?resize=300%2C282" data-recalc-dims="1" /></a><br />
<strong>Customer Page with Tiles</strong><br />
<a href="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2.png"><img class="alignnone size-medium wp-image-2904" alt="struts2" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts2.png?resize=300%2C282" data-recalc-dims="1" /></a><br />
<strong>Customer Success Page with Tiles</strong><br />
<a href="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts1.png"><img class="alignnone size-medium wp-image-2903" alt="struts1" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/struts1.png?resize=300%2C282" data-recalc-dims="1" /></a></p>
<h2>Download Source Code</h2>
<p><a href="http://viralpatel.net/blogs/download/struts/Part-4-StrutsHelloWorld.zip"><strong>Click here to download Source Code without JAR files (11KB)</strong></a></p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i0.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/05/06/struts-2-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to the Struts Web Framework</title>
		<link>http://latest-tutorial.com/2013/05/02/introduction-to-the-struts-web-framework/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=introduction-to-the-struts-web-framework</link>
		<comments>http://latest-tutorial.com/2013/05/02/introduction-to-the-struts-web-framework/#comments</comments>
		<pubDate>Thu, 02 May 2013 07:52:26 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Java Tutorials]]></category>
		<category><![CDATA[Apache Struts]]></category>
		<category><![CDATA[GlassFish]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java Servlet]]></category>
		<category><![CDATA[JavaBeans]]></category>
		<category><![CDATA[JavaServer Pages]]></category>
		<category><![CDATA[NetBeans]]></category>
		<category><![CDATA[Struts in netbeans]]></category>
		<category><![CDATA[Struts tutorial using netbeans]]></category>
		<category><![CDATA[Struts Web Framework]]></category>
		<category><![CDATA[Struts Web Framework tutorial]]></category>
		<category><![CDATA[Web application]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2849</guid>
		<description><![CDATA[This document takes you through the basics of using NetBeans IDE to develop web applications using the Struts web framework. Struts is an open source framework that extends the Java Servlet API and employs a Model, View, Controller (MVC) architecture. It enables you to create maintainable, extensible, and flexible web applications based on standard technologies, [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><p><img class="zemanta-img-inserted zemanta-img-configured alignright" title="English: Logo of Apache Struts" alt="English: Logo of Apache Struts" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/Struts_logo.gif?resize=166%2C77" data-recalc-dims="1" /><br />
This document takes you through the basics of using NetBeans IDE to develop web applications using the Struts web framework. Struts is an open source framework that extends the Java Servlet API and employs a <a href="http://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/web-tier/web-tier5.html">Model, View, Controller</a> (MVC) architecture. It enables you to create maintainable, extensible, and flexible web applications based on standard technologies, such as JSP pages, JavaBeans, resource bundles, and XML.</p>
<p>This tutorial teaches you how to build a simple MVC application that displays a login page and returns a success page upon submitting data that passes validation. You learn several basic features provided by Struts, as well as how these features are implemented using the IDE. Specifically, you use Struts tags in JSP pages, maintain user data with a Struts <code>ActionForm</code> bean, and implement forwarding logic using a Struts <code>Action</code> object. You are also shown how to implement simple validation to your application, including setting up warning message for a failed login attempt.</p>
<p><strong>Notes:</strong></p>
<ul>
<li>The Java installation enables you to optionally install the GlassFish server and the Apache Tomcat servlet container. You must install one of these (or register a different server in the IDE) to work through this tutorial.</li>
<li>If you need to compare your project with a working solution, you can <a href="http://netbeans.org/projects/samples/downloads/download/Samples%252FJava%2520Web%252FMyStrutsApp.zip">download the sample application</a>.</li>
</ul>
<p><a name="overview"></a></p>
<h2>Overview of the Application</h2>
<p>When you use Struts, the framework provides you with a controller servlet, <code>ActionServlet</code>, which is defined in the Struts libraries that are included in the IDE, and which is automatically registered in the <code>web.xml</code> deployment descriptor as <a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#controllerServlet">shown below</a>. The controller servlet uses a <code>struts-config.xml</code> file to map incoming requests to Struts <code>Action</code> objects, and instantiate any <code>ActionForm</code> objects associated with the action to temporarily store form data. The <code>Action</code> object processes requests using its <code>execute</code> method, while making use of any data stored in the form bean. Once the <code>Action</code> object processes a request, it stores any new data (i.e., in the form bean, or in a separate result bean), and forwards the results to the appropriate view.</p>
<div><img title="Struts workflow" alt="Struts workflow" src="https://netbeans.org/images_www/articles/70/web/struts/workflow.png" /></div>
<p>Developing a Struts application is similar to developing any other kind of web application in NetBeans IDE. However, you complement your web development toolkit by taking advantage of the Struts support provided by the IDE. For example, you use templates in the IDE to create Struts <code>Action</code> objects and <code>ActionForm</code> beans. Upon creation, the IDE automatically registers these classes in the <code>struts-config.xml</code> file and lets you extend this file very easily using menu items in the Source Editor&#8217;s right-click menu. Because many web applications use JSP pages for the view, Struts also provides custom tag libraries which facilitate interaction with HTML forms. Within the IDE&#8217;s Source Editor, you can invoke code completion and Javadoc support that helps you to work efficiently with these libraries.</p>
<p>The following steps demonstrate how to create a simple form that collects user data, performs simple validation, and outputs the data on a success page.</p>
<p><a name="set"></a></p>
<h2>Setting Up a Struts Application</h2>
<p>In the IDE, a Struts application is nothing more than a normal web application accompanied by the Struts libraries and configuration files. You create a Struts application in the same way as you create any other web application in the IDE &#8211; using the New Web Application wizard, with the additional step of indicating that you want the Struts libraries and configuration files to be included in your application.</p>
<ol>
<li>Choose File &gt; New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Java Web in the list of Categories and then select Web Application in the list of Projects. Click Next.</li>
<li>In the Name and Location panel, enter <code>MyStrutsApp</code> for Project Name and click Next.</li>
<li>In the Server and Settings panel, select the server to which you want to deploy your application. Only servers that are registered with the IDE are listed. (To register a server, click Add next to the Server drop-down list.) Also, note that the Context Path to your deployed application becomes <code>/MyStrutsApp</code>. Click Next.</li>
<li>Select Struts in the Frameworks panel.<br />
<img title="Struts option displays in Frameworks panel of New Web Application wizard" alt="Struts option displayed in Frameworks panel of New Web Application wizard" src="https://netbeans.org/images_www/articles/70/web/struts/new-project-wizard.png" />For purposes of this tutorial, do not change any of the configuration values in the lower region of this panel. The wizard displays the following configuration options.</p>
<ul>
<li><strong>Action Servlet Name</strong>: The name of the Struts action servlet used in the application. The <code>web.xml</code> deployment descriptor contains an entry for the action servlet and specifies the appropriate Struts-specific parameters, such as the path to the servlet class within the Struts library and to the <code>struts-config.xml</code> configuration file within the application.</li>
<li><strong>Action URL Pattern</strong>: Specifies the patterns of incoming requests which are mapped to the Struts action controller. This generates a mapping entry in the deployment descriptor. By default, only the <code>*.do</code> pattern is mapped.</li>
<li><strong>Application Resource</strong>: Lets you specify the resource bundle which will be used in the <code>struts-config.xml</code> file for localizing messages. By default, this is <code>com.myapp.struts.ApplicationResource</code>.</li>
<li><strong>Add Struts TLDs</strong>: Lets you generate tag library descriptors for the Struts tag libraries. A tag library descriptor is an XML document which contains additional information about the entire tag library as well as each individual tag. In general this is not necessary, because you can refer to on-line URIs rather than local TLD files.</li>
</ul>
</li>
<li>Click Finish. The IDE creates the project folder in your file system. As with any web application in the IDE, the project folder contains all of your sources and the IDE&#8217;s project metadata, such as the Ant build script. However, your web application in addition has all of the Struts libraries on its classpath. Not only are they on the application&#8217;s classpath, but they are included in the project and will be packaged with it later when you build the project.</li>
</ol>
<p>The project opens in the IDE. The Projects window is the main entry point to your project sources. It shows a logical view of important project contents. For example, if you expand several nodes within the new project, it may appear as follows:</p>
<div><img title="Projects window displays MyStrutsApp project" alt="Projects window containing newly created project" src="https://netbeans.org/images_www/articles/70/web/struts/proj-window-init.png" /></div>
<p><strong>Note: </strong>Use the Files window (Window &gt; Files) to see all of your project contents in a directory-based view.</p>
<p><a name="controllerServlet"></a>The Struts-specific configuration files, as well as the application&#8217;s deployment descriptor, are conveniently placed within the Configuration Files folder. Open the deployment descriptor (double-click the <code>web.xml</code> file node to have it display in the Source Editor). In order to handle Struts processing, a mapping is provided for the Struts controller servlet.</p>
<pre>&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>Above, the Struts controller servlet is named <code>action</code> and is defined in the Struts library (<code>org.apache.struts.action.ActionServlet</code>). It is set to handle all requests that satisfy the <code>*.do</code> mapping. In addition, initialization parameters for the servlet are specified by means of the <code>struts-config.xml</code> file, also contained in the <code>WEB-INF</code> folder.</p>
<p><a name="jsp"></a></p>
<h2>Creating JSP Pages</h2>
<p>Begin by creating two JSP pages for the application. The first displays a form. The second is the view returned when login is successful.</p>
<ul>
<li><a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#login">Creating a Login Page</a></li>
<li><a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#success">Creating a Success Page</a></li>
</ul>
<div>
<p><a name="login"></a></p>
<h3>Creating a Login Page</h3>
<ol>
<li>Right-click the <code>MyStrutsApp</code> project node, choose New &gt; JSP, and name the new file <code>login</code>. Click Finish. The <code>login.jsp</code> file opens in the Source Editor.</li>
<li>In the Source Editor, change the content of both the <code>&lt;title&gt;</code> and <code>&lt;h1&gt;</code> tags (or <code>&lt;h2&gt;</code> tags, depending on the IDE version you are using) to <code>Login Form</code>.</li>
<li>Add the following two taglib directives to the top of the file:
<pre>&lt;%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %&gt;
&lt;%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %&gt;</pre>
<p>Many web applications use JSP pages for views in the MVC paradigm, so Struts provides custom tag libraries which facilitate interaction with HTML forms. These can be easily applied to a JSP file using the IDE&#8217;s support for code completion. When you type in the Source Editor, the IDE provides you with code completion for Struts tags, as well as the Struts Javadoc. You can also invoke code completion manually by pressing Ctrl-Space:<br />
<img title="Code completion and Javadoc are supplied for Struts tags" alt="Code completion and Javadoc for Struts tags provided in Source Editor" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/code-completion.png" data-recalc-dims="1" /><br />
The <a href="http://struts.apache.org/1.3.10/struts-taglib/dev_bean.html">bean taglib</a> provides you with numerous tags that are helpful when associating a form bean (i.e., an <code>ActionForm</code> bean) with the data collected from the form. The <a href="http://struts.apache.org/1.3.10/struts-taglib/dev_html.html">html taglib</a> offers an interface between the view and other components necessary to a web application. For example, below you replace common html <code>form</code> tags with Struts&#8217; <code>&lt;html:form&gt;</code> tags. One benefit this provides is that it causes the server to locate or create a bean object that corresponds to the value provided for <code>html:form</code>&#8216;s <code>action</code> element.</li>
<li>Below the <code>&lt;h1&gt;</code> (or <code>&lt;h2&gt;</code>) tags, add the following:
<pre>&lt;html:form action="/login"&gt;

   &lt;html:submit value="Login" /&gt;

&lt;/html:form&gt;</pre>
<p>Whenever you finish typing in the Source Editor, you can tidy up the code by right-clicking and choosing Format (Alt-Shift-F).</li>
<li>In the Palette (Window &gt; Palette) in the right region of the IDE, drag a Table item from the HTML category to a point just above the <code>&lt;html:submit value="Login" /&gt;</code> line. The Insert Table dialog box displays. Set the rows to <code>3</code>, columns to <code>2</code>, and leave all other settings at <code>0</code>. Later in the tutorial, you will <a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#style">attach a stylesheet</a> to affect the table display.<br />
<img title="The Palette provides dialogs for easy-to-use code templates" alt="Create Table dialog displayed in Source Editor" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/insert-table.png" data-recalc-dims="1" /><br />
Click OK, then optionally reformat the code (Alt-Shift-F). The form in <code>login.jsp</code> now looks as follows:</p>
<pre>&lt;html:form action="/login"&gt;
    &lt;table border="0"&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;&lt;/th&gt;
                &lt;th&gt;&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
            &lt;tr&gt;
                &lt;td&gt;&lt;/td&gt;
                &lt;td&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;&lt;/td&gt;
                &lt;td&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;&lt;/td&gt;
                &lt;td&gt;&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;

    &lt;html:submit value="Login" /&gt;

&lt;/html:form&gt;</pre>
<p><strong>Note: </strong>You can safely delete the <code>&lt;thead&gt;</code> table row, as it is not used in this tutorial.</li>
<li>In the first table row, enter the following (changes in <strong>bold</strong>):
<pre>&lt;tr&gt;
    &lt;td&gt;<strong>Enter your name:</strong>&lt;/td&gt;
    &lt;td&gt;<strong>&lt;html:text property="name" /&gt;</strong>&lt;/td&gt;
&lt;/tr&gt;</pre>
</li>
<li>In the second table row, enter the following (changes in <strong>bold</strong>):
<pre>&lt;tr&gt;
    &lt;td&gt;<strong>Enter your email:</strong>&lt;/td&gt;
    &lt;td&gt;<strong>&lt;html:text property="email" /&gt;</strong>&lt;/td&gt;
&lt;/tr&gt;</pre>
<p>The <code>html:text</code> element enables you to match the input fields from the form with properties in the form bean that will be created in the next step. So for example, the value of <code>property</code> must match a field declared in the form bean associated with this form.</li>
<li>Move the &lt;html:submit value=&#8221;Login&#8221; /&gt; element into the second column of the third table row, so that the third table row appears as follows (changes in <strong>bold</strong>):
<pre>&lt;tr&gt;
    &lt;td&gt;&lt;/td&gt;
    &lt;td&gt;<strong>&lt;html:submit value="Login" /&gt;</strong>&lt;/td&gt;
&lt;/tr&gt;</pre>
</li>
</ol>
<p>At this stage, your login form should look as follows:</p>
<pre>&lt;html:form action="/login"&gt;
    &lt;table border="0"&gt;
        &lt;tbody&gt;
            &lt;tr&gt;
                &lt;td&gt;Enter your name:&lt;/td&gt;
                &lt;td&gt;&lt;html:text property="name" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;Enter your email:&lt;/td&gt;
                &lt;td&gt;&lt;html:text property="email" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
            &lt;tr&gt;
                &lt;td&gt;&lt;/td&gt;
                &lt;td&gt;&lt;html:submit value="Login" /&gt;&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/html:form&gt;</pre>
<p><a name="success"></a></p>
<h3>Creating a Success Page</h3>
<ol>
<li>Right-click the <code>MyStrutsApp</code> project node, choose New &gt; JSP, and name the new file <code>success</code>. In the Folder field, click the adjacent Browse button and select <code>WEB-INF</code> from the dialog that displays. Click Select Folder to enter WEB-INF in the Folder field. Any files contained in the WEB-INF folder are not directly accessible to client requests. In order for <code>success.jsp</code> to be properly displayed, it must contain processed data. Click Finish.</li>
<li>In the Source Editor, change the content of the newly created page to the following:
<pre>&lt;head&gt;
    &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
    &lt;title&gt;Login Success&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;h1&gt;Congratulations!&lt;/h1&gt;

    &lt;p&gt;You have successfully logged in.&lt;/p&gt;

    &lt;p&gt;Your name is: .&lt;/p&gt;

    &lt;p&gt;Your email address is: .&lt;/p&gt;
&lt;/body&gt;</pre>
</li>
<li>Add a <a href="http://struts.apache.org/1.3.10/struts-taglib/dev_bean.html">bean taglib</a> directive to the top of the file:
<pre>&lt;%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %&gt;</pre>
</li>
<li>Add the following <code>&lt;bean:write&gt;</code> tags (changes in <strong>bold</strong>):
<pre>&lt;p&gt;Your name is: <strong>&lt;bean:write name="LoginForm" property="name" /&gt;</strong>.&lt;/p&gt;

&lt;p&gt;Your email address is: <strong>&lt;bean:write name="LoginForm" property="email" /&gt;</strong>.&lt;/p&gt;</pre>
<p>By employing the <code>&lt;bean:write&gt;</code> tags, you make use of the bean taglib to locate the <code>ActionForm</code> bean you are about to create, and display the user data saved for <code>name</code> and <code>email</code>.</li>
</ol>
</div>
<p><a name="actionForm"></a></p>
<h2>Creating an <code>ActionForm</code> Bean</h2>
<p>A Struts <code>ActionForm</code> bean is used to persist data between requests. For example, if a user submits a form, the data is temporarily stored in the form bean so that it can either be redisplayed in the form page (if the data is in an invalid format or if login fails) or displayed in a login success page (if data passes validation).</p>
<ol>
<li>Right-click the <code>MyStrutsApp</code> project node and choose New &gt; Other. Under Categories choose Struts, then under File Types choose Struts ActionForm Bean. Click Next.</li>
<li>Type in <code>LoginForm</code> for the Class Name. Then select <code>com.myapp.struts</code> in the Package drop-down list and click Finish.The IDE creates the <code>LoginForm</code> bean and opens it in the Source Editor. By default, the IDE provides it with a <code>String</code> called <code>name</code> and an <code>int</code> called <code>number</code>. Both fields have accessor methods defined for them. Also, the IDE adds a bean declaration to the <code>struts-config.xml</code> file. If you open the <code>struts-config.xml</code> file in the Source Editor, you can see the following declaration, which was added by the wizard:
<pre>&lt;form-beans&gt;
    <strong>&lt;form-bean name="LoginForm" type="com.myapp.struts.LoginForm" /&gt;</strong>
&lt;/form-beans&gt;</pre>
<p>The IDE provides navigation support in the <code>struts-config.xml</code> file. Hold down the Ctrl key and hover your mouse over the <code>LoginForm</code> bean&#8217;s fully qualified class name. The name becomes a link, enabling you to navigate directly to the class in the Source Editor:</p>
<p><img title="Navigation support is provided in struts-config.xml" alt="Navigation support displayed in Struts config file" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/navigation-support.png" data-recalc-dims="1" /></li>
<li>In the <code>LoginForm</code> bean in the Source Editor, create fields and accompanying accessor methods that correspond to the <code>name</code> and <code>email</code> text input fields that you created in <code>login.jsp</code>. Because <code>name</code> has already been created in the <code>LoginForm</code> skeleton, you only need to implement <code>email</code>.Add the following declaration beneath <code>name</code> (changes in <strong>bold</strong>):
<pre>private String name;
<strong>private String email;</strong></pre>
<p><a name="accessors"></a></p>
<p>To create accessor methods, place your cursor on <code>email</code> and press Alt-Insert.</p>
<p><img title="Insert Code menu displays when pressing Ctrl-I in Source Editor" alt="Insert Code menu displayed in Source Editor" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/create-accessors.png" data-recalc-dims="1" /></p>
<p>Select Getter and Setter, then in the dialog that displays, select <code>email : String</code> and click Generate. Accessor methods are generated for the <code>email</code> field.</p>
<p><strong>Note: </strong>You can delete the declaration and accessor methods for <code>number</code>, as it is not used in this tutorial.</li>
</ol>
<p><a name="actionClass"></a></p>
<h2>Creating an <code>Action</code> Class</h2>
<p>The <code>Action</code> class contains the business logic in the application. When form data is received, it is the <code>execute</code> method of an <code>Action</code> object that processes the data and determines which view to forward the processed data to. Because the <code>Action</code> class is integral to the Struts framework, NetBeans IDE provides you with a wizard.</p>
<ol>
<li>In the Projects window, right-click the <code>MyStrutsApp</code> project node and choose New &gt; Other. From the Struts category choose Struts Action and click Next.</li>
<li>In the Name and Location panel, change the name to <code>LoginAction</code>.</li>
<li>Select <code>com.myapp.struts</code> in the Package drop-down list.</li>
<li>Type <code>/login</code> in Action Path. This value must match the value you set for the <code>action</code> attribute of the <code>&lt;html:form&gt;</code> tags in <code>login.jsp</code>. Make sure settings appear as in the screenshot below, then click Next.<br />
<img title="New Struts Action wizard" alt="New Struts Action wizard" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/new-struts-action.png" data-recalc-dims="1" /></li>
<li>In the third step of the wizard, you are given the opportunity to associate the <code>Action</code> class with a form bean. Notice that the <code>LoginForm</code> bean you previously created is listed as an option for ActionForm Bean Name. Make the following adjustments to the panel:
<ul>
<li>Delete the forward slash for the Input Resource field</li>
<li>Set Scope to Request (Session is the default scope setting in Struts.)</li>
<li>Deselect the Validate ActionForm Bean option</li>
</ul>
<p>Click Finish. The <code>LoginAction</code> class is generated, and the file opens in the Source Editor. Also note that the following <code>action</code> entry is added to the <code>struts-config.xml</code> file:</p>
<pre>&lt;action-mappings&gt;
    <strong>&lt;action name="LoginForm" path="/login" scope="request" type="com.myapp.struts.LoginAction" validate="false"/&gt;</strong>
    &lt;action path="/Welcome" forward="/welcomeStruts.jsp"/&gt;
&lt;/action-mappings&gt;</pre>
<p>The <code>name</code> and <code>scope</code> attributes apply to the form bean that is associated with the action. Specifically, when an incoming request matches <code>/login</code>, the Struts framework automatically instantiates a <code>LoginForm</code> object and populates it with the form data sent in the request. The default value of <code>validate</code> is set to <code>true</code>. This tells the framework to call the <code>validate</code> method of the form bean. You deselected this option in the wizard however because you will hand-code simple validation in the next step, which does not require the <code>validate</code> method.</li>
</ol>
<p><a name="validate"></a></p>
<h2>Implementing Validation</h2>
<p>In the Source Editor, browse through the <code>LoginAction</code> class and look at the <code>execute</code> method:</p>
<pre>public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws Exception {

    return mapping.findForward(SUCCESS);
}</pre>
<p>Notice the definition of <code>SUCCESS</code>, listed beneath the <code>LoginAction</code> class declaration:</p>
<pre>private final static String SUCCESS = "success";</pre>
<p>Currently, the <code>mapping.findForward</code> method is set to unconditionally forward any request to an output view called <code>success</code>. This is not really desirable; you want to first perform some sort of validation on the incoming data to determine whether to send the <code>success</code> view, or any different view.</p>
<ul>
<li><a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#beanData">Accessing Bean Data and Preparing a Forwarding Condition</a></li>
<li><a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#errorMsg">Setting Up an Error Message</a></li>
</ul>
<div>
<p><a name="beanData"></a></p>
<h3>Accessing Bean Data and Preparing a Forwarding Condition</h3>
<ol>
<li>Type in the following code within the body of the <code>execute</code> method:
<pre>// extract user data
LoginForm formBean = (LoginForm)form;
String name = formBean.getName();
String email = formBean.getEmail();</pre>
<p>In order to use the incoming form data, you need to take <code>execute</code>&#8216;s <code>ActionForm</code> argument and cast it as <code>LoginForm</code>, then apply the getter methods that you created earlier.</li>
<li>Type in the following conditional clause to perform validation on the incoming data:
<pre>// perform validation
if ((name == null) ||             // name parameter does not exist
    email == null  ||             // email parameter does not exist
    name.equals("") ||            // name parameter is empty
    email.indexOf("@") == -1) {   // email lacks '@'

    return mapping.findForward(FAILURE);
}</pre>
<p>At this stage, the <code>execute</code> method should look as follows:</p>
<pre>public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    // extract user data
    LoginForm formBean = (LoginForm) form;
    String name = formBean.getName();
    String email = formBean.getEmail();

    // perform validation
    if ((name == null) || // name parameter does not exist
            email == null || // email parameter does not exist
            name.equals("") || // name parameter is empty
            email.indexOf("@") == -1) {   // email lacks '@'

        return mapping.findForward(FAILURE);
    }

    return mapping.findForward(SUCCESS);
}</pre>
</li>
<li>Add a declaration for <code>FAILURE</code> to the <code>LoginAction</code> class (changes in <strong>bold</strong>):
<pre>private final static String SUCCESS = "success";
<strong>private final static String FAILURE = "failure";</strong></pre>
</li>
</ol>
<p>Using the above logic, the <code>execute</code> method forwards the request to the <code>success</code> view if the user provides an entry for both <code>name</code> and <code>email</code> fields, and the email entered contains an &#8216;@&#8217; sign. Otherwise, the <code>failure</code> view is forwarded. As will be demonstrated below in <a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#forward">Adding <code>forward</code> Entries to <code>struts-config.xml</code></a>, you can set the <code>failure</code> view to point back to the form page, so that the user has another chance to enter data in the correct format.</p>
<p><a name="errorMsg"></a></p>
<h3>Setting Up an Error Message</h3>
<p>If the login form is returned, it would be good to inform the user that validation failed. You can accomplish this by adding an <code>error</code> field in the form bean, and an appropriate <code>&lt;bean:write&gt;</code> tag to the form in <code>login.jsp</code>. Finally, in the <code>Action</code> object, set the error message to be displayed in the event that the <code>failure</code> view is chosen.</p>
<ol>
<li>Open <code>LoginForm</code> and add an <code>error</code> field to the class:
<pre>// error message
private String error;</pre>
</li>
<li>Add a getter method and a setter method for <code>error</code>, as <a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#accessors">demonstrated above</a>.</li>
<li>Modify the setter method so that it appears as follows:
<pre>public void setError() {
    this.error =
        "&lt;span style='color:red'&gt;Please provide valid entries for both fields&lt;/span&gt;";
}</pre>
</li>
<li>Open <code>login.jsp</code> and make the following changes:
<pre>&lt;html:form action="/login"&gt;
    &lt;table border="0"&gt;
        &lt;tbody&gt;
            <strong>&lt;tr&gt;
                &lt;td colspan="2"&gt;
                    &lt;bean:write name="LoginForm" property="error" filter="false"/&gt;
                    &amp;nbsp;&lt;/td&gt;
            &lt;/tr&gt;</strong>
            &lt;tr&gt;
                &lt;td&gt;Enter your name:&lt;/td&gt;
                &lt;td&gt;&lt;html:text property="name" /&gt;&lt;/td&gt;
            &lt;/tr&gt;</pre>
</li>
<li>In <code>LoginAction</code>, within the <code>if</code> conditional clause, add a statement to set the error message before forwarding the <code>failure</code> condition (changes in <strong>bold</strong>):
<pre>if ((name == null) ||             // name parameter does not exist
    email == null  ||             // email parameter does not exist
    name.equals("") ||            // name parameter is empty
    email.indexOf("@") == -1) {   // email lacks '@'

    <strong>formBean.setError();</strong>
    return mapping.findForward(FAILURE);
}</pre>
</li>
</ol>
<p>Your completed <code>LoginAction</code> class should now appear as follows:</p>
<pre>public class LoginAction extends org.apache.struts.action.Action {

    private final static String SUCCESS = "success";
    private final static String FAILURE = "failure";

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        // extract user data
        LoginForm formBean = (LoginForm)form;
        String name = formBean.getName();
        String email = formBean.getEmail();

        // perform validation
        if ((name == null) ||             // name parameter does not exist
            email == null  ||             // email parameter does not exist
            name.equals("") ||            // name parameter is empty
            email.indexOf("@") == -1) {   // email lacks '@'

            formBean.setError();
            return mapping.findForward(FAILURE);
        }

        return mapping.findForward(SUCCESS);

    }
}</pre>
</div>
<p><a name="forward"></a></p>
<h2>Adding <code>forward</code> Entries to <code>struts-config.xml</code></h2>
<p>In order for the application to match JSP pages with forwarding conditions returned by <code>LoginAction</code>&#8216;s <code>execute</code> method, you need to add <code>forward</code> entries to the <code>struts-config.xml</code> file.</p>
<ol>
<li>Open <code>struts-config.xml</code> in the Source Editor, right-click anywhere in the <code>action</code> entry for <code>LoginForm</code>, and choose Struts &gt; Add Forward.<br />
<img title="Right-click and choose Struts &gt; Add Forward" alt="Struts options displayed in right-click menu of struts-config.xml" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/add-forward.png" data-recalc-dims="1" /></li>
<li>In the Add Forward dialog box, type <code>success</code> in Forward Name. Enter the path to <code>success.jsp</code> in the Resource File field (i.e., <code>/WEB-INF/success.jsp</code>). The dialog box should now look as follows:<br />
<img title="Add Forward dialog creates a forward entry in struts-config.xml" alt="Add Forward dialog" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/add-forward-dialog.png" data-recalc-dims="1" /><br />
Click Add. Note that the following <code>forward</code> entry was added to <code>struts-config.xml</code> (changes in <strong>bold</strong>):</p>
<pre>&lt;action name="LoginForm" path="/login" scope="request" type="com.myapp.struts.LoginAction" validate="false"&gt;
    <strong>&lt;forward name="success" path="/WEB-INF/success.jsp"/&gt;</strong>
&lt;/action&gt;</pre>
</li>
<li>Perform the same action to add a forward entry for <code>failure</code>. Set the Resource File path to <code>/login.jsp</code>. The following <code>forward</code> entry is added to <code>struts-config.xml</code> (changes in <strong>bold</strong>):
<pre>&lt;forward name="success" path="/WEB-INF/success.jsp"/&gt;
<strong>&lt;forward name="failure" path="/login.jsp"/&gt;</strong></pre>
</li>
</ol>
<p><a name="configure"></a></p>
<h2>Configuring and Running the Application</h2>
<p>The IDE uses an Ant build script to build and run your web application. The IDE generated the build script when you created the project, basing it on the options you entered in the New Project wizard. Before you build and run the application, you need to set the application&#8217;s default entry point to <code>login.jsp</code>. Optionally, you can also add a simple stylesheet to the project.</p>
<ul>
<li><a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#welcome">Setting the Welcome Page</a></li>
<li><a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#style">Attaching a Stylesheet</a></li>
<li><a href="https://netbeans.org/kb/docs/web/quickstart-webapps-struts.html#run">Running the Application</a></li>
</ul>
<p><a name="welcome"></a></p>
<h3>Setting the Welcome Page</h3>
<ol>
<li>In the Projects window, double-click the <code>web.xml</code> deployment descriptor. The tabs listed along the top of the Source Editor provide you with an interface to the <code>web.xml</code> file. Click on the Pages tab. In the Welcome Files field, enter <code>login.jsp</code>.<br />
<img title="Graphical editor for the application's deployment descriptor" alt="deployment descriptor interface" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/welcome-files.png" data-recalc-dims="1" /><br />
Now click on the Source tab to view the file. Note that <code>login.jsp</code> is now listed in the <code>welcome-file</code> entry:</p>
<pre>&lt;welcome-file&gt;login.jsp&lt;/welcome-file&gt;</pre>
</li>
</ol>
<p><a name="style"></a></p>
<h3>Attaching a Stylesheet</h3>
<ol>
<li>Add a simple stylesheet to the project. One easy way to do this is by saving <a href="http://www.netbeans.org/files/documents/4/2228/stylesheet.css">this sample stylesheet</a> to your computer. Copy the file (Ctrl-C), then in the IDE, select the Web Pages node in the Projects window and press Ctrl-V). The file is added to your project.</li>
<li>Link the stylesheet to your JSP pages by adding a reference between the <code>&lt;head&gt;</code> tags of both <code>login.jsp</code> and <code>success.jsp</code>:
<pre>&lt;link rel="stylesheet" type="text/css" href="stylesheet.css"&gt;</pre>
</li>
</ol>
<p><a name="run"></a></p>
<h3>Running the Application</h3>
<ol>
<li>In the Projects window, right-click the project node and choose Run. The IDE builds the web application and deploys it, using the server you specified when creating the project. The browser opens and displays the <code>login.jsp</code> page. Type in some data that should fail validation, i.e., either leave either field blank, or enter an email address with a missing &#8216;@&#8217; sign:<br />
<img title="Form contains data that will fail validation" alt="login.jsp displayed in browser with sample data" src="http://i0.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/login-form.png" data-recalc-dims="1" />When you click Login, the login form page redisplays, containing an error message:<br />
<img title="Form redisplays with error message" alt="login.jsp with error message displayed" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/login-form-error.png" data-recalc-dims="1" />Try entering data that should pass validation. Upon clicking Login, you are presented with the success page:<br />
<img title="Success page displays showing input data" alt="success.jsp displayed showing input data" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/05/success-page.png" data-recalc-dims="1" /></li>
</ol>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i0.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/05/02/introduction-to-the-struts-web-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>RESTful Web Services JSON API Transformer with Java</title>
		<link>http://latest-tutorial.com/2013/04/26/restful-web-services-json-api-transformer-with-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=restful-web-services-json-api-transformer-with-java</link>
		<comments>http://latest-tutorial.com/2013/04/26/restful-web-services-json-api-transformer-with-java/#comments</comments>
		<pubDate>Fri, 26 Apr 2013 05:41:41 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Java Tutorials]]></category>
		<category><![CDATA[Application programming interface]]></category>
		<category><![CDATA[Data Access Object]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[GSON]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[Representational state transfer]]></category>
		<category><![CDATA[Web service]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2813</guid>
		<description><![CDATA[This post is the continuation of my previous last post, I had explained how to create a basic RESTful web services API using Java, now I want to explain JSON transformer to work with input Get and Post methods parameters. Just added a new class called transformer it converts object data into JSON text output [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><p><a href="http://www.flickr.com/photos/44792728@N00/3762360637" target="_blank"><img class="zemanta-img-inserted zemanta-img-configured alignright" title="JSON Card -- Front" alt="JSON Card -- Front" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/3762360637_6b851c9478_m.jpg?resize=227%2C121" data-recalc-dims="1" /></a></p>
<p>This post is the continuation of my previous <a href="http://www.9lessons.info/2012/09/restful-web-services-api-using-java-and.html">last post</a>, I had explained how to create a basic RESTful web services API using <a class="zem_slink" title="Java (programming language)" href="http://www.oracle.com/technetwork/java/" target="_blank" rel="homepage">Java</a>, now I want to explain <a class="zem_slink" title="JSON" href="http://json.org/" target="_blank" rel="homepage">JSON</a> transformer to work with input Get and Post methods parameters. Just added a new class called transformer it converts object data into JSON text output format.<br />
<a href="http://demos.9lessons.info/url.php?url=https://www.box.com/s/cmh3llfbov58v1pf4wr8" target="_blank"><img alt="" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/down1.png" align="absmiddle" border="0" data-recalc-dims="1" />Download War File</a>    <a href="http://demos.9lessons.info/url.php?url=https://www.box.com/s/5p6pzsq235fijtounkbp" target="_blank"><img alt="" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/down1.png" align="absmiddle" border="0" data-recalc-dims="1" />Download Project Source</a></p>
<p><b>Database</b></p>
<p>Sample database <i>messages</i> table contains three columns msg_id, message and user_id_fk.</p>
<div>CREATE TABLE  `messages` (<br />
`msg_id` int(11) <a class="zem_slink" title="Null (SQL)" href="http://en.wikipedia.org/wiki/Null_%28SQL%29" target="_blank" rel="wikipedia">NOT NULL</a> AUTO_INCREMENT,<br />
`message` TEXT,<br />
`user_id_fk` INT,<br />
PRIMARY KEY (`msg_id`)<br />
);</div>
<p>This tutorial required RESTful service support <a class="zem_slink" title="JAR (file format)" href="http://en.wikipedia.org/wiki/JAR_%28file_format%29" target="_blank" rel="wikipedia">JAR files</a> <i>jersey-client-1.0.3.jar</i>, <i>jersey-core-1.0.3.jar</i>, <i>jersey-server-1.0.3.jar</i>(<a href="http://download.java.net/maven/1/jersey/jars/" rel="nofollow">Download</a>), <i>jsr311-api-1.0.jar</i>(<a href="http://jsr311.java.net/" rel="nofollow">Download</a>) and <i>asm-3.1.jar</i>(<a href="http://asm.ow2.org/download/index.html" rel="nofollow">Download</a>). Copy these files into <i>WEB-INF</i> -&gt; <i>lib</i></p>
<p><img alt="RESTful Web Services using Java and MySQL" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/library.png" data-recalc-dims="1" /></p>
<p>Download Project Source link contains all these JARs.</p>
<p><b>Previous Tutorials:</b> <a href="http://www.9lessons.info/2012/07/java-mysql-insert-record-using-jquery.html">Java MySQL Insert Record using Jquery.</a> and <a href="http://www.9lessons.info/2012/08/java-json-jquery-display-records.html">Java MySQL JSON Display Records using Jquery.</a></p>
<p>Package structure for more details please check my previous java tutorials.<br />
<img alt="RESTful Web Services using Java and MySQL" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/filestucture.png" data-recalc-dims="1" /></p>
<p><b>FeedObjects.java</b><br />
Create a new package called <i>dto</i> (Data Transaction Objects). Created transaction objects title, description and url.</p>
<div>
<p>package dto;</p>
<p>public class FeedObjects {</p>
<p>private String msg_id;<br />
private String message;<br />
private String user_id;</p>
<p>//Generate Getters and Setters<br />
}</p>
</div>
<p>Explained generating Getters and Setter methods in this following tutorial<a href="http://www.9lessons.info/2012/08/java-json-jquery-display-records.html">Java MySQL JSON Display Records using Jquery.</a></p>
<p><b>Project.java</b><br />
Create a dao(<a class="zem_slink" title="Data access object" href="http://en.wikipedia.org/wiki/Data_access_object" target="_blank" rel="wikipedia">Data Access Object</a>) method <i>GetFeeds</i> with Arraylist datatype, using select statement getting results from <i>messageses</i> table where<i> user_id_fk</i>. Binding results into <i>feedData</i> object.</p>
<div>
<p>package dao;</p>
<p>import java.sql.Connection;<br />
import java.sql.PreparedStatement;<br />
import java.sql.ResultSet;<br />
import java.util.ArrayList;</p>
<p>import dto.FeedObjects;</p>
<p>public class Project<br />
{<br />
public ArrayList&lt;feedobjects&gt; GetFeeds(Connection connection,,String User_ID) throws Exception<br />
{<br />
ArrayList&lt;feedobjects&gt; feedData = new ArrayList&lt;feedobjects&gt;();<br />
try<br />
{<br />
PreparedStatement ps = connection.prepareStatement(&#8220;SELECT msg_id,message,user_id_fk FROM messages WHERE user_id_fk=? ORDER BY msg_id DESC&#8221;);<br />
ps.setString(1,User_ID);<br />
ResultSet rs = ps.executeQuery();<br />
while(rs.next())<br />
{<br />
FeedObjects feedObject = new FeedObjects();<br />
feedObject.setTitle(rs.getString(&#8220;msg_id&#8221;));<br />
feedObject.setDescription(rs.getString(&#8220;message&#8221;));<br />
feedObject.setUrl(rs.getString(&#8220;user_id_fk&#8221;));<br />
feedData.add(feedObject);<br />
}<br />
return feedData;<br />
}<br />
catch(Exception e)<br />
{<br />
throw e;<br />
}<br />
}</p>
<p>}</p>
</div>
<p><b>ProjectManager.java</b><br />
Model class write the business logic and data validation.</p>
<div>
<p>package model;</p>
<p>import java.sql.Connection;<br />
import java.util.ArrayList;</p>
<p>import dao.Database;<br />
import dao.Project;<br />
import dto.FeedObjects;</p>
<p>public class ProjectManager {</p>
<p>public ArrayList&lt;feedobjects&gt; GetFeeds(String User_Id)throws Exception {<br />
ArrayList&lt;feedobjects&gt; feeds = null;<br />
try {<br />
Database database= new Database();<br />
Connection connection = database.Get_Connection();<br />
Project project= new Project();<br />
feeds=project.GetFeeds(connection,User_Id);<br />
}<br />
catch (Exception e) {<br />
throw e;<br />
}<br />
return feeds;<br />
}</p>
<p>}</p>
</div>
<p><b>FeedTransformer.java</b><br />
Transformer class converts Java object result into JSON text format.</p>
<div>
<p>package transformer;</p>
<p>import java.util.ArrayList;<br />
import com.google.gson.<a class="zem_slink" title="GSON" href="http://code.google.com/p/google-gson/" target="_blank" rel="homepage">Gson</a>;</p>
<p>import dto.FeedObjects;</p>
<p>public class FeedTransformer<br />
{<br />
public static String UserFeed(ArrayList&lt;FeedObjects&gt; feedData)<br />
{<br />
String feeds = null;<br />
Gson gson = new Gson();<br />
feeds = gson.toJson(feedData);<br />
return feeds;<br />
}<br />
}</p>
</div>
<p><b>FeedService.java</b><br />
Web Services class for <a class="zem_slink" title="Representational state transfer" href="http://en.wikipedia.org/wiki/Representational_state_transfer" target="_blank" rel="wikipedia">RESTful API</a>.</p>
<div>
<p>package <a class="zem_slink" title="Web service" href="http://en.wikipedia.org/wiki/Web_service" target="_blank" rel="wikipedia">webService</a>;</p>
<p>import java.util.ArrayList;<br />
import javax.ws.rs.GET;<br />
import javax.ws.rs.Path;<br />
import javax.ws.rs.Produces;<br />
import javax.ws.rs.QueryParam;</p>
<p>import model.ProjectManager;<br />
import com.google.gson.Gson;<br />
import dto.FeedObjects;</p>
<p>@Path(&#8220;/WebService&#8221;)<br />
public class FeedService {</p>
<p>@GET<br />
@Path(&#8220;/GetFeeds&#8221;)<br />
@Produces(&#8220;application/json&#8221;)<br />
public String messageFeed(@QueryParam(&#8220;userId&#8221;) String User_Id)<br />
{<br />
String feeds = null;<br />
try<br />
{</p>
<div>ArrayList&lt;FeedObjects&gt; feedData = null;</div>
<div>ProjectManager projectManager= new ProjectManager();</div>
<div>feedData = projectManager.GetFeeds(User_Id);</div>
<div>feeds=FeedTransformer.UserFeed(feedData);</div>
<p>}<br />
catch (Exception e)<br />
{<br />
System.out.println(&#8220;Exception Error&#8221;); //Console<br />
}<br />
return feeds;<br />
}</p>
<p>}</p>
</div>
<p>If you want to convert <i>GET</i> to <i>POST</i> just do little change.</p>
<div>import javax.ws.rs.GET;<br />
import javax.ws.rs.QueryParam;<br />
to<br />
import javax.ws.rs.POST;<br />
import javax.ws.rs.FormParam;@GET<br />
@Path(&#8220;/GetFeeds&#8221;)<br />
to<br />
@POST<br />
@Path(&#8220;/GetFeeds&#8221;)public String messageFeed(@QueryParam(&#8220;userId&#8221;) String User_Id)<br />
to<br />
public String messageFeed(@FormParam(&#8220;userId&#8221;) String User_Id)</div>
<p>You can test post method with <a class="zem_slink" title="Mozilla Firefox" href="http://web-browsers.findthebest.com/l/2/Mozilla-Firefox" target="_blank" rel="fdbsoftware">Mozilla Firefox</a> Add on <a href="https://addons.mozilla.org/en-US/firefox/addon/poster/">Poster</a>.</p>
<div><img alt="RESTful Web Services with input parameters" src="http://i1.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/Poster.png" data-recalc-dims="1" /></div>
<p><b>web.xml</b><br />
The URL configuration file.</p>
<div>
<p>&lt;?xml version=&#8221;1.0&#8243; encoding=&#8221;UTF-8&#8243;?&gt;</p>
<div>&lt;web-app xmlns:xsi=&#8221;http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns=&#8221;http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=&#8221;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; xsi:schemaLocation=&#8221;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221; id=&#8221;WebApp_ID&#8221; version=&#8221;2.5&#8243;&gt;<br />
&lt;display-name&gt;FirstProject&lt;/display-name&gt;<br />
&lt;welcome-file-list&gt;</div>
<div>&lt;welcome-file&gt;index.html&lt;/welcome-file&gt;</div>
<div>&lt;welcome-file&gt;index.htm&lt;/welcome-file&gt;</div>
<div>&lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;</div>
<div>&lt;/welcome-file-list&gt;</div>
<div>&lt;servlet&gt;</div>
<div>&lt;servlet-name&gt;ServletAdaptor&lt;/servlet-name&gt;</div>
<div>&lt;servlet-class&gt;</div>
<div>com.sun.jersey.server.impl.container.servlet.ServletAdaptor&lt;/servlet-class&gt;</div>
<div>&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;</div>
<div>&lt;/servlet&gt;</div>
<div>&lt;servlet-mapping&gt;</div>
<div>&lt;servlet-name&gt;ServletAdaptor&lt;/servlet-name&gt;</div>
<div>&lt;url-pattern&gt;/REST/*&lt;/url-pattern&gt;</div>
<div>&lt;/servlet-mapping&gt;</div>
<div>&lt;/web-app&gt;</div>
</div>
<p><b>Final GET URL</b></p>
<p>http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds</p>
<p>Here RESTfulProject is the project name, REST is the web.xml servelt mapping name, WebService is REST API path and GetFeeds is the method name.</p>
<p>Note: For checking POST URLs user Poster extension for Chrome and Firefox.</p>
<p><b>JSON Output</b></p>
<div>[{<br />
"msg_id":"3",<br />
"message":"Everything is possible. ",<br />
"user_id":"2"<br />
},<br />
{<br />
"msg_id":"1",<br />
"message":"Make People fall in love with Your Ideas",<br />
"user_id":"2"<br />
}]</div>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i0.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/04/26/restful-web-services-json-api-transformer-with-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get Data from Clipboard in Java</title>
		<link>http://latest-tutorial.com/2013/04/10/get-data-from-clipboard-in-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=get-data-from-clipboard-in-java</link>
		<comments>http://latest-tutorial.com/2013/04/10/get-data-from-clipboard-in-java/#comments</comments>
		<pubDate>Wed, 10 Apr 2013 13:30:06 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Random Posts]]></category>
		<category><![CDATA[Class (computer programming)]]></category>
		<category><![CDATA[clipboard]]></category>
		<category><![CDATA[FAQs Help and Tutorials]]></category>
		<category><![CDATA[Get Data from Clipboard]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[languages]]></category>
		<category><![CDATA[Method (computer programming)]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[UnsupportedFlavorException]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2701</guid>
		<description><![CDATA[An example on getting and printing a string from system clipboard in Java in just 2 statements. Example import java.awt.*; import java.awt.datatransfer.*; class SystemClipboard { public static void main(String args[]) throws Exception { // Create a Clipboard object using getSystemClipboard() method Clipboard c=Toolkit.getDefaultToolkit().getSystemClipboard(); // Get data stored in the clipboard that is in the form [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><p>An example on getting and printing a string from system <a class="zem_slink" title="Clipboard (computing)" href="http://en.wikipedia.org/wiki/Clipboard_%28computing%29" target="_blank" rel="wikipedia">clipboard</a> in <a class="zem_slink" title="Java (programming language)" href="http://www.oracle.com/technetwork/java/" target="_blank" rel="homepage">Java</a> in just 2 statements.</p>
<p><a name="more"></a></p>
<h1><a class="zem_slink" title="Example (musician)" href="http://trythisforexample.com" target="_blank" rel="homepage">Example</a></h1>
<div></div>
<div>
<div>
<pre><code>
import java.awt.*;
import java.awt.datatransfer.*;
<a class="zem_slink" title="Class (computer programming)" href="http://en.wikipedia.org/wiki/Class_%28computer_programming%29" target="_blank" rel="wikipedia">class</a> SystemClipboard
{
 public static void main(String args[]) throws Exception
 {

 // Create a Clipboard object using getSystemClipboard() method
 Clipboard c=Toolkit.getDefaultToolkit().getSystemClipboard();

 // Get <a class="zem_slink" title="Data" href="http://en.wikipedia.org/wiki/Data" target="_blank" rel="wikipedia">data</a> stored in the clipboard that is in the form of a string (text)
 System.out.println(c.getData(DataFlavor.stringFlavor));

 }
}</code></pre>
<h1>Explanation</h1>
</div>
</div>
<div><b> </b></div>
<div><b>java.awt.*:</b> Contains <i>Toolkit</i> class.</div>
<div></div>
<div><b>java.awt.datatransfer.*: </b>Contains <i>Clipboard</i> class.</div>
<div></div>
<div><b>Exception: </b>UnsupportedFlavorException is thrown.</div>
<div></div>
<div><b>Flavor:</b> Nothing but the type of the data. We need to specify it in order to get what type of data we want. For example, if clipboard contains an image, then it is <i>imageFlavor</i> or if it contains only characters then <i>stringFlavor.</i> These are constants however present in the <i><a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/datatransfer/DataFlavor.html" target="_blank" rel="nofollow">java.awt.datatransfer.DataFlavor</a></i> class.</div>
<div></div>
<div><b>Toolkit.getDefaultToolkit().getSystemClipboard():</b> Toolkit class has a <i>public static</i> method <i>getDefaultToolkit()</i> which returns an instance of the <i>java.awt.Toolkit</i> class which is useful for calling the normal <i>public</i> method <i>getSystemClipboard().</i> This method returns the <i><a href="http://docs.oracle.com/javase/1.7.0/docs/api/java/awt/datatransfer/Clipboard.html" target="_blank" rel="nofollow">java.awt.datatransfer.Clipboard</a></i> object which will further be used to get data from the system clipboard.</div>
<div><b> </b></div>
<div><b>c.getData(DataFlavor.stringFlavor): </b>Get the data in the clipboard that is just in the form of general characters. An exception is thrown if either the clipboard is empty or contains other than string (for example an image).</div>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i0.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/04/10/get-data-from-clipboard-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Paste Image from Clipboard on JFrame in Java</title>
		<link>http://latest-tutorial.com/2013/04/10/paste-image-from-clipboard-on-jframe-in-java/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=paste-image-from-clipboard-on-jframe-in-java</link>
		<comments>http://latest-tutorial.com/2013/04/10/paste-image-from-clipboard-on-jframe-in-java/#comments</comments>
		<pubDate>Wed, 10 Apr 2013 13:25:39 +0000</pubDate>
		<dc:creator>Zeeshan Akhter</dc:creator>
				<category><![CDATA[Java Posts]]></category>
		<category><![CDATA[Random Posts]]></category>
		<category><![CDATA[Clipboard (software)]]></category>
		<category><![CDATA[FAQs Help and Tutorials]]></category>
		<category><![CDATA[Image from Clipboard]]></category>
		<category><![CDATA[Import]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[languages]]></category>
		<category><![CDATA[Magazines and E-zines]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[swing]]></category>

		<guid isPermaLink="false">http://latest-tutorial.com/?p=2696</guid>
		<description><![CDATA[An example on pasting an image that is on system clipboard in Java on a JFrame. Here we&#8217;ve used a JLabel and set the image from the clipboard to it as icon. Example // Import for BorderLayout import java.awt.*; // Import for JFrame, JLabel import javax.swing.*; // Import for Clipboard, DataFlavor import java.awt.datatransfer.*; // Import [...]]]></description>
				<content:encoded><![CDATA[<div class="page-restrict-output"><p>An example on pasting an image that is on system clipboard in <a class="zem_slink" title="Java (programming language)" href="http://www.oracle.com/technetwork/java/" target="_blank" rel="homepage">Java</a> on a <a class="zem_slink" title="Swing (Java)" href="http://en.wikipedia.org/wiki/Swing_%28Java%29" target="_blank" rel="wikipedia">JFrame</a>. Here we&#8217;ve used a JLabel and set the image from the clipboard to it as icon.</p>
<p><a name="more"></a></p>
<h1>Example</h1>
<div></div>
<div>
<pre><code>
// Import for <a class="zem_slink" title="Layout manager" href="http://en.wikipedia.org/wiki/Layout_manager" target="_blank" rel="wikipedia">BorderLayout</a>
<a class="zem_slink" title="Import" href="http://en.wikipedia.org/wiki/Import" target="_blank" rel="wikipedia">import</a> java.awt.*;

// Import for JFrame, JLabel
import javax.swing.*;

// Import for <a class="zem_slink" title="Clipboard (computing)" href="http://en.wikipedia.org/wiki/Clipboard_%28computing%29" target="_blank" rel="wikipedia">Clipboard</a>, DataFlavor
import java.awt.datatransfer.*;

// Import for BufferedImage
import java.awt.image.*;

class PasteImage extends JFrame
{
JLabel l;
 public PasteImage()
 {

 // Set frame properties
 setTitle("<a class="zem_slink" title="Paste (magazine)" href="http://www.pastemagazine.com" target="_blank" rel="homepage">Paste</a> Image");
 setLayout(new BorderLayout());
 setDefaultCloseOperation(EXIT_ON_CLOSE);
 setVisible(true);

 // UnsupportedFlavorException, IOException can be raised.
 try
 {

 // Get image type data from the clipboard (<a class="zem_slink" title="Object (computer science)" href="http://en.wikipedia.org/wiki/Object_%28computer_science%29" target="_blank" rel="wikipedia">Object type</a> is returned) but <a class="zem_slink" title="Typecasting (acting)" href="http://en.wikipedia.org/wiki/Typecasting_%28acting%29" target="_blank" rel="wikipedia">type casted</a> to BufferedImage
 l=new JLabel(new ImageIcon((BufferedImage)Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.imageFlavor)));

 }catch(Exception e){

  // If image is not found, try text!
  try
  {

  // Create a JLabel containing text that is in the clipboard
  l=new JLabel((String)Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor));

  }catch(Exception e1){
  // If nothing was there in the clipboard..
  l=new JLabel("Nothing is there in the clipboard!");

  }

 }

 // Add the JLabel to the frame
 add(l);
 
 // Pack it tightly!
 pack();

 // Center the JFrame
 setLocationRelativeTo(null);

 }

 public static void main(String args[])
 {

 new PasteImage();

 }

}</code></pre>
<h1>Explanation</h1>
</div>
<div></div>
<div>
<div><b>Toolkit.getDefaultToolkit().getSystemClipboard():</b> Toolkit class has a <i>public static</i> method <i>getDefaultToolkit()</i> which returns an instance of the <i><a href="http://docs.oracle.com/javase/1.7.0/docs/api/java/awt/Toolkit.html" target="_blank" rel="nofollow">java.awt.Toolkit</a></i> class which is useful for calling the normal <i>public</i> method <i>getSystemClipboard().</i> This method returns the  object which will further be used to get data from the system clipboard.</div>
<div><b> </b></div>
<div><b>getData(DataFlavor.imageFlavor): </b>Get the data in the clipboard that is in the form of an image.</div>
</div>
<div></div>
<div><b>Note:</b> To make this program successful and see an image, before executing the program don&#8217;t forget to copy any image to the clipboard.</div>
<div></div>
<div>
<h1>Output</h1>
<p><a href="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/PasteImage.png"><img alt="PasteImage" src="http://i2.wp.com/latest-tutorial.com/wp-content/uploads/2013/04/PasteImage.png?resize=300%2C269" data-recalc-dims="1" /></a></p>
<p>Paste image from Clipboard in Java</p>
</div>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Enhanced by Zemanta" href="http://www.zemanta.com/?px"><img class="zemanta-pixie-img" style="border: none; float: right;" alt="Enhanced by Zemanta" src="http://i2.wp.com/img.zemanta.com/zemified_e.png" data-recalc-dims="1" /></a></div>
</div>]]></content:encoded>
			<wfw:commentRss>http://latest-tutorial.com/2013/04/10/paste-image-from-clipboard-on-jframe-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
