<?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>JavaBeat &#187; Struts 2.0</title>
	<atom:link href="http://www.javabeat.net/category/web-frameworks/struts-2-0/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Sun, 16 Jun 2013 11:17: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>Custom Validators in Struts 2.0</title>
		<link>http://www.javabeat.net/2011/04/custom-validators-in-struts-2-0/</link>
		<comments>http://www.javabeat.net/2011/04/custom-validators-in-struts-2-0/#comments</comments>
		<pubDate>Fri, 01 Apr 2011 15:09:03 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Struts 2.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=617</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Custom Validators in Struts 2.0 Introduction Struts 2.0 is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on MVC Model 2 design pattern. Dispatcher Filter is the front controller for the struts2 based applications. Struts 2.0 has simplified web development for its users by introducing POJO based actions, interceptors, [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p><center></p>
<h1>Custom Validators in Struts 2.0</h1>
<p></center></p>
<h2>Introduction</h2>
<p><strong><a href="http://www.javabeat.net/articles/67-struts-20-introduction-and-validations-using-annotatio-1.html">Struts 2.0</a></strong> is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on <strong>MVC Model 2 </strong>design pattern. Dispatcher Filter is the front controller for the struts2 based applications. <a href="http://www.javabeat.net/articles/67-struts-20-introduction-and-validations-using-annotatio-1.html">Struts 2.0</a> has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support for many different result types. Struts can be used to build the user interface tier of the enterprise application. Data validation is an important aspect in enterprise applications. This article explains the concept of custom validators.</p>
<h2>Development Environment</h2>
<ul>
<li>NetBeans IDE 6.9</li>
<li>GlassFish V3</li>
</ul>
<h2>Project Structure</h2>
<p>The sample application developed in this article is &#8216;Struts2CustomValidation&#8217;<br />
where a user can register to the application by specifying few details like userId,firstname,city etc. Custom validator developed in the application will be responsible for validating the value of the city field.</p>
<p><strong>Libraries/Jar Files Required</strong></p>
<ul>
<ul>
<li>Struts 2.0 jar files</li>
</ul>
</ul>
<p>The complete application structure is shown below:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/11.jpg"><img class="aligncenter size-medium wp-image-1150" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/04/11-189x300.jpg" alt="" width="189" height="300" /></a></p>
<ul>
<ul>
<li>The User Interface (JSP pages) is created in the “Web Pages” directory. The java classes (Actions, Interceptors and struts.xml) are created in the “Source Packages” directory. The required jar files are present in the “Libraries” directory. The web application deployment descriptor “web.xml” is created by the IDE in the “WEB-INF” subdirectory of “Web Pages”.</li>
</ul>
</ul>
<h2>Action Class</h2>
<p>Struts does the request processing with the help of Action classes. Here’s the code for the<strong> RegisterAction.java</strong> which handles the<br />
request to register to our application. This class is created in the package “com.actions”.</p>
<p><strong>RegisterAction.java</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package com.actions;
	import com.opensymphony.xwork2.ActionSupport;
	import java.util.Date;
	public class RegisterAction extends ActionSupport {
		private String userId;
		private String firstName;
		private String lastName;
		private int age;
		private String city;
		private String email;
		private Date joiningDate;
		private String password;
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
		public String getUserId() {
			return userId;
		}
		public void setUserId(String userId) {
			this.userId = userId;
		}
		public Date getJoiningDate() {
			return joiningDate;
		}
		public void setJoiningDate(Date joiningDate) {	
			this.joiningDate = joiningDate;
		}
		public int getAge() {
			return age;
		}
		public void setAge(int age) {
			this.age = age;
		}
		public String getCity() {
			return city;
		}
		public void setCity(String city) {
			this.city = city;
		}
		public String getEmail() {
			return email;
		}
		public void setEmail(String email) {
			this.email = email;
		}
		public String getFirstName() {
			return firstName;
		}
		public void setFirstName(String firstName) {
			this.firstName = firstName;
		}
		public String getLastName() {
			return lastName;
		}
		public void setLastName(String lastName) {
			this.lastName = lastName;
		}
&nbsp;
		@Override
		public String execute() {
			return &quot;success&quot;;
		}
	}</pre></td></tr></table></div>

<p>Let us understand the request processing logic in the action class. The action class handles the register request in the execute method. There&#8217;s no validation logic hardcoded in the java class. The complete validation logic including the custom validation is added in the<strong> &#8220;RegisterAction-validation.xml&#8221;</strong> file.Upon successful validation, the user is forwarded to &#8220;Register_Success.jsp&#8221; page.</p>
<p>We have put the validation logic in the <strong>“RegisterAction-validation.xml” </strong>file kept in the <strong>“com.actions”</strong> package. Please note that the validation.xml file should always be kept in the same package where your action class is present.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;!DOCTYPE validators PUBLIC
		&quot;-//OpenSymphony Group//XWork Validator 1.0.2//EN&quot;
		&quot;http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd&quot;&gt;
	&lt;validators&gt;
		&lt;field name=&quot;userId&quot;&gt;
			&lt;field-validator type=&quot;requiredstring&quot;&gt;
				&lt;message&gt;Employee Id is a mandatory field&lt;/message&gt;
			&lt;/field-validator&gt;
			&lt;field-validator type=&quot;regex&quot;&gt;
				&lt;param name=&quot;expression&quot;&gt;
					&lt;![CDATA[([E][m][p][0-9][0-9][0-9])]]&gt;
				&lt;/param&gt;
				&lt;message&gt;Valid Employee Id required e.g. Emp001&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
		&lt;field name=&quot;age&quot;&gt;
			&lt;field-validator type=&quot;int&quot;&gt;
				&lt;param name=&quot;min&quot;&gt;20&lt;/param&gt;
				&lt;param name=&quot;max&quot;&gt;80&lt;/param&gt;
				&lt;message&gt;Age needs to between ${min} and ${max}&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
		&lt;field name=&quot;firstName&quot;&gt;
			&lt;field-validator type=&quot;requiredstring&quot;&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;First Name is required&lt;/message&gt;
			&lt;/field-validator&gt;
			&lt;field-validator type=&quot;stringlength&quot;&gt;
				&lt;param name=&quot;maxLength&quot;&gt;10&lt;/param&gt;
				&lt;param name=&quot;minLength&quot;&gt;5&lt;/param&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;
					Enter firstName between 5 and 10 characters
				&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
		&lt;field name=&quot;lastName&quot;&gt;
			&lt;field-validator type=&quot;requiredstring&quot;&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;Last Name is required&lt;/message&gt;
			&lt;/field-validator&gt;
			&lt;field-validator type=&quot;stringlength&quot;&gt;
				&lt;param name=&quot;maxLength&quot;&gt;10&lt;/param&gt;
				&lt;param name=&quot;minLength&quot;&gt;5&lt;/param&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;
					Enter lastName between 5 and 10 characters
				&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
		&lt;field name=&quot;password&quot;&gt;
			&lt;field-validator type=&quot;requiredstring&quot;&gt;
				&lt;message&gt;Password is required&lt;/message&gt;
			&lt;/field-validator&gt;
			&lt;field-validator type=&quot;stringlength&quot;&gt;
				&lt;param name=&quot;maxLength&quot;&gt;10&lt;/param&gt;
				&lt;param name=&quot;minLength&quot;&gt;5&lt;/param&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;
					Enter password between 5 and 10 characters
				&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
		&lt;field name=&quot;city&quot;&gt;
			&lt;field-validator type=&quot;requiredstring&quot; short-circuit=&quot;true&quot;&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;You can not leave city as blank&lt;/message&gt;
			&lt;/field-validator&gt;
			&lt;field-validator type=&quot;cityValidator&quot; short-circuit=&quot;true&quot;&gt;
				&lt;message&gt;City value is incorrect. it must match the pattern Az*&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
		&lt;field name=&quot;email&quot;&gt;
			&lt;field-validator type=&quot;requiredstring&quot;&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;You can not leave email as blank&lt;/message&gt;
			&lt;/field-validator&gt;
			&lt;field-validator type=&quot;email&quot;&gt;
				&lt;message&gt;
					The email address you entered is not valid.
				&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
		&lt;field name=&quot;joiningDate&quot;&gt;
			&lt;field-validator type=&quot;required&quot;&gt;
				&lt;message&gt;
					You cannot leave the date of joining field blank.
				&lt;/message&gt;
			&lt;/field-validator&gt;
			&lt;field-validator type=&quot;date&quot; &gt;
				&lt;message&gt;
					Joining date must be supplied
				&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
	&lt;/validators&gt;</pre></td></tr></table></div>

<p>The data validation is performed with the help of “RegisterAction-validation.xml” file. Different validation routines are configured for the the various attributes.Along with the various built in validations, we have made use of a custom validator &#8220;cityValidator&#8221; to validate the value of the &#8220;city&#8221; attribute. The id of the validator &#8220;cityValidator&#8221; is taken from the file <strong> validators.xml</strong> which is created in the default class path.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fweb-frameworks%2Fstruts-2-0%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/web-frameworks/struts-2-0/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/web-frameworks/struts-2-0/feed/" data-count="vertical" data-text="Struts 2.0" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/04/custom-validators-in-struts-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Custom Interceptors in Struts 2.0</title>
		<link>http://www.javabeat.net/2011/03/custom-interceptors-in-struts-2-0/</link>
		<comments>http://www.javabeat.net/2011/03/custom-interceptors-in-struts-2-0/#comments</comments>
		<pubDate>Fri, 11 Mar 2011 13:31:40 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Struts 2.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=577</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction Struts 2.0 is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on MVC Model 2 design pattern. Dispatcher Filter is the front controller for the struts 2.0 based applications. Struts 2.0 has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p><strong>Struts 2.0</strong> is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on <strong>MVC Model 2 </strong>design pattern. Dispatcher Filter is the front controller for the <strong>struts 2.0</strong> based applications. <strong>Struts 2.0</strong> has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support for many different result types. Struts can be used to build the user interface tier of the enterprise application. Interceptors can be used to embed the cross cutting or plumbing logic of the application in a clean and reusable manner. This article explains the concept of custom interceptors.</p>
<h2>Development Environment</h2>
<ul>
<li>NetBeans IDE 6.8</li>
<li>GlassFish V2.x</li>
<li>Apache Derby Database</li>
</ul>
<h2>Project Structure</h2>
<p>The sample application developed in this article is &#8220;StrutsLoginDemo&#8221; where a user can log in to the application by specifying a valid userId and password. Custom Interceptor developed in the application will be calculating the time spent in the request processing.</p>
<p><strong>Libraries/Jar Files Required</strong></p>
<ul>
<ul>
<li><strong>Struts 2.0</strong> jar files</li>
</ul>
</ul>
<p>The complete application structure is shown below:</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/1.jpg"><img class="aligncenter size-medium wp-image-1064" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/03/1-190x300.jpg" alt="" width="190" height="300" /></a></p>
<ul>
<li>The User Interface (JSP pages) is created in the “Web Pages” directory. The java classes (Actions, Interceptors and struts.xml) are created in the “Source Packages” directory. The required jar files are present in the “Libraries” directory. The web application deployment descriptor “web.xml” is created by the IDE in the “WEB-INF” subdirectory of “Web Pages”.</li>
</ul>
<h2>Action Class</h2>
<p>Struts does the request processing with the help of Action classes. Here’s the code for the<strong> LoginAction.java</strong> which handles the<br />
request to login to our application. This class is created in the package “demo”.</p>
<p><strong>LoginAction.java</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package demo;
&nbsp;
	import com.opensymphony.xwork2.ActionSupport;
	import com.opensymphony.xwork2.ActionContext;
	import java.util.*;
&nbsp;
	public class LoginAction extends ActionSupport {
	    private String userId;
	    private String password;
	    public String execute() throws Exception {
	        if (&quot;admin&quot;.equals(userId) &amp;&amp; &quot;admin&quot;.equals(password)) {
	            Map session = ActionContext.getContext().getSession();
	            session.put(&quot;logged-in&quot;, &quot;true&quot;);
	            return SUCCESS;
	        } else {
	            return ERROR;
	        }
	    }
&nbsp;
	    public String logout() throws Exception {
&nbsp;
	        Map session = ActionContext.getContext().getSession();
	        session.remove(&quot;logged-in&quot;);
	        return SUCCESS;
	    }
&nbsp;
	    public String getPassword() {
	        return password;
	    }
&nbsp;
	    public void setPassword(String password) {
	        this.password = password;
	    }
&nbsp;
	    public String getUserId() {
	        return userId;
	    }
&nbsp;
		public void setUserId(String userId) {
	        this.userId = userId;
	    }
	}</pre></td></tr></table></div>

<p>Let us understand the request processing in the action class. The action class handles the login request in the execute method, where we are validating that both the userId and password values must be &#8220;admin&#8221;. If the values do not match, then the user is forwarded to &#8220;Login_Failure.jsp&#8221; page. Upon successful validation, the user is forwarded to &#8220;Login_Success.jsp&#8221; page.Also, in the execute method we have added a sleep interval of 2 seconds, to show the time spent in the action class via interceptor.</p>
<p>Please note that there’s no validation logic in the action class. We have put the validation logic in the <strong>“LoginAction-validation.xml” </strong>file kept in the <strong>“demo”</strong> package. Please note that the validation.xml file should always be kept in the same package where your action class is<br />
present.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;!DOCTYPE validators PUBLIC
		&quot;-//OpenSymphony Group//XWork Validator 1.0.2//EN&quot;
		&quot;http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd&quot;&gt;
&nbsp;
		&lt;validators&gt;
			&lt;field name=&quot;userId&quot;&gt;
				&lt;field-validator type=&quot;requiredstring&quot;&gt;
					&lt;message&gt;User Id is a mandatory field&lt;/message&gt;
				&lt;/field-validator&gt;
			&lt;/field&gt;      
			&lt;field name=&quot;password&quot;&gt;
				&lt;field-validator type=&quot;requiredstring&quot;&gt;
					&lt;message&gt;Password is required&lt;/message&gt;
				&lt;/field-validator&gt;
			&lt;field-validator type=&quot;stringlength&quot;&gt;
				&lt;param name=&quot;maxLength&quot;&gt;10&lt;/param&gt;
				&lt;param name=&quot;minLength&quot;&gt;5&lt;/param&gt;
				&lt;param name=&quot;trim&quot;&gt;true&lt;/param&gt;
				&lt;message&gt;
					Enter password between 5 and 10 characters
				&lt;/message&gt;
			&lt;/field-validator&gt;
		&lt;/field&gt;
	&lt;/validators&gt;</pre></td></tr></table></div>

<p>The data validation is performed with the help of “LoginAction-validation.xml” file. Different validation routines are configured for the both the attributes (userId and password).</p>
<h2>The Custom Interceptor</h2>
<p>In this application, we have created a custom interceptor <strong>&#8220;MyCustomInterceptor&#8221; </strong>which keeps track of the time spent in the action class. The interceptor is created in the <strong> interceptors</strong> package inside <strong>Source Packages</strong> sub directory.The custom interceptor provides the implementation of <strong>Interceptor</strong> interface and provides the implementation of <strong>init(),destory() and intercept()</strong> methods.</p>
<p>Here’s the code for the<strong> MyCustomInterceptor.java</strong> which handles the logic to calculate the time spent in the action. This class is created in the package <strong>“interceptors”</strong>.</p>
<p><strong>MyCustomInterceptor.java</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">package interceptors;
&nbsp;
	import com.opensymphony.xwork2.ActionInvocation;
	import com.opensymphony.xwork2.interceptor.Interceptor;
	import java.text.SimpleDateFormat;
	import java.util.Calendar;
	import java.util.Date;
&nbsp;
	public class MyCustomInterceptor implements Interceptor {
		public String intercept(ActionInvocation next) throws Exception {
	        System.out.println(&quot;*****************************&quot;);
		    SimpleDateFormat sdf = new SimpleDateFormat(&quot; MM/dd/yyyy HH:mm:ss &quot;);
	        Calendar cal = Calendar.getInstance();
	        Date initDate = cal.getTime();
	        String newdate = sdf.format(initDate);
	        System.out.println(&quot;In the interceptor in pre processing logic&quot;);
	        System.out.println(&quot;Request reached the custom interceptor @ &quot; + newdate + &quot; time&quot;);
	        System.out.println(&quot;*****************************&quot;);
	        Thread.sleep(2000);
	        String s = next.invoke();
	        System.out.println(&quot;*****************************&quot;);
	        System.out.println(&quot;Back in the interceptor in post processing logic&quot;);
	        Calendar cal1 = Calendar.getInstance();
	        String finalDate = sdf.format(cal1.getTime());
	        System.out.println(&quot;Request returned in the custom interceptor @ &quot; + finalDate + &quot; time&quot;);
	        long milliseconds1 = cal.getTimeInMillis();
	        long milliseconds2 = cal1.getTimeInMillis();
	        long timeDiff = milliseconds2 - milliseconds1;
	        long timeDiffSeconds = timeDiff / 1000;
	        long timeDiffMinutes = timeDiff / (60 * 1000);
	        System.out.println(&quot;Time in milliseconds: &quot; + timeDiff + &quot; milliseconds.&quot;);
	        System.out.println(&quot;Time in seconds: &quot; + timeDiffSeconds + &quot; seconds.&quot;);
	        System.out.println(&quot;Time in minutes: &quot; + timeDiffMinutes + &quot; minutes.&quot;);
	        System.out.println(&quot;*****************************&quot;);
	        return s;
	    }
&nbsp;
		public void init() {
	        System.out.println(&quot;Interceptor is initialized&quot;);
	    }
&nbsp;
		public void destroy() {
	        System.out.println(&quot;In the destroy method of Interceptor&quot;);
	    }
	}</pre></td></tr></table></div>

<h2>The User Interface Tier</h2>
<p>The user interface part of the application is created in JSP. The home page of the application is <strong>“Login.jsp”</strong>, where a form is displayed to the users asking for userId and password for login purpose. PFB the code of <strong>“Login.jsp”</strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot;%&gt;
	&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html&quot;%&gt;
&nbsp;
	&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Login Page!&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
	    &lt;s:form action=&quot;login.action&quot; method=&quot;post&quot;&gt;
			&lt;s:textfield name=&quot;userId&quot; label=&quot;Login Id&quot; /&gt;
			&lt;br&gt;
			&lt;s:password name=&quot;password&quot; label=&quot;Password&quot; /&gt;
			&lt;br&gt;
			&lt;s:submit value=&quot;Login&quot; align=&quot;center&quot; /&gt;
		&lt;/s:form&gt;
		&lt;s:actionerror /&gt;
&nbsp;
	&lt;/body&gt;
	&lt;/html&gt;</pre></td></tr></table></div>

<p>Once the user fills in the both userId and password &amp; clicks on the “Submit” button, the request is submitted to the action class. Upon<br />
successful validation, the user is forwarded to <strong>“Login_Success.jsp”</strong>page. Here’s the code of “Login_Success.jsp”.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;%@ taglib prefix=&quot;s&quot; uri=&quot;/struts-tags&quot; %&gt;
	&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html&quot; import=&quot;java.util.*&quot;%&gt;
&nbsp;
	&lt;html&gt;
	&lt;head&gt;
		&lt;title&gt;Welcome, you have logged in!&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
		Welcome, you have logged in. &lt;br /&gt;
		&lt;b&gt;Session Time: &lt;/b&gt;&lt;%=new Date(session.getLastAccessedTime())%&gt;
		&lt;br /&gt;&lt;br /&gt;
		&lt;a href=&quot;&lt;%= request.getContextPath()%&gt;/logout.action&quot;&gt;Logout&lt;/a&gt;
		&lt;br /&gt;
	&lt;/body&gt;
	&lt;/html&gt;</pre></td></tr></table></div>

<p>In case, the userId and password values are invalid, the user is forwarded to <strong>Login_Failure.jsp</strong>Here’s the code of “Login_Failure.jsp&#8221;.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=ISO-8859-1&quot;
         pageEncoding=&quot;ISO-8859-1&quot;%&gt;
	&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
	&lt;html&gt;
	&lt;head&gt;
		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=ISO-8859-1&quot;&gt;
		&lt;title&gt;Login Failure&lt;/title&gt;
	&lt;/head&gt;
	&lt;body&gt;
		Invalid Username/Password. Please Retry!!!!
		&lt;a href=&quot;Login.jsp&quot;&gt;Logout&lt;/a&gt;
	&lt;/body&gt;
	&lt;/html&gt;</pre></td></tr></table></div>

<h2>The Configuration Files</h2>
<p>Here’s the configuration added in the <strong>“web.xml”</strong> file:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
	&lt;web-app version=&quot;2.5&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;	xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;&gt;
		&lt;filter&gt;
			&lt;filter-name&gt;struts2&lt;/filter-name&gt;
			&lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher&lt;/filter-class&gt;
		&lt;/filter&gt;
		&lt;filter-mapping&gt;
			&lt;filter-name&gt;struts2&lt;/filter-name&gt;
			&lt;url-pattern&gt;/*&lt;/url-pattern&gt;
		&lt;/filter-mapping&gt;
		&lt;session-config&gt;
			&lt;session-timeout&gt;
				30
			&lt;/session-timeout&gt;
		&lt;/session-config&gt;
		&lt;welcome-file-list&gt;
			&lt;welcome-file&gt;Login.jsp&lt;/welcome-file&gt;
		&lt;/welcome-file-list&gt;
	&lt;/web-app&gt;</pre></td></tr></table></div>

<p>In the <strong>deployment descriptor</strong>, we have added the following configurations:</p>
<ol>
<li>The Welcome File of the application</li>
<li>Struts2 Dispatcher Filter (Controller element of Struts2<br />
applications)</li>
</ol>
<p>Here’s the configuration added in the<strong> “struts.xml”</strong> file kept in the default package in the “Source Packages” directory.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; ?&gt;
	&lt;!DOCTYPE struts PUBLIC
		&quot;-//Apache Software Foundation//DTD Struts Configuration 2.0//EN&quot; &quot;http://struts.apache.org/dtds/struts-2.0.dtd&quot;&gt;
	&lt;struts&gt;
		&lt;constant name=&quot;struts.devMode&quot; value=&quot;false&quot;/&gt;
		&lt;package name=&quot;default&quot; extends=&quot;struts-default&quot; namespace=&quot;/&quot;&gt;
			&lt;interceptors&gt;
				&lt;interceptor name=&quot;customtimer&quot; class=&quot;interceptors.MyCustomInterceptor&quot;/&gt;
				&lt;interceptor-stack name=&quot;timerstack&quot;&gt;
					&lt;interceptor-ref name=&quot;defaultStack&quot; /&gt;
					&lt;interceptor-ref name=&quot;customtimer&quot;/&gt;
				&lt;/interceptor-stack&gt;
			&lt;/interceptors&gt;
&nbsp;
			&lt;default-interceptor-ref name=&quot;timerstack&quot; /&gt;
			&lt;action name=&quot;login&quot; class=&quot;demo.LoginAction&quot;&gt;
				&lt;result name=&quot;success&quot;&gt;/Login_Success.jsp&lt;/result&gt;
				&lt;result name=&quot;error&quot;&gt;
					/Login_Failure.jsp
				&lt;/result&gt;
&nbsp;
				&lt;result name=&quot;input&quot;&gt;
					/Login.jsp
				&lt;/result&gt;
			&lt;/action&gt;
			&lt;action name=&quot;logout&quot; class=&quot;demo.LoginAction&quot; method=&quot;logout&quot;&gt;
				&lt;result name=&quot;success&quot; type=&quot;redirect&quot;&gt;
					Login.jsp
				&lt;/result&gt;
				&lt;result name=&quot;input&quot; type=&quot;redirect&quot;&gt;/Login.jsp&lt;/result&gt;
			&lt;/action&gt;
		&lt;/package&gt;
	&lt;/struts&gt;</pre></td></tr></table></div>

<p>In the <strong>struts.xml</strong>, we have added the following configurations:</p>
<ol>
<li>The custom interceptor is configured and given an alias &#8220;customtimer&#8221;</li>
<li>A custom stack of interceptors is created and given an alias &#8220;timerstack&#8221;. The same stack is also configured to be the default interceptor stack of the application.</li>
<li>&#8220;execute&#8221; method of &#8220;LoginAction&#8221; class is configured to handled the login attempt to the application.</li>
<li>&#8220;logout&#8221; method of &#8220;LoginAction&#8221; class is configured to handled the logout attempt from the application.</li>
</ol>
<h2>Executing The Application</h2>
<p>Finally, we are ready to execute the application. Deploy the application to the container and execute.</p>
<p><strong>Open the Login.jsp page.</strong></p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/21.jpg"><img class="aligncenter size-medium wp-image-1066" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/03/21-300x187.jpg" alt="" width="300" height="187" /></a>Enter some invalid data, The snapshot given below shows the validation error messages</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/3.jpg"><img class="aligncenter size-medium wp-image-1068" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/03/3-300x273.jpg" alt="" width="300" height="273" /></a>Once, all the validation error messages have been rectified, the user is forwarded to Login_Success.jsp page, where the welcome message is displayed.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/41.jpg"><img class="aligncenter size-medium wp-image-1069" title="4" src="http://www.javabeat.net/wp-content/uploads/2011/03/41-300x173.jpg" alt="" width="300" height="173" /></a>Click on the &#8220;Logout&#8221; button and the user is redirected back to Login.jsp page.</p>
<p>Check the server console. It shows the messages from our custom timer interceptor. The time in the preprocessing and postprocessing is displayed along with the time spent in action method in milliseconds, seconds and minutes format.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/03/5.jpg"><img class="aligncenter size-medium wp-image-1063" title="5" src="http://www.javabeat.net/wp-content/uploads/2011/03/5-300x87.jpg" alt="" width="300" height="87" /></a></p>
<h2>Conclusion</h2>
<p>Thus, any Struts application can take benefit of the built in interceptors and also take control of request processing by creating custom interceptors.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/03/custom-interceptors-in-struts-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Struts 2.0 and JPA Integration</title>
		<link>http://www.javabeat.net/2011/02/struts-2-0-and-jpa-integration/</link>
		<comments>http://www.javabeat.net/2011/02/struts-2-0-and-jpa-integration/#comments</comments>
		<pubDate>Mon, 28 Feb 2011 13:25:18 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JPA]]></category>
		<category><![CDATA[Struts 2.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=564</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction Struts 2.0 is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on MVC Model 2 design pattern. Dispatcher Filter is the front controller for the struts2 based applications. Struts 2.0 has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support for [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p><strong>Struts 2.0</strong> is the popular Open Source Presentation Tier framework developed by Apache Group. It is based on <strong>MVC Model 2 </strong>design pattern. Dispatcher Filter is the front controller for the struts2 based applications. <strong><a href="http://www.javabeat.net/articles/67-struts-20-introduction-and-validations-using-annotatio-1.html">Struts 2.0</a></strong> has simplified web development for its users by introducing POJO based actions, interceptors, flexible validation and support for many different result types.</p>
<p>Struts can be used to build the user interface tier of the enterprise application. Whereas, any of the popular ORMs like Hibernate, JPA, iBatis can be used for the persistence tier of the application. Struts2 provides easy integration with these persistence tier frameworks.</p>
<p>This article demonstrates the integration of <strong><a href="http://www.javabeat.net/articles/67-struts- 20-introduction-and-validations-using-annotatio-1.html">Struts 2.0</a></strong> applications with the <strong><a href="http://www.javabeat.net/articles/5-introduction-to-java-persistence-apijpa-1.html">Java Persistence API (JPA)</a></strong>. The concept is explained with the help of a sample application. Knowledge of <strong>JPA and Struts 2.0</strong> is the prerequisite for this article.</p>
<h2>Development Environment</h2>
<ul>
<li>NetBeans IDE 6.8</li>
<li>GlassFish V2.x</li>
<li>Apache Derby Database</li>
</ul>
<h2>Project Structure</h2>
<p>The sample application developed in this article is &#8220;StrutsJPADemo&#8221; where an employee details are persisted to the database with the help of JPA.</p>
<p><strong>Libraries/Jar Files Required</strong></p>
<ul>
<li>Struts 2.0 jar files</li>
<li>JPA jar files</li>
<li>Jar file for the database driver (derbyclient.jar, in our case) The<br />
complete application structure is shown below:</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2011/02/15.jpg"><img class="aligncenter size-medium wp-image-1045" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/02/15-249x300.jpg" alt="" width="249" height="300" /></a></li>
<li><center></center></li>
<li>The User Interface (JSP pages) is created in the “Web Pages” directory. The java classes (Actions, Entities, Service classes, Resource Bundles, struts.xml) are created in the “Source Packages” directory. The required jar files are present in the “Libraries” directory. The web application deployment descriptor “web.xml” is created by the IDE in the “WEB-INF” subdirectory of “Web Pages”. This sample application stores the employee details into the Derby database.</li>
</ul>
<h2>Environment Set Up</h2>
<p>Once the web application is created and all the required libraries are added to the classpath, we can start working on the different components of the application.</p>
<p>Before we start working on the different application components like JSP pages and Java classes, we must first configure the following resources in the application server:</p>
<ol type="1">
<li><strong>javax.transaction.UserTransaction</strong>
<ol type="a">
<ol type="a">
<li>In our application, we have created a UserTransaction and bound the same in JNDI with the name “UserTransaction”. The snapshot given below shows the same.</li>
<li><a href="http://www.javabeat.net/wp-content/uploads/2011/02/24.jpg"><img class="aligncenter size-medium wp-image-1047" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/02/24-300x146.jpg" alt="" width="300" height="146" /></a></li>
</ol>
</ol>
<p><center></center></li>
<li><strong>Connection Pool &amp; DSN</strong>
<ol type="a">
<ol type="a">
<li>For the database, we have created a connection pool in the application server to connect to ScrambleDatabase in the local machine running at port number 1527. The connection pool is bound to the name<br />
“scramblePool” as shown in the snapshot below.</li>
</ol>
</ol>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/34.jpg"><img class="aligncenter size-medium wp-image-1048" title="3" src="http://www.javabeat.net/wp-content/uploads/2011/02/34-300x166.jpg" alt="" width="300" height="166" /></a></p>
<p><center></center></p>
<ol type="a">
<li>The next step is to configure the DSN in the application server. Our DSN is bound to the name “jdbc/scramdleDSN” in JNDI. This is shown below in the snapshot. This DSN will use <strong>“scramblePool”</strong>created in the previous step.</li>
</ol>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/44.jpg"><img class="aligncenter size-medium wp-image-1050" title="4" src="http://www.javabeat.net/wp-content/uploads/2011/02/44-300x166.jpg" alt="" width="300" height="166" /></a></li>
</ol>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/02/struts-2-0-and-jpa-integration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Integrating Struts 2.0 applications with Hibernate</title>
		<link>http://www.javabeat.net/2011/02/integrating-struts-2-0-applications-with-hibernate/</link>
		<comments>http://www.javabeat.net/2011/02/integrating-struts-2-0-applications-with-hibernate/#comments</comments>
		<pubDate>Sat, 19 Feb 2011 13:13:18 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Struts 2.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=552</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Struts 2.0 is one of the popularly used Presentation tier framework for Java web Applications.It is based on the WebWork2 technology.Struts 2.0 framework implements MVC 2 architecture by centralizing the control using a Front Controller strategy. The extensible and flexible nature of Struts 2.0 makes it the favourite choice of Java web developers. The major [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><strong style="font-size: 13px;">Struts 2.0</strong><span style="font-size: 13px;"> is one of the popularly used Presentation tier framework for Java web Applications.It is based on the </span><strong style="font-size: 13px;">WebWork2</strong><span style="font-size: 13px;"> technology.</span><strong style="font-size: 13px;">Struts 2.0</strong><span style="font-size: 13px;"> framework implements MVC 2 architecture by centralizing the control using a Front Controller strategy. The extensible and flexible nature of Struts 2.0 makes it the favourite choice of Java web developers. The major features of Struts 2.0 are user interface tags, Interceptor, result and validation.</span></p>
<p>A strong persistence framework is critical to the success and scalability of any application that we develop. Today we have a lot of data access frameworks like Hibernate, JDBC, JPAs, etc available in the market. <span style="text-decoration: underline;">Sturts can be integrated easily with any of these popularly used data access frameworks</span>.</p>
<p><span style="text-decoration: underline;">This article demonstrates the integration of <strong>Struts 2.0</strong> applications with the Hibernate</span>. The concept is explained with the help of a sample application. There are pluggins also available for integrating <strong>Struts 2.0 with Hibernate</strong>. The sample application used in this articile does not use any pluggins.</p>
<p>The author asuumes readers of this article have basic knowledge of <strong>Struts 2.0 and Hibernate</strong>.If you are beginner in learning Struts and hibernate, please read <a href="http://www.javabeat.net/2007/05/struts-2-0-introduction-and-validations-using-annotations/">Introduction to Struts 2.0</a> and <a href="http://www.javabeat.net/2007/05/hibernate-ormobjectrelational-framework-an-introduction/">Introduction to Hibernate</a>. The sample is created in NetBens IDE. Sample project struture is displayed in the next section.</p>
<h2>Project Structure</h2>
<p>This application which is discussed here stores the registration details of an employee to an Oracle DB table using struts 2 and hibernate.Includ the hibernate jar files and <strong>struts 2.0</strong> jar files to the project class path. Since we are using Oraccle we need to load the <em>classes12.jar/odbc5.jar</em> also to the class path.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/11.jpg"><img class="aligncenter" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/02/11-214x300.jpg" width="214" height="300" /></a></p>
<p>Create the domain model Employee.java as below.This class will be used as the hibernate model object.Hence we need to have the hibernate mapping files created for this as listed in the next section.</p>
<p>The same is used to push the form data to the valuestack.ValueStack, as you know already , is ,one of the powerful features of Struts 2.ValueStack can be defined as a storage structure where the data associated with the current request is stored.</p>
<p>The properties of this bean is directly accessible from the JSP pages using OGNL expresion language.</p>
<h5>Listing 1. Employee.java</h5>
<pre class="brush: java; title: ; notranslate">public class Employee {
    private int empno;
    private String name;
    private String jobtitle;
    private String unit;//business unit  - Retail,Testing, etc
    private String technology;//current working technology
	// getter  &amp;amp; setter methods
}</pre>
<h2>Struts 2.0 Action Class <strong>Registration.java</strong></h2>
<p>As you are already aware of , Struts 2 do not have the ActionForm concept. But those of you ,who would like to use such a feature in Struts 2, they can create a POJO that holds the form data in its properties and then create an Action class that implements the ModelDriven interface. This is what we have done in the sample described here.</p>
<p>Please note that when you implement ModelDriven interface, you need to get the model object using the getModel() method. The Preparable interface is implemented here so that the action class can prepare itself. If you don&#8217;t have anything to prepare, there&#8217;s no reason to implement Preparable. Here we are initializing the instance of the Employee object with the prepare() method of the Preparable interface.</p>
<h5>Listing 2 : Model Driven Action class &#8211; Registration.java</h5>
<pre class="brush: java; title: ; notranslate">package com.myaction;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Registration extends ActionSupport implements ModelDriven, Preparable {

    Employee employee;
    SessionFactory sessionFactory = null;
    Session session = null;

    public String execute() {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
            Transaction transaction = session.beginTransaction();
            session.saveOrUpdate(employee);
            transaction .commit();
            System.out.println(&quot;Record Inserted Successfully&quot;);
        } catch (HibernateException hibernateException) {
            System.out.println(hibernateException.getMessage());
            session.close();
            return &quot;ERROR&quot;;
        }
        return &quot;SUCCESS&quot;;
    }

    @Override
    public Employee getModel() {
        return employee;
    }
    @Override
    public void prepare() throws Exception {
        employee = new Employee();
    }
}</pre>
<p>In this action class we are obtaining the SessionFactory instance from the hibernate configuration. Once the SessionFactory instance is obtained, you can create the Session object and invoke the necessary methods for insertion / updation of the records in the table.</p>
<h2><strong>JSP Pages </strong></h2>
<p>We use three JSP pages in this application. The first one is the index.jsp page that accepts the registration details of the employee. Upon submiting this form, the action class&#8217; execute method is invoked and data is strored in the database. Success.jsp(Listed next) will be shown to the user upon successful insertion of the data.</p>
<p>If an error occurs during insertion , Error.jsp is displayed.</p>
<h5>Listing 3 :index.jsp</h5>
<pre class="brush: java; title: ; notranslate">&lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
    &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;%@taglib uri=&quot;/struts-tags&quot;  prefix=&quot;s&quot;%&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;JSP Page&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;center&gt;
            &lt;!-- &lt;img src=&quot;PDT_TVM_SMall.JPG&quot;/&gt; --&gt;
            &lt;h1&gt;Registration Form&lt;/h1&gt;
            &lt;s:form action=&quot;Registration&quot;&gt;
                &lt;table bgcolor=&quot;pink&quot;&gt;
                    &lt;tr&gt;
                        &lt;td&gt;
                            &lt;s:textfield name=&quot;empno&quot; label=&quot; Employee Id &quot; value=&quot;&quot; /&gt;
                        &lt;/td&gt;
                        &lt;td&gt;
                            &lt;s:textfield name=&quot;name&quot; label=&quot; Name&quot; /&gt;
                        &lt;/td&gt;
                        &lt;td&gt;
                            &lt;s:textfield name=&quot;jobtitle&quot; label=&quot; Job Title &quot; /&gt;
                        &lt;/td&gt;
                        &lt;td&gt;
                            &lt;s:combobox label=&quot; Business Unit &quot; name=&quot;unit&quot;
                                        headerValue=&quot;--- Please Select ---&quot;
                                        headerKey=&quot;1&quot;
                                        list=&quot;{'Retail','HR','Quality','R&amp;D','Testing','Facilities'}&quot; /&gt;
                        &lt;/td&gt;
                        &lt;td&gt;
                            &lt;s:combobox label=&quot; Current Technology Area&quot; name=&quot;technology&quot;
                                        headerValue=&quot;--- Please Select ---&quot;
                                        headerKey=&quot;1&quot;
                                        list=&quot;{'Java','J2EE','.NET','Main Frame','Others'}&quot;/&gt;
                        &lt;/td&gt;
                        &lt;td colspan=&quot;0&quot;&gt;&lt;s:submit label=&quot;Register&quot;/&gt;&lt;/td&gt;
                    &lt;/tr&gt;
                &lt;/table&gt;
            &lt;/s:form&gt;
        &lt;/center&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<h5>Listing 4 : Success.jsp</h5>
<pre class="brush: java; title: ; notranslate">&lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot; import=&quot;com.myaction.Employee&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
   &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;
&lt;%@taglib prefix=&quot;s&quot;  uri=&quot;/struts-tags&quot;%&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;JSP Page&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;&lt;center&gt;
            &lt;br&gt;  &lt;br&gt;  &lt;br&gt;  &lt;br&gt;
            &lt;h1 style=&quot;color:chocolate&quot;&gt; &lt;s:property value=&quot;name&quot;/&gt; registered successfully !!&lt;/h1&gt;
               &lt;/center&gt;
           &lt;/body&gt;
&lt;/html&gt;</pre>
<h5>Listing 5 : Error.jsp</h5>
<pre class="brush: java; title: ; notranslate">
&lt;%@page contentType=&quot;text/html&quot; pageEncoding=&quot;UTF-8&quot; errorPage=&quot;Error.jsp&quot;%&gt;
&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;
   &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;

&lt;html&gt;
    &lt;head&gt;
        &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;
        &lt;title&gt;Error Page&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Some Error Occurred !!  &lt;/h1&gt;
    &lt;/body&gt;
&lt;/html&gt;
</pre>
<h2><strong>Oracle Database table structure</strong></h2>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/21.jpg"><img class="aligncenter size-medium wp-image-1021" title="2" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/02/21-225x300.jpg" width="225" height="300" /></a></p>
<h5>Listing 6 : web.xml</h5>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;web-app version=&quot;3.0&quot; xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd&quot;&gt;
    &lt;filter&gt;
        &lt;filter-name&gt;struts2&lt;/filter-name&gt;
        &lt;filter-class&gt;org.apache.struts2.dispatcher.FilterDispatcher&lt;/filter-class&gt;
    &lt;/filter&gt;
    &lt;filter-mapping&gt;
        &lt;filter-name&gt;struts2&lt;/filter-name&gt;
        &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
    &lt;/filter-mapping&gt;
    &lt;session-config&gt;
        &lt;session-timeout&gt;
            30
        &lt;/session-timeout&gt;
    &lt;/session-config&gt;
    &lt;welcome-file-list&gt;
        &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt;
    &lt;/welcome-file-list&gt;
&lt;/web-app&gt;</pre>
<h2>Hibernate and Struts 2 configuration files</h2>
<h5>Listing 7 : Struts.xml</h5>
<pre class="brush: java; title: ; notranslate">&lt;!DOCTYPE struts PUBLIC
&quot;-//Apache Software Foundation//DTD Struts Configuration 2.0//EN&quot;
&quot;http://struts.apache.org/dtds/struts-2.0.dtd&quot;&gt;

&lt;struts&gt;
    &lt;!-- Configuration for the default package. --&gt;
     &lt;package name=&quot;default&quot; extends=&quot;struts-default&quot;&gt;
        &lt;action name=&quot;Registration&quot; class=&quot;com.myaction.Registration&quot;&gt;
            &lt;result name=&quot;SUCCESS&quot;&gt;/Success.jsp&lt;/result&gt;
             &lt;result name=&quot;ERROR&quot;&gt;/Error.jsp&lt;/result&gt;
        &lt;/action&gt;
    &lt;/package&gt;
&lt;/struts&gt;
</pre>
<h5>Listing 8 : hibernate.cfg.xml – Hibernate configuration file</h5>
<pre class="brush: java; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC &quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
&quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;
&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;property name=&quot;hibernate.dialect&quot;&gt;org.hibernate.dialect.Oracle8iDialect&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.driver_class&quot;&gt;oracle.jdbc.OracleDriver&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.url&quot;&gt;jdbc:oracle:thin:@10.154.117.76:1521:oracle&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.username&quot;&gt;user&lt;/property&gt;
        &lt;property name=&quot;hibernate.connection.password&quot;&gt;password&lt;/property&gt;
        &lt;property name=&quot;hibernate.hbm2ddl.auto&quot;&gt;update&lt;/property&gt;
        &lt;property name=&quot;hibernate.show_sql&quot;&gt;true&lt;/property&gt;
        &lt;mapping resource=&quot;Employee.hbm.xml&quot;/&gt;
    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<h5>Listing 9 : Employee.hbm.xml &#8211; hibernate mapping file</h5>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN&quot;
&quot;http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd&quot;&gt;
&lt;hibernate-mapping&gt;
  &lt;class name=&quot;com.myaction.Employee&quot; table=&quot;StrutsHibEmployee&quot;&gt;
    &lt;id column=&quot;EMPNO&quot; name=&quot;empno&quot; type=&quot;int&quot;&gt;
      &lt;generator class=&quot;assigned&quot;/&gt;
    &lt;/id&gt;
    &lt;property column=&quot;EMPNAME&quot; name=&quot;name&quot; type=&quot;string&quot;/&gt;
    &lt;property column=&quot;ROLE&quot; name=&quot;jobtitle&quot; type=&quot;string&quot;/&gt;
    &lt;property column=&quot;UNIT&quot; name=&quot;unit&quot; type=&quot;string&quot;/&gt;
    &lt;property column=&quot;TECHNOLOGY&quot; name=&quot;technology&quot; type=&quot;string&quot;/&gt;
  &lt;/class&gt;
&lt;/hibernate-mapping&gt;</pre>
<p>Run the application. Sample screen shots are shown below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/31.jpg"><img class="aligncenter size-medium wp-image-1022" title="3" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/02/31-300x176.jpg" width="300" height="176" /></a></p>
<p>Output can be verified in the database as below.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/02/41.jpg"><img class="aligncenter size-medium wp-image-1018" title="4" alt="" src="http://www.javabeat.net/wp-content/uploads/2011/02/41-300x100.jpg" width="300" height="100" /></a></p>
<h2>Summary</h2>
<p>Integrating <strong>Struts 2.0 with Hibernate</strong> is very simple. From the sample explained in the article, you can see that there is no need of using any separate pluggins for this. What is required is to get the <strong>SessionFactory</strong> object in the <em>Action class</em> and use it the way you use it in normal Java Applications.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/02/integrating-struts-2-0-applications-with-hibernate/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX Support in Struts 2.0</title>
		<link>http://www.javabeat.net/2007/06/ajax-support-in-struts-2-0/</link>
		<comments>http://www.javabeat.net/2007/06/ajax-support-in-struts-2-0/#comments</comments>
		<pubDate>Sat, 09 Jun 2007 01:44:38 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[Struts 2.0]]></category>
		<category><![CDATA[Web Frameworks]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=54</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Ajax or Asynchronous JavaScript and XML was introduced by Jesse James Garrett in 2005. He is called the “Father of Ajax” .Ajax is a collection of concepts and technologies that allows richer and more interactive user interaction with the web applications. The Ajax engine allows the user’s interaction with the application to happen asynchronously — [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><span style="font-size: 13px;">Ajax or Asynchronous JavaScript and XML was introduced by Jesse James Garrett in 2005. He is called the “Father of Ajax” .Ajax is a collection of concepts and technologies that allows richer and more interactive user interaction with the web applications. The Ajax engine allows the user’s interaction with the application to happen asynchronously — independent of communication with the server. So the user is never staring at a blank browser window and an hourglass icon, waiting around for the server to do something.</span></p>
<h2>Who is using AJAX</h2>
<p>The most popular and the biggest user of AJAX is Google. Orkut, Gmail, the latest beta version of Google Groups, Google Suggest, and Google Maps — are Ajax applications Google mail, Google calendar and Google home page are some examples. In your Google mailbox the “loading” that is displayed in the top right corner is using these Ajax technologies. The new Yahoo homepage too uses some of these technologies. Another cool Ajax implemented website would be <a href="http://www.pageflakes.com">www.pageflakes.com</a> Others are following suit: many of the features that people love in Flickr depend on Ajax, and Amazon’s A9.com search engine applies similar techniques.</p>
<h2>The BackScreen of Ajax</h2>
<p>In traditional webpages, the pages will be reloaded for each and every request. But in most of the cases only a part of the page will be processed. Hence such a page reload is unnecessary. <strong>Thus the usage of ajax plays a efficient role. In the webpages, that are using ajax, only the part of the page that has to be processed will be transferred to the web server and the processed data will be loaded in the page without a page reload.</strong></p>
<h2>AJAX internals</h2>
<p>AJAX is not a single technology as mentioned earlier. It is important to remember that AJAX is not Java or .NET dependent.</p>
<p>Whatever be your back end code, you can use AJAX to communicate with it. People prefer AJAX for the high speed with which it works. It does it with three basic ways</p>
<ul style="list-style-type: decimal;">
<li>Better utilization of browser cache</li>
<li>Batching up of network requests in a single packet to reduce network latency issues</li>
<li>Decreasing the workload on the server by not requiring it to process the entire page</li>
</ul>
<h2>Where can we use AJAX</h2>
<dl>
<dt>Forms:</dt>
<dd>Web based forms are slow. AJAX can definitely improve the performance of web-based formsUser Communication:</dd>
<dd>User communications like chat pages, voting’s and ratings can be done efficiently using AJAX</dd>
<dt>News:</dt>
<dd>RSS feed is another popular concept where AJAX can be used</dd>
<dt>Data Manipulation:</dt>
<dd>This includes some sort of filtering data, selecting names from one combo box to another, sorting data, invoking the suggest criteria or a hint</dd>
</dl>
<h2>Defining Ajax</h2>
<p>As we have seen an introduction to AJAX, let us try to define it. Ajax isn’t a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporates:</p>
<ul style="list-style-type: circle;">
<li>Standards-based presentation using XHTML and CSS;</li>
<li>Dynamic display and interaction using the Document Object Model;</li>
<li>Data interchange and manipulation using XML and XSLT;</li>
<li>Asynchronous data retrieval using XMLHttpRequest;</li>
</ul>
<p>And JavaScript binding everything together.<br />
So, how does AJAX does this sending request and getting response from the backend server??</p>
<p>Using the XML Http Request object.</p>
<h2>XML Http Request object</h2>
<p>The XML HttpRequest was introduced by Microsoft in Internet Explorer 5.0. Recently , Mozilla and apple have included support for this in their web browsers(Firefox and Safari).This object is the fundamental basis for Ajax. Microsoft implementation is different from that of other web browsers, so when you create this object in your code, you need to do a typical browser check.</p>
<p>For Internet Explorer, we can create this object using,</p>
<p><strong>Var req = new ActiveXObject(“Microsoft.XMLHTTP”);</strong></p>
<p>For firefox and safari,</p>
<p><strong>Var req = new XMLHttpRequest();</strong></p>
<h2>Struts and Ajax in Action</h2>
<p>As we have seen enough of the theory behind the working of Ajax in struts let us see an example. Simple example is loading a drop down depending on the selected item in another drop down. We need to populate the characters in a “showcharacters” dropdown when a particular TV Show is selected in the “showTVShow” drop down using AJAX. Let us see the Ajax request response cycle for this scenario.</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2007/06/1.bmp"><img class="aligncenter  wp-image-2288" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2007/06/1.bmp" width="352" height="351" /></a></p>
<p><center>Fig 1.1 Ajax Request Response Cycle</center></p>
<h3>Step 1: Create a jsp page (“tvshow.jsp”)</h3>
<p>Let us take three TV shows which I like.”Lisse Maguire”,” That’s so Raven” and “Dhoom Machallo Dhoom”. We need to populate the characters dropdown as and when the TV Show dropdown value changes , so we decide to call the javascript in the “onchange()” of the select box.</p>
<pre class="brush: java; title: ; notranslate">&lt;html:form action=&quot;showCharacters.do&quot;&gt;
		TV Show:
		&lt;html:select property=&quot;TVShowSelect&quot;
						onchange=&quot;retrieveURL(' showCharacters.do?tvShow=' + this.value);&quot;&gt;
			&lt;html:option value=&quot;Lissie Maguire&quot;&gt; Lissie Maguire &lt;/html:option&gt;
			&lt;html:option value=&quot;That’s so Raven&quot;&gt; That’s so Raven &lt;/html:option&gt;
			&lt;html:option value=&quot;Dhoom machale&quot;&gt; Dhoom machale &lt;/html:option&gt;
		&lt;/html:select&gt;
		&lt;br&gt;
		Characters: &lt;span id=&quot;characters&quot;&gt;&lt;/span&gt;
	&lt;/html:form&gt;	</pre>
<p>Here we are sending a URL to the Java script function.</p>
<pre class="brush: java; title: ; notranslate">“’ showCharacters.do?tvShow=' + this.value”</pre>
<p>We are appending the selected item with the URL as a query string. We can also just send the Url and append the form contents in the java script.</p>
<h3>Step:2 Making the AJAX Call to the Server</h3>
<p>In the java script we need to create a XML HttpRequest object</p>
<pre class="brush: java; title: ; notranslate">	function retrieveURL(url)
	{
	if (window.XMLHttpRequest)
	{
	// Non-IE browsers
				req = new XMLHttpRequest();
				req.onreadystatechange = processStateChange;
				try {
					 req.open(&quot;GET&quot;, url, true);
				} catch (e) {
					 alert(e);
				}
				req.send(null);
			} else if (window.ActiveXObject) { // IE

				 req = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
				if (req) {
					 req.onreadystatechange = processStateChange;
					 req.open(&quot;GET&quot;, url, true);
					 req.send();
				 }
			}
	  }</pre>
<p>Within the retrieveURL() method, the line req.onreadystatechange = processStateChange (note: no brackets) tells the browser to call the processStateChange() method once the server sends back its response. This method (now standard in AJAX) also determines whether it should use the Internet Explorer (ActiveX) or Netscape/Mozilla (XmlHttpRequest) object to ensure cross-browser compatibility.</p>
<p>Now when the XMLHttpRequest object is created , we ask the browser to call the processstatechange method when we get the response from the server.</p>
<h3>Step 3: Configure action path in struts-config</h3>
<p>This is the same old struts functioning.</p>
<p>“’showCharacters.do” is configured in the struts-config.xml</p>
<p><strong>struts-config.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;action path=&quot;/showCharacters &quot; type=&quot;ShowTVAction&quot; validate=&quot;false&quot; &gt;
			&lt;forward name=&quot;success&quot; path=&quot;/pages/showCharacters.jsp&quot; /&gt;
	&lt;/action&gt;</pre>
<h3>Step 4: Write the action class</h3>
<p>The action class has to get the value selected in the TVShow dropdown and Get the appropriate list of characters using the function getCharacters(String tvShow) .</p>
<pre class="brush: java; title: ; notranslate">public class ShowTVAction extends Action {

	public ActionForward execute(ActionMapping mapping, ActionForm inForm, HttpServletRequest request, HttpServletResponse response) throws Exception {

		 // Get a list of characters associated with the select TV show
		 String tvShow = (String)request.getParameter(&quot;tvShow&quot;);
			if (tvShow == null) {
				 tvShow = &quot;&quot;;
			}
			ArrayList characters = getCharacters(tvShow);
			request.getSession().setAttribute(&quot;characters&quot;, characters);
		 response.setContentType(&quot;text/html&quot;);
		 return mapping.findForward(&quot;success&quot;);
	  } // End execute()

	  // This method returns a list of characters for a given TV show.  If no TV
	  // show is selected, i.e., initial page view, am empty ArrayList is returned.

	  private ArrayList getCharacters (String tvShow) {

		 ArrayList al = new ArrayList();

			if (tvShow.equalsIgnoreCase(&quot;Lissie Mcguire&quot;)) {
				 al.add(&quot;Lizzie Mcguire&quot;);
				 al.add(&quot;Mathew Mcguire&quot;);
				 al.add(&quot;Miranda&quot;);
				 al.add(&quot;Gordon&quot;);
		 }

		 if (tvShow.equalsIgnoreCase(&quot;That’s so Raven &quot;)) {
				al.add(&quot;Raven&quot;);
				al.add(&quot;Chelse”);
				al.add(&quot;Orlanda&quot;);
				al.add(&quot;Victor Backstor&quot;);
				al.add(&quot;Cory Backstor&quot;);
			}

		if (tvShow.equalsIgnoreCase(&quot;Dhoom machale &quot;)) {
				al.add(&quot;Priyanka&quot;);
				al.add(&quot;Koyel&quot;);
				al.add(&quot;Nehal&quot;);
				al.add(&quot;Aadhiraj&quot;);
				al.add(&quot;Maleni&quot;);
			}

			return al;

	  } // End getCharacters()

	} // End class</pre>
<p>Then it sets the Appropriate characters in the session and returns the keyword “success” Thus the control passes to showCharacters.jsp</p>
<h3>Step 5: Write the contents you need to reload in the characters drop down (“ShowCharacters.jsp”)</h3>
<p>In the showCharacters.jsp we load the contents of the characters drop down by taking their values from the session. Remember to add the tag libraries and surround the code with a form tag.</p>
<p><strong>ShowCharacters.jsp</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;html:select property=&quot;TVShowSelect&quot;&gt;
		  &lt;logic:present name=&quot;characters&quot;&gt;
				&lt;%ArrayList ch = (ArrayList)  request.getSession().getAttribute(&quot;characters&quot;);
				String[] s = new String[ch.size()];
				ch.toArray(s);
				for(int i=0;i&lt;s.length;i++)
				{%&gt;
					 &lt;html:option value =&quot;&lt;%=s[i] %&gt;&quot; &gt;&lt;/html:option&gt;
				&lt;%} %&gt;
		  &lt;/logic:present&gt;
	&lt;/html:select&gt;</pre>
<p>Thus the showCharacters.jsp is the response from the Back end server. Once the response form the server is got by the browser. It calls the processStateChange() method</p>
<h3>Step 6: Updating the Web Page with the AJAX Response</h3>
<p>So far, we have looked at the JavaScript to do the AJAX call (listed above) and the Struts Action, ActionForm, and JSP (mostly the same, with the addition of tags). To complete our understanding of the Struts-AJAX project, we need to look at the following JavaScript function that is responsible for updating the current web page when the results from the server are received.</p>
<p>processStateChange(): The method name that we set before making the AJAX call. The XMLHttpRequest/Microsoft.XMLHTTP object calls this method once the server has completed sending back its response.</p>
<pre class="brush: java; title: ; notranslate">function processStateChange() {
			if (req.readyState == 4) { // Complete
			if (req.status == 200) { // OK response
					document.getElementById(&quot;characters&quot;).innerHTML = req.responseText;
			} else {
				 alert(&quot;Problem: &quot; + req.statusText);
			 }
		 }
	  }</pre>
<p>Here readystate is checked .If it is equal to 4 , it means the response is completely received and the status of the response is checked to 200.</p>
<p>If everything fit in, the response is set as the innerHTML of the span “characters”. We can also give the response to a div.</p>
<p>Thus we have done a asynchronous call to the back end and got the response and set it to a span element. Only the contents of the span have been reloaded while the rest of the page remained there.</p>
<h2>Flow of Control</h2>
<p>By adding the above JavaScript code to our application, the following steps now happen on the server and on the browser.</p>
<ul style="list-style-type: decimal;">
<li>The page loads as per a normal Struts application.</li>
<li>The user changes a dropdown value, triggering an onChange() event, which calls the retrieveURL() JavaScript function</li>
<li>This JavaScript function makes a (background) call to the Struts Action on the server</li>
<li>This JavaScript function also sets the name of a second JavaScript function, which will be called when the server response is finished. In this case, it is set to the processStateChange() method.</li>
<li>As expected, when the server response is finished, the processStateChange() method is called.</li>
<li>The JavaScript sets the response to a span in the page</li>
</ul>
<h2>New Features in Struts 2.0 for AJAX</h2>
<p>One of the useful enhancements in Struts 2.0 is the introduction of AJAX Theme</p>
<p>The Ajax theme extends the xhtml theme with AJAX features. The theme uses the popular DOJO AJAX/JavaScript toolkit. The new AJAX features include:</p>
<ul style="list-style-type: disc;">
<li>AJAX Client Side Validation</li>
<li>Remote form submission support (works with the submit tag as well)</li>
<li>An advanced div template that provides dynamic reloading of partial HTML</li>
<li>An advanced a template that provides the ability to load and evaluate JavaScript remotely</li>
<li>An AJAX-only tabbed Panel implementation</li>
<li>A rich pub-sub event model</li>
<li>Interactive auto complete tag</li>
</ul>
<p>The framework provides a set of tags to help you ajaxify your applications, on Dojo.</p>
<p>To use the Ajax tags you need to set the &#8220;theme&#8221; attribute to &#8220;Ajax&#8221;.<strong>Use the head tag to configure the page for the Ajax theme.</strong></p>
<h3>URL</h3>
<p>The &#8220;href&#8221; attribute must contain a url built with the URL tag<br />
Example:</p>
<pre class="brush: java; title: ; notranslate"> Initial Content</pre>
<p>Set the &#8220;debug&#8221; attribute of the head tag to &#8220;true&#8221; to display debug information on the bottom of the page</p>
<h3>Indicators</h3>
<p>Use indicators to notify the user that a request is in progress. The indicator should be hidden when the page is loaded.</p>
<h3>Dynamic Div</h3>
<p>The div tag is a content area that can load its content asynchronously. The div tag can be forced to reload its content using topics. To define the topics that will trigger the refresh of the panel, use the &#8220;listenTopics&#8221; attribute. This tag will load its content when the page is loaded, unless &#8220;autoStart&#8221; is set to &#8220;false&#8221;.<br />
While Dojo supports crossdomain XHR using IFrames, the S2 Ajax tags do not (yet)</p>
<p>This div will refresh every time the topics &#8220;/refresh0&#8243; or &#8220;/refresh1&#8243; are published:</p>
<p>to publish a topic use.</p>
<pre class="brush: java; title: ; notranslate">dojo.event.topic.publish(&quot;/refresh”);</pre>
<h3>Retrieve Remote Data</h3>
<p>The simplest way to use the div tag is to provide an href attribute. For example</p>
<p>What this does after the HTML page is completely loaded; the specified URL will be retrieved asynchronously in the browser. The entire contents returned by that URL will be injected in to the div and will update every minute after a two second delay: Include the attribute errorText in case the URL is not loaded</p>
<pre class="brush: java; title: ; notranslate">errorText=&quot;Unable to contact weather server&quot;</pre>
<h3>Submit</h3>
<p>The submit tag can be used to update the content of its &#8220;targets&#8221; attribute with text returned from the asynchronous request. &#8220;targets&#8221; is a comma-delimited list of element ids. The &#8220;targets&#8221; attribute is optional.</p>
<p>Regular submit button that will update the content of div1:</p>
<div id="div1">Div 1</div>
<p>For using Submit button using an image add the attribute src</p>
<pre class="brush: java; title: ; notranslate">src=&quot;${pageContext.request.contextPath}/images/struts-rocks.gif&quot;</pre>
<p>If the submit button is used inside a form (href is not required on this case), the form will be submitted asynchronously using<br />
A submit button can be used to submit a form, even if it is outside the form, using &#8220;formId&#8221;, &#8220;formFilter&#8221; and &#8220;href&#8221;. Note that in this case &#8220;href&#8221; is required.</p>
<pre class="brush: java; title: ; notranslate"> &lt;input type=&quot;textbox&quot; name=&quot;data&quot; /&gt;</pre>
<h3>Anchor</h3>
<p>The anchor tag, like the submit tag; can be used to update the content of its &#8220;targets&#8221; attribute with text returned from the asynchronous request. &#8220;Targets&#8221; is a comma-delimited list of element ids. The &#8220;targets&#8221; attribute is optional.</p>
<p>This anchor will update the content of div1 and div2 with text returned form &#8220;/AjaxTest.action&#8221;</p>
<div id="div1">Div 1</div>
<div id="div2">Div 2</div>
<p>Update divs If the anchor tag is used inside a form (href is not required on this case), the form will be submitted asynchronously:</p>
<pre class="brush: java; title: ; notranslate">
	  &lt;input type=&quot;textbox&quot; name=&quot;data&quot; /&gt;
	  Submit form</pre>
<p>Using the anchor tag to submit a form:</p>
<pre class="brush: java; title: ; notranslate">
	  &lt;input type=&quot;textbox&quot; name=&quot;data&quot; /&gt;

	Submit form</pre>
<h3>AJAX Client Side Validation</h3>
<ul style="list-style-type: disc;">
<li>Ajax Validation requires DWR servlet being setup, Dojo and the Ajax theme being used.</li>
<li>In the Ajax theme, DWR is used for normal validation while Dojo handles everything else (widgets, XHR, browser JS events etc.)</li>
<li>In order for validation to function properly it is advised to use standard Struts Tags</li>
</ul>
<h3>Setup DWR</h3>
<p>DWR could be setup by having the following dwr configuration (dwr.xml) at /WEB-INF/ directory. If it needs to be in other places.</p>
<p>A DWRServlet need to be registered with the web application as well. The following shows a typical web.xml with DWRSerlvet.</p>
<pre class="brush: java; title: ; notranslate">
		   dwr
		   uk.ltd.getahead.dwr.DWRServlet

			   debug
			   true

	&lt;!-- JavaServer Faces Servlet Configuration, not used directly --&gt;

		faces
		javax.faces.webapp.FacesServlet
		1

		&lt;!-- JavaServer Faces Servlet Mapping, not called directly --&gt;

		   faces
		   *.action

		   dwr
		   /dwr/*</pre>
<h3>Add a form attribute</h3>
<p>Add the attribute validate to the. The validate=&#8221;true&#8221; option is set for thetag to enable onblur-triggered validation</p>
<pre class="brush: java; title: ; notranslate">Validation - Basic</pre>
<p>Now as usual have a form bean for this form with getters and setters and constructors, and configure the validation.xml for required fields</p>
<pre class="brush: java; title: ; notranslate">You must enter a name1319
				Only people ages 13 to 19 may take this quiz</pre>
<h2>Summary</h2>
<p>This is a simple introduction to Ajax.Start implementing it and you will find it simple, easy and attractive. One can use it to do many different things. It all accounts your creativity. It is a good approach in many cases, but will not be appropriate in others. If reaching the maximum possible audience is your goal, you would want to stay away from this. If a user disabling scripting in their browser might be a concern (and your site wouldn’t be any good without it), this probably isn’t a good answer either. There are other reasons to stay away from it in some situations, but the bottom line is treat it like any other tool in your toolbox: it will be right for some jobs, maybe &#8220;not so&#8221; for others.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/06/ajax-support-in-struts-2-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Struts 2.0 and Validations using Annotations</title>
		<link>http://www.javabeat.net/2007/05/struts-2-0-introduction-and-validations-using-annotations/</link>
		<comments>http://www.javabeat.net/2007/05/struts-2-0-introduction-and-validations-using-annotations/#comments</comments>
		<pubDate>Wed, 30 May 2007 12:53:36 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Struts 2.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=179</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article provides an introduction to Struts 2.0 and its new Validation Features. Since Struts 2.0 is new, the first few sections of the article discusses in brief about the basics of Struts 2.0, its architecture and its various New Features. The rest of the article is dedicated towards explaining about the new Validation Features [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><span style="font-size: 13px;">This article provides an introduction to </span><strong style="font-size: 13px;"><em>Struts 2.0</em></strong><span style="font-size: 13px;"> and its new </span><strong style="font-size: 13px;"><em>Validation Features</em></strong><span style="font-size: 13px;">. Since Struts 2.0 is new, the first few sections of the article discusses in brief about the basics of Struts 2.0, its architecture and its various New Features. The rest of the article is dedicated towards explaining about the new Validation Features available. Struts is an </span><strong style="font-size: 13px;"><em>Open-Source Web Application Framework</em></strong><span style="font-size: 13px;"> that simplifies the creation of a </span><strong style="font-size: 13px;"><em>Java Web Application</em></strong><span style="font-size: 13px;">. It is based on the </span><strong style="font-size: 13px;"><em>Model-View-Controller 2 (MVC 2) Architecture</em></strong><span style="font-size: 13px;"> which was originally found in a language called </span><strong style="font-size: 13px;"><em>SmallTalk</em></strong><span style="font-size: 13px;">. The recent version of Struts is Struts 2.0 and it has borrowed most of the concepts in terms of architecture and functionality from two frameworks namely </span><strong style="font-size: 13px;"><em>WebWork</em></strong><span style="font-size: 13px;"> and </span><strong><em>XWork</em></strong>.</p>
<h2>Struts 2.0 &#8211; MVC Architecture</h2>
<p align="justify">Struts 2.0 is based on <strong><em>MVC 2 Architecture</em></strong>. MVC is mainly concentrated in splitting the whole set of logic that happens in an Application into three different layers namely the <strong><em>Model</em></strong>, <strong><em>View</em></strong> and the <strong><em>Controller</em></strong>. In Struts 2.0, the Controller acts as a mediator between the View and the Model components. Whenever a request comes from a client, it is this Controller component who intercepts the request before being passed to <strong><em>Appropriate Handler</em></strong>.</p>
<p align="justify">Model represents the application data as well as the business logic that operates on the Data. Whenever the Framework routes the request to some Action class, the <strong><em>Action</em></strong> Class will do the <strong><em>Business Processing Logic</em></strong> which results in the <strong><em>State of the Application</em></strong> getting affected. After the application&#8217;s state is affected, the control is returned back to the Controller which determines which <strong><em>View</em></strong> to be Rendered to the Client Application.</p>
<p align="justify">View is the <strong><em>Display Surface</em></strong> given as a response back to the Client populated with values. Struts 2.0 is not restricted in having JSP as its only View. Any <strong><em>View Technolgy</em></strong> can be chosen to render the Client Surface. It can be <strong><em>JSP</em></strong>, <strong><em>Velocity</em></strong>, <strong><em>Freemaker</em></strong>, or even <strong><em>XSLT</em></strong>. Even a brand new View technology can be plugged-in easily to the Struts Framework.</p>
<h2>The Flow of a Struts 2.0 Application</h2>
<p align="justify">The following are the sequence of steps that will happen when a Html Client makes a request to a Web Application built on top of Struts 2.0</p>
<ul>
<li>The <strong><em>Client</em></strong> (which is usually a Html Browser) makes a Request to the Web Application.</li>
<li>The <strong><em>Web Server</em></strong> will search for the <strong><em>Configuration Information</em></strong> that is very specific to the <strong><em>Web Application</em></strong> (taken from the web.xml file), and will identity which <strong><em>Boot-strap Component</em></strong> has to be loaded to serve the <strong><em>Client&#8217;s Request</em></strong>.</li>
<li>In Struts 2.0, this Component is going to be a <strong><em>Servlet Filter</em></strong> (whereas in Struts 1.0, the component is an Action Servlet).</li>
<li>The Filter Servlet then finds out the <strong><em>Action Class</em></strong> for this Request that is mapped in the Configuration File.</li>
<li>Before passing the Request to the Action class, the Controller passes the Request to a series of <strong><em>Interceptor Stack</em></strong> (explained later).</li>
<li>Then the Request Object is passed on to the corresponding <strong><em>Action Class</em></strong>.</li>
<li>The Action Class then executes the <strong><em>Appropriate Business Logic</em></strong> based on the Request and the Request Parameters.</li>
<li>After the execution of the Business Logic, a <strong><em>Result (&#8220;success&#8221; or &#8220;error&#8221;)</em></strong> is returned either in the form of String or in the form of <strong><em>Result Object</em></strong> back to the Controller.</li>
<li>The Controller uses the Return Result to choose which <strong><em>View</em></strong> to be rendered back to the Client Application.</li>
</ul>
<p align="justify">Let us look into the details of the major steps that was listed above.</p>
<h3>Filter Servlet Loaded and Invoked by the Framework</h3>
<p align="justify">A client makes a Web Request by typing the URL of the Web Application that is hosted in the Web Server something like the following, where localhost is the Machine Name where the Web Server is running, 8080 is the Port Number and hello is the Application Context for the Web Application.</p>
<pre class="brush: java; title: ; notranslate">http://localhost:8080/hello</pre>
<p align="justify">Whenever a Request comes to a <strong><em>Web Application</em></strong> that is <strong><em>Struts 2.0 Enabled</em></strong>, the Web Server will search and load the Configuration Related Information that is very specific to the Application. In the case of a Struts 2.0 enabled Application, the <strong><em>Boot-Strap Component</em></strong> is going to a <strong><em>Filter Servlet</em></strong>. The <strong><em>Configuration Information</em></strong> about the Web Application will be maintained separately in <strong><em>web.xml</em></strong> file. Following is the Xml snippet taken from the web.xml file,</p>
<p><strong>web.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;filter&gt;
    &lt;filter-name&gt;Struts2FilterServlet&lt;/filter-name&gt;
    &lt;filter-class&gt;
        org.apache.struts.action2.dispatcher.FilterDispatcher
    &lt;/filter-class&gt;
&lt;/filter&gt;

&lt;filter-mapping&gt;
    &lt;filter-name&gt;Struts2FilterServlet&lt;/filter-name&gt;
    &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
&lt;/filter-mapping&gt;</pre>
<p align="justify">The above Xml Code tells that whatever be the <strong><em>Request URI Pattern</em></strong> (which is indicated by /*) that comes from the Client, identify the Component named by <strong> <em>Struts2FilterServlet</em></strong> which happens to be the class <code>org.apache.struts.action2.dispatcher.FilterDispatcher</code>.<br />
The Identified Component is then instantiated and then passed with the Request Information.</p>
<h3>Request Intercepted by Interceptors</h3>
<p align="justify"><strong><em>Interceptors</em></strong> provide <strong><em>Pre-processing</em></strong> and <strong><em>Post-processing</em></strong> functionality for a Request or a Response object in a Web Application. For general information about Interceptors, readers can go through  <a href="http://hibernate.javabeat.net/articles/2007/05/interceptors-in-hibernate-introduction/">this</a> section on JavaBeat. A Request Object usually passes through a <strong><em>Series of Interceptors</em></strong> before actually reaching the Framework. Assume that some kind of <strong><em>Authentication and Authorization</em></strong> related stuffs have to be done before a Request Object is being passed to a particular Module. In such a case, we can have the Core Business Logic that does the functionality of authorizing the Client Request in an Interceptor called <code>AuthenticationInterceptor</code> which does the Pre-processing works. Implementing a <strong><em>Custom Interceptor</em></strong> like this is very simple in Struts 2.0. The class structure may look like this,</p>
<p><strong>AuthenticationInterceptor.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myinterceptors;

import com.opensymphony.xwork2.interceptor.*;

class AuthenticationInterceptor implements Interceptor{

    public void init(){}

    public void destroy(){}

    public String intercept(ActionInvocation invocation) throws Exception{

  	   // Get the value of user credentials from the Request and Validate it.

    }
}</pre>
<p align="justify">As we can see, writing a <strong><em>Custom Interceptor</em></strong> is as simple as writing a class that implements the <code>Interceptor</code> interface which is found in the <code>com.opensymphony.xwork2.interceptor</code> package. The method of interest is <code>Interceptor.intercept()</code> which has to be overriden along with the the appropriate business logic. Then the Custom Interceptor has to be made available to the framework<br />
by adding information in the <strong><em>Configuration File</em></strong> (struts.xml) as shown below,</p>
<p><strong>struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;

    ...
    &lt;interceptors&gt;
        &lt;interceptor name = &quot;authentication&quot;
            class = &quot;myinterceptors.AuthenticationInterceptor&quot;&gt;
        &lt;/interceptor&gt;
    &lt;interceptors&gt;
   ...

&lt;/struts&gt;</pre>
<p align="justify">Interceptors are configured into the Web Application in the struts.xml file with the help of <strong><em>&lt;interceptors&gt; and &lt;interceptor&gt;</em></strong> entries. The <strong><em>name</em></strong> attribute is the alias name of the interceptor and it must be unique among the other set of Interceptor names.<br />
The <strong><em>class</em></strong> attribute identifies the actual implementation class for an Interceptor. The advantages of interceptors is not only limited to this. Interceptors can participate in so many different activities, to name a few &#8211; providing <strong><em>Logging Information to an Application</em></strong>, providing <strong><em>Encryption Facilities</em></strong> for the user input that used to get transmitted across layers, etc.. . Struts 2.0 already comes with a bunch of <strong><em>Built-in Useful Interceptors</em></strong>.</p>
<h3>Performing some Action for a Request</h3>
<p align="justify">After passing through a series of Interceptors, now it is time for the Framework to determine what <strong><em>Action</em></strong> has to be done for the Request. The <strong><em>Mapping between a Request</em></strong> and its <strong><em>Corresponding Action</em></strong> is configurable in the <strong><em>Xml Configuration File</em></strong>.<br />
Assume that in a Web Application, Regitration, Login and Logout represents the different set of actions. Let us have an assumptions that the operations are fairly complex, so that we tend to have individual classes for each of the operation. These things are configured in the <strong><em>struts.xml</em></strong> like the following,</p>
<p><strong>struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;

    &lt;action name = &quot;Registration&quot; class = &quot;hello.RegistrationAction&quot;&gt;
    &lt;action name = &quot;Login&quot; class = &quot;hello.LoginAction&quot;&gt;
    &lt;action name = &quot;Logout&quot; class = &quot;hello.LogoutAction&quot;&gt;

&lt;/struts&gt;</pre>
<p>The <strong><em>Action Class</em></strong> usually acts as a <strong><em>Model</em></strong> and executes a particular business logic depending on the Request object and the Input Parameters. In earlier versions of Struts (before Struts 2.0), an Action class is supposed to extend the <code>org.apache.struts.Action</code> class and has to override the <code>Action.execute()</code> method which takes four parameters. Following is the code snippet of an Action class before Struts 2.0,</p>
<p><strong>MyAction.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myactions;

import java.servlet.http.*;
import org.apache.struts.*;

class MyAction extends Action{

    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws java.lang.Exception {

	    // Do some business logic here.

	}
}</pre>
<p align="justify">In Struts 2.0, an Action class is made flexible as it can be a <strong><em>simple POJO Class</em></strong>. It means that the <strong><em>Action Class</em></strong> doesn&#8217;t need to extend some class or implement an interface. It can be as simple as possible, and the following code snippet proves the same,</p>
<p><strong>MyAction.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myactions;

import com.opensymphony.xwork2.*;

class MyAction extends Action{

    public String execute(){
        // Some logic here.
    }

}</pre>
<p align="justify"><strong>Here comes the big question!</strong>. Then how can an <code>Action</code> class is supposed to access the <code>HttpServletRequest</code> and the <code>HttpServletResponse</code> objects to get the needed information!!! At this stage it is worth to mention about the <strong><em>Aware-Related Interfaces</em></strong> here.<br />
Suppose that an <code>Action</code> class wants to access the <code>HttpServletRequest</code> object. For this, it has to implement a special Aware Interface called <code>ServletRequestAware</code> and has to override the method <code>setServletRequest(HttpServletRequest request)</code> thereby storing it in an instance variable. So, the new modified action class becomes like this,</p>
<p><strong>MyAction.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myactions;

import javax.servlet.http.*;

import com.opensymphony.xwork2.*;
import org.apache.struts2.interceptor.*;

class MyAction extends Action implements ServletRequestAware{

    private HttpServletRequest request;

    public String execute(){
    }

    public void setServletRequest(HttpServletRequest request){
        this.request = request;
    }
}</pre>
<p align="justify">This above technique is basically an <strong><em>Inversion of Control</em></strong>. Inversion of Control is generally a <strong><em>Push Model</em></strong> which means that the data needed by the Application will be pushed by the <strong><em>Container</em></strong> or the <strong><em>Framework</em></strong>. In our case, we are making the Struts 2.0 Framework to call the method <code>ServletRequestAware.setServletRequest(HttpServletRequest request) </code>thereby populating the Request Object. Similar to this, there are <strong><em>Aware-Related Interfaces</em></strong> for Application, Servlet Request, Servlet Response, Parameters etc namely <code>ApplicationAware</code>, <code>HttpServletRequestAware</code>, <code>HttpServletResponseAware</code>,<br />
<code>ParameterAware</code> respectively.</p>
<h3>Rendering the Result back to the Client</h3>
<p align="justify">As we can see from the method signature, the return type of the <code>Action.excute()</code> method is just a String. This return type defines the <strong><em>Logical Outcome</em></strong> of the Action or the Page. <strong><em>Actual Outcome</em></strong> or the <strong><em>Response of a Page</em></strong> is configurable in the Struts Configuration File. Say the Action class can return a logical &#8216;success&#8217; which tells that the action has be successfully processed or &#8216;failure&#8217; which sadly tells that some thing wrong has happened in the Application. Some <strong><em>Predefined Constants</em></strong> have been defined in the<br />
<code>Action</code> interface for the logical outcomes namely, <code>Action.SUCCESS</code>, <code>Action.ERROR</code>, <code>Action.LOGIN</code>, <code>Action.INPUT </code>and<br />
<code>Action.NONE</code>. Consider the following code snippet,</p>
<p><strong>MyAction.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myactions;

public class MyAction{

    public String execute(){

        if (createOperation()){
            return &quot;create&quot;;
        }else if (deleteOperation()){
            return &quot;delete&quot;;
        }else if( readOperation()){
            return &quot;read&quot;;
        }else if  (writeOperation()){
            return &quot;write&quot;;
        }
        return &quot;error&quot;;
    }
}</pre>
<p align="justify">The above method returns a bunch of <strong><em>Logical Outputs</em></strong> namely &#8220;create&#8221;, &#8220;delete&#8221;, &#8220;read&#8221; and &#8221;write&#8221;. The logical outcomes should have their <strong><em>Corresponding Mappings</em></strong> defined in the struts.xml like the following, <strong>struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;

    …
    &lt;action name = &quot;MyAction&quot; class = &quot;myactions.MyAction&quot;&gt;
        &lt;result name = &quot;create&quot;&gt;/myApp/create.jsp&lt;/result&gt;
        &lt;result name = &quot;delete&quot;&gt;/myApp/delete.jsp&lt;/result&gt;
        &lt;result name = &quot;read&quot;&gt;/myApp/read.jsp&lt;/result&gt;
        &lt;result name = &quot;write&quot;&gt;/myApp/write.jsp&lt;/result&gt;
    &lt;/action&gt;

    …
&lt;/struts&gt;</pre>
<h2>Struts.xml Configuration File</h2>
<p align="justify">All the <strong><em>Configuration Related Information</em></strong> are externalized from a Web Application by maintaining them in a Xml File. The new Struts 2.0 Configuration Xml File is very <strong><em>Simple and Modular</em></strong> when compared with its older versions. Let us look into the structure of the <strong><em>Struts 2.0 Configuration File</em></strong> and the <strong><em>Core Elements</em></strong> within them in detail in the following sections.</p>
<h3>Modularization of Configuration Files</h3>
<p align="justify">The first nice feature is the <strong><em>File Inclusion Faciltity</em></strong>. Assume that in a very complex Web Application, there are multiple modules and each module is designated to be developed by a particular team. Similar to the <strong><em>Modularization of Work</em></strong>, the configuration file can also be made modular using the <strong><em>File Inclusion Facility</em></strong>. For the sake of simplicity, let the assume that there are three modules namely &#8220;admin&#8221;, &#8220;customer&#8221;, &#8220;employer&#8221; in a Web Application. We can define the three modules in three different Configuration Files,<br />
and using the File Inclusion Facility, the three files can be directly included in the <strong><em>Main Configuration File</em></strong>. A Main Configuration File is nothing but a File that includes other Configuration Files. Examine the following code snippet,</p>
<p><strong>Admin-Config.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;
    &lt;!-- Configuration Information Related to Admin Module --&gt;
&lt;/struts&gt;</pre>
<p><strong>Customer-Config.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;
    &lt;!-- Configuration Information Related to Customer Module --&gt;
&lt;/struts&gt;</pre>
<p><strong>Employee-Config.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;
    &lt;!-- Configuration Information Related to Employee Module --&gt;
&lt;/struts&gt;</pre>
<p align="justify">All the above separate Configuration Files can be directly referenced or included in the Root Configuration File with the help of <strong><em>&lt;include&gt;</em></strong> tag like the following,</p>
<p><strong>Struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;

    &lt;!-- Other information goes here --&gt;
    &lt;include file = &quot;Admin-Config.xml&quot;/&gt;
    &lt;include file = &quot;Customer-Config.xml&quot;/&gt;
    &lt;include file = &quot;Employer-Config.xml&quot;/&gt;
    &lt;!-- Other information goes here --&gt;

&lt;/struts&gt;</pre>
<h3>Grouping of Similar Actions inside a Package</h3>
<p align="justify">Packages in Java are logically used to group similar Classes or Interfaces. Similary, there is a <strong><em>&lt;package&gt;</em></strong> tag in Struts 2.0, which is used to <strong><em>Group Similar Actions</em></strong> along with <strong><em>Interceptors</em></strong>, <strong><em>Results</em></strong>, <strong><em>Exceptions</em></strong> etc. Following is the structure of the<br />
<strong><em>package </em></strong>element,</p>
<p><strong>Struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;

    &lt;package name = &quot;MyPackage1&quot;&gt;

        &lt;interceptors&gt;
        &lt;/interceptors&gt;

        &lt;global-results&gt;
        &lt;global-results&gt;

        &lt;action name = &quot;MyAction1&quot;&gt;
        &lt;/action&gt;

        &lt;action name = &quot;MyAction2&quot;&gt;
        &lt;/action&gt;

    &lt;/package&gt;

    &lt;package name = &quot;MyPackage2&quot;&gt;

        &lt;interceptors&gt;
        &lt;/interceptors&gt;

        &lt;global-results&gt;
            &lt;result name = &quot;common-error&quot;&gt;
                /myApp/commons/commonError.jsp
            &lt;/result&gt;
        &lt;global-results&gt;

        &lt;action name = &quot;MyAction3&quot;&gt;
            &lt;result name = &quot;result1&quot;&gt;
                /myApp/myResult1.jsp
            &lt;/result&gt;
        &lt;/action&gt;

        &lt;action name = &quot;MyAction4&quot;&gt;
        &lt;/action&gt;

    &lt;/package&gt;

&lt;/stuts&gt;</pre>
<p align="justify">Assuming that <strong><em>MyAction1</em></strong> and <strong><em>MyAction2</em></strong> are someway related, they are grouped under a package called <strong><em>MyPackage1</em></strong>. All the declaration of <strong><em>Interceptors</em></strong>, <strong><em>Results</em></strong> and <strong><em>Exceptions </em></strong>within the Package <strong><em>MyPackage1</em></strong> will be availabe only within the actions<br />
<strong><em>MyAction1</em></strong> and <strong><em>MyAction2</em></strong>. Similarly all the definition of the Interceptors, Results and Exceptions within the package <strong><em>MyPackage2 </em></strong>will be applicable only for <strong><em>MyAction3</em></strong> and <strong><em>MyAction4 </em></strong>action elements. Packages can also be <strong><em>extended</em></strong> through the means of <strong><em>extends </em></strong>attribute like the following,</p>
<p><strong>Struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;
    ...
    &lt;package name = &quot;MySubPackage&quot; extends = &quot;MyBasePackage&quot;&gt;
        ...
    &lt;/package&gt;
    ...
&lt;/struts&gt;</pre>
<p align="justify">Let us define what a <strong><em>Package Extension</em></strong> is and their advantages. Assume that there is a Package called <strong><em>P1</em></strong> with interceptors <strong><em>I1</em></strong> and<br />
<strong><em>I2</em></strong>, Results <strong><em>R1</em></strong> and <strong><em>R2</em></strong> and <strong><em>Exceptions </em></strong><strong><em>E1</em></strong> and <strong><em>E2</em></strong>. If we say some Package called <strong><em>P2</em></strong> extends <strong><em>P1</em></strong>, then all the elements that are available in <strong><em>P1</em></strong> becomes visible to Package <strong><em>P2</em></strong>. Package Extension is very similar to <strong><em>Class Inheritance</em></strong> which we normally see in any kind of <strong><em>Object Oriented Language</em></strong>.</p>
<h3>Interceptors and Stack</h3>
<p align="justify">As previously discussed, <strong><em>Custom Interceptors</em></strong> can be written and made immediately available in Application by configuring them in the <strong><em>Configuration File</em></strong> with the help of <strong><em>&lt;interceptor&gt;</em></strong> tag. An Interceptor defined can be applied to a particlur <strong><em>Action</em></strong> (or a set of Actions) through the help of <strong><em>&lt;intercept-ref&gt;</em></strong> tag. Following Xml snippet will show this,</p>
<p><strong>Struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;

    &lt;package name = &quot;MyPackage&quot;&gt;

        &lt;interceptors&gt;
            &lt;interceptor name=&quot;logger-interceptor&quot;
                class=&quot;myinterceptors.LoggingInterceptor&quot;&gt;
        &lt;/interceptor&gt;

        &lt;action name = &quot;MyAction&quot;&gt;
            &lt;result name = &quot;MyResult&quot;&gt;
                /myApp/Result1.jsp
            &lt;/result&gt;
            &lt;interceptor-ref name = &quot;logger-interceptor&quot;/&gt;
        &lt;/action&gt;

    &lt;/package&gt;

&lt;/struts&gt;</pre>
<p align="justify">The above code defines an Interceptor called <strong><em>logger-interceptor </em></strong>identified by the <code>class myinterceptors.LoggingInterceptor</code> and the same is included for an action called <strong><em>MyAction</em></strong> with the help of <strong><em>&lt;interceptor-ref&gt;</em></strong> tag. It is very common that a <strong><em>Set of Interceptors</em></strong> (often called <strong><em>Interceptor Stack</em></strong>) to be applied as a whole for one or<br />
more actions. Such a piece of functionality can be easily achieved with the help of <strong><em>&lt;interceptor-stack&gt;</em></strong> element.</p>
<p><strong>struts.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;struts&gt;

    &lt;package name = &quot;MyPackage&quot;&gt;

        &lt;interceptors&gt;
            &lt;!--Some set of common interceptors for a particular action--&gt;
            &lt;interceptor name = &quot;A_I1&quot; class = &quot;MyA_I1&quot;&gt;
            &lt;interceptor name = &quot;A_I2&quot; class = &quot;MyA_I2&quot;&gt;
            &lt;interceptor name = &quot;A_I3&quot; class = &quot;MyA_I3&quot;&gt;
            &lt;interceptor name = &quot;A_I4&quot; class = &quot;MyA_I4&quot;&gt;

            &lt;!--Another set of common interceptors  --&gt;
            &lt;interceptor name = &quot;B_I1&quot; class = &quot;MyB_I1&quot;&gt;
            &lt;interceptor name = &quot;B_I2&quot; class = &quot;MyB_I2&quot;&gt;
            &lt;interceptor name = &quot;B_I3&quot; class = &quot;MyB_I3&quot;&gt;
            &lt;interceptor name = &quot;B_I4&quot; class = &quot;MyB_I4&quot;&gt;
        &lt;/interceptors&gt;

        &lt;interceptor-stack name = &quot;A&quot;&gt;
            &lt;interceptor-ref name = &quot;A_I1&quot;&gt;
            &lt;interceptor-ref name = &quot;A_I2&quot;&gt;
            &lt;interceptor-ref name = &quot;A_I3&quot;&gt;
            &lt;interceptor-ref name = &quot;A_I4&quot;&gt;
        &lt;/interceptor-stack&gt;

        &lt;interceptor-stack name = &quot;B&quot;&gt;
            &lt;interceptor-ref name = &quot;B_I1&quot;&gt;
            &lt;interceptor-ref name = &quot;B_I2&quot;&gt;
            &lt;interceptor-ref name = &quot;B_I3&quot;&gt;
            &lt;interceptor-ref name = &quot;B_I4&quot;&gt;
        &lt;/interceptor-stack&gt;

        &lt;action name = &quot;MyAction1&quot;&gt;
            &lt;interceptor-ref name = &quot;A&quot;/&gt;
        &lt;/action&gt;

        &lt;action name = &quot;MyAction2&quot;&gt;
            &lt;interceptor-ref name = &quot;B&quot;/&gt;
        &lt;/action&gt;

        &lt;/package&gt;

&lt;/struts&gt;</pre>
<p align="justify">The above Xml snippet defines a series of interceptors with the help of <strong><em>&lt;interceptors&gt;</em></strong> tag. Related <strong><em>Set of Interceptors</em></strong> to be added<br />
to an action element is then categorized with the help of <strong><em>&lt;interceptor-stack&gt;</em></strong> element. The categorized Interceptor Stack is then bound to an action element using the same sensible <strong><em>&lt;interceptor-ref&gt;</em></strong> tag. The framework is sensible here, it will find out the value<br />
for the <strong><em>name</em></strong> attribute. If the value is an interceptor name, then the corresponding <code>intercept()</code> method will be invoked, else if the value is an <strong><em>Interceptor-Stack</em></strong>, then all the interceptors within the stack are iterated in the same order as their definition and their<br />
<strong><em>intercept()</em></strong> method will be invoked.</p>
<h2>Validation using Configuration Files and Annotations</h2>
<p align="justify">Struts 2.0 comes with new set of <strong><em>Robust Validation Features</em></strong>. Most of the common Validation Activities related to a Web Application are taken care by the Framework itself which means that only less burden lies on the shoulders of a Developer. Following lists the most commonly used Validations in Struts 2.0,</p>
<ol>
<li><strong>Integer Validation</strong> &#8211; Checks whether the value for a field is an integer and it falls<br />
within the integer range.</li>
<li><strong>Double Validation</strong> &#8211; Checks whether the value for a field is a double and it falls<br />
within the double range.</li>
<li><strong>Date Validation</strong> &#8211; Checks whether the value of the field is a Date value.</li>
<li><strong>Email Validation</strong> &#8211; Validates whether the input string is in appropriate email format<br />
(Eg: userName@someDomain.com).</li>
<li><strong>Url Validation</strong> &#8211; Ensures whether the value for a field is in appropriate URL Format.</li>
<li><strong>Required Validation</strong> &#8211; Checks for the emptiness of a field value.</li>
<li><strong>Required String Validation</strong> &#8211; Checks for the emptiness of a trimmed String value (not null)</li>
<li><strong>String Length Validation</strong> &#8211; Checks whether the given field value is of the specified length.</li>
<li><strong>Regex Validation</strong> &#8211; Ensures whether the field Value given matches the Regular Expression.</li>
</ol>
<h3>5.1) Validations Types based on Scope</h3>
<p align="justify">Validation comes in two different flavors based on its <strong><em>Scope</em></strong>. A Scope defines whether a Validation is dedicated to a <strong><em>Single Field</em></strong> in a Page or it corresponds to a particular <strong><em>Action</em></strong> which may involve more than one fields along with some other constraints. Based on this, the following types are available.</p>
<ul>
<li>Field Validation</li>
<li>Non-Field Validation</li>
</ul>
<h5>5.1.1) Field Validation</h5>
<p align="justify">Validating a Field in a Page for correctness is a common situation for almost any Web Application. As mentioned this type of Validation is restricted to a particular field. Common cases may be validating the username and password field for emptiness. Both<br />
<strong><em>Xml-Based Validation</em></strong> or <strong><em>Annotation-Based Validation</em></strong> can be mentioned for the field elements. The following snippet code is an example of <strong><em>Field-Level Validation</em></strong>.</p>
<p><strong>validation.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;field name=&quot;username&quot;&gt;
    &lt;field-validator type=&quot;required&quot;&gt;
        &lt;message&gt;User name cannot be empty.&lt;/message&gt;
    &lt;/field-validator&gt;
&lt;field-name=&quot;username&quot;&gt;

&lt;field name=&quot;email_address&quot;&gt;
    &lt;field-validator type=&quot;required&quot;&gt;
        &lt;message&gt;Email Address cannot be empty.&lt;/message&gt;
    &lt;/field-validator&gt;

    &lt;field-validator type=&quot;email&quot;&gt;
        &lt;message&gt;
            Enter the email id in proper format (eg: abc.def@xyz.com)
        &lt;/message&gt;
    &lt;/field-validator&gt;
&lt;/field&gt;</pre>
<p align="justify">The above Xml snippet essentially applies one <strong><em>Validation Rule</em></strong> to the username field and two <strong><em>Validation Rules</em></strong> to the email-address field. The type of the validation rule is specified by the attribute called <strong><em>type</em></strong>. In our case, the types represent the <strong><em>Required Validation (required)</em></strong> and the <strong><em>EMail Validation (email)</em></strong>. Any number of validation rules can be attached to a field element with the help of <strong><em>&lt;field-validator&gt;</em></strong> tag. <strong><em>Annotation-Based Validation</em></strong> for a field is also possible. The only requirement for the class is that the class that contains the fields representing the page (it can be an Action class too) <em id="__mceDel"><em id="__mceDel"><em id="__mceDel">must be marked with the </em></em></em><code>@Validation</code> annotation. Assume the Validation has to take place when the user submits the form. It is known that the Action.execute() method will be invoked as a result of this. So we can perform the field validations by marking the necessary Annotations against the method.</p>
<p><strong>MyAction.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myactions;

import com.opensymphony.xwork2.validator.annotations.*;

@Validation
public class MyAction{

    @Validations(
        emails = {
        @EmailValidator(type = ValidatorType.SIMPLE,
        fieldName = &quot;email_address&quot;,
        message = &quot;Enter the email id in proper format (eg: abc.def@xyz.com)&quot;)
        }

        requiredFields = {
        @RequiredFieldValidator(type = ValidatorType.SIMPLE,
        fieldName = &quot;email_address&quot;,
        message = &quot;Email Address cannot be empty.&quot;)},

        @RequiredFieldValidator(type = ValidatorType.SIMPLE,
        fieldName = &quot;username&quot;,
        message = &quot;User name cannot be empty.&quot;)}
        }
    )
    public String execute(){
        // Other Logic goes here..
    }

}</pre>
<p align="justify">Instead of marking the whole <strong><em>Bunch of Validations</em></strong> on the Action.execute method(), there is another alternate way wherein which the <strong><em>Annotation-Based Validation</em></strong> can be applied on a <strong><em>Field-by-Field</em></strong> basis. Assume that username and password are the two<br />
properties inside the Action class, then the following type of Annotation is also possible.</p>
<p><strong>MyAction.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myactions;

import com.opensymphony.xwork2.validator.annotations.*;

public class MyAction{

    private String username;
    private String emailAddress;

    @RequiredFieldValidator(type = ValidatorType.SIMPLE,
        fieldName = &quot;username&quot;,
        message = &quot;User name cannot be empty.&quot;)
    public String getUsername(){
        return username;
    }

    ...

    @RequiredFieldValidator(type = ValidatorType.SIMPLE,
        fieldName = &quot;email_address&quot;,
        message = &quot;Email Address cannot be empty.&quot;)
    @EmailValidator(type = ValidatorType.SIMPLE,
        fieldName = &quot;email_address&quot;,
        message = &quot;Enter the email id in app. format(eg: abc.def@xyz.com)&quot;)
    public String getEmailAddress(){
        return emailAddress;
    }
}</pre>
<h5>5.1.2) Non-Field Validation</h5>
<p align="justify"><strong><em>Non-Field Validations</em></strong> are generally Application specific and they will be given implementation by the <strong><em>Application Developers</em></strong>. Example may be performing validations based one or more fields in a form along with some Application specific Business Logic. The only availabe Validation that comes along with Struts 2.0 in this category is the <strong><em>Expression Validation</em></strong>. Assume that in some Application an Employee is asked to enter his Dirth of Birth and the Joining Date. For sure, the Birth Date will be logically lesser than the Joining Date. We can enforce this kind of Validation Rule using <strong><em>Expression Validation</em></strong> as follows.</p>
<p><strong>validation.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;field name = &quot;date_of_birth&quot;&gt;
&lt;/field&gt;

&lt;field name = &quot;joining_date&quot;&gt;
&lt;/field&gt;

&lt;validator type = &quot;expression&quot;&gt;
    &lt;param name=&quot;expression&quot;&gt;
        date_of_birth lt joining_date
    &lt;/param&gt;
    &lt;message&gt;
        Warning: DOB(${date_of_birth}) is greater than Joining Date(${joining_date})
    &lt;/message&gt;
&lt;/validator&gt;</pre>
<p align="justify">The first noticeable thing in the above Xml snippet is that the type of the Validation is identified as <strong><em>expression</em></strong>. The <strong><em>param</em></strong> tag is used to specify the constraint to be applied for the Validation. Here the constraint is very simple which tells that the Date of Birth for an Employee must be lesser that his Joining Date in the Organisation. Also notice, how actually the value of the field is taken to display error messages ($field_name). If the user enters 10/10/2000 for the DOB field and 10/10/1960 in the Joining Date Field, then the message &#8221;Warning: DOB(10/10/2000) is greater than the Joining Date(10/10/1960)&#8221; will be flashed in the User Browser.</p>
<h3>Validation Types based on Implementation</h3>
<p align="justify">If we look at another angle based on how Validations are <strong><em>Configured</em></strong> or <strong><em>Implemented</em></strong>, they can be classified into two categories namely,</p>
<ul>
<li>Declarative Validation</li>
<li>Programmtic Validation.</li>
</ul>
<h5>Declarative Validation</h5>
<p align="justify">If the Validation Logic for a particular <strong><em>Field</em></strong> or for an <strong><em>Entire Action</em></strong> is specified either in the Xml File or through Annotations, then it is called <strong><em>Declarative Validation</em></strong>. Whatever Validation we are seeing till now are Declarative Validations only. The idea behind Declarative Validation is that during the Deployment time of the Web Application itself, the Framework or the Container will be in a suitable position to <strong><em>map</em></strong> the set of fields participating in Validations against their <strong><em>Validation Rules</em></strong>.</p>
<h5>Programmatic Validation</h5>
<p align="justify">Not at all times, the <strong><em>Built-in Validations </em></strong>provided by the Framework will be sufficient. At times, there will be a situation to perform a Complex Validation Logic that is very specific to an application. For example situation may occur wherein, a single value of a field can be validated based on the content of some other text-fields along with some values fetched from the Database. In such a case, we can implement the <strong><em>Validation Logic</em></strong> directly into the Code. The following code snippet shows that,</p>
<p><strong>MyAction.java</strong></p>
<pre class="brush: java; title: ; notranslate">package myactions;

import com.opensymphony.xwork2.*;

public class MyAction extends ActionSupport{

    public void validate(){
        String stockSymbol = getStockFieldValue();

        if ((stockSymbol == null) || (stockSymbol.trim().length == 0) ){
            addFieldError(&quot;stock_field&quot;, &quot;Stock Symbol cannot be empty&quot;);
        }

        boolean result = validateStockSymbolFromDb(stockSymbol);
        if (!result){
            addActionError(&quot;Invalid Stock Symbol&quot;);
        }
        // Other Code goes here.
    }
}</pre>
<p align="justify">If an Application is going to provide <strong><em>Manual Validation</em></strong>, then it has to implement two interfaces namely <code>Validateable</code> and<br />
<code>ValidationAware</code> interfaces in the <code>com.opensymphony.xwork2</code> package. The core logic for the <strong><em>Custom Validation</em></strong> must be done<br />
within the <code>Validateable.validate()</code> method. ValidationAware Interface is used to collect the <strong><em>Error Messages</em></strong> that are related to fields or to a general Action. Fortunately, as expected, Struts 2.0 provides Default Implementation for both these interfaces in the<br />
<code>ActionSupport</code> class. So it is wise to extend this class for performing any Validation Logic without redefining every methods available in the Validation Interfaces.</p>
<p align="justify">Our sample Action class extends <code>ActionSupport</code> class to get all the Basic functionality for <strong><em>Storing and Retrieving Error Messages</em></strong>. Two types of <strong><em>Error Messages</em></strong> are available in the <code>ValidationAware</code> interface. One is the <strong><em>Field-level Messages</em></strong> and the other thing is the <strong><em>Action-Level Messages</em></strong>. Convinient methods are available for populating and retreiving both these messages. Methods <code>addActionError(String message)</code> and <code>addFieldMessage(String fieldName, String message)</code> are used to<br />
populate the error messages to an internal Collection. To retrive the Error Messages <code>getActionErrors()</code> and <code>getFieldErrors()</code> are used. To check whether errors have occured in a page use <code>hasActionErrors()</code> and <code>hasFieldErrors()</code> methods.</p>
<p align="justify">The sample code essentially checks the value of the stock symbol obtained from the field and checks for its emptiness. If not, it is populating the field-level error message by calling the <code>addFieldMessage("...")</code>. It then make <strong><em>Database Calls </em></strong>to ensure whether the Stock Symbol is valid. If not, an Action Level Error message is populated in the code by calling <code>addActionEror("...")</code>;</p>
<h2>Conclusion</h2>
<p align="justify">Though Struts 2.0 has more new features to its credit, this article just provides only the basic piece of information. It walked-through about how Struts 2.0 fits into the <strong><em>Bigger MVC2 Architecture</em></strong>. Then the <strong><em>Flow of the Client Request</em></strong> into the Struts Framework is explained in detail. Following that, some samples regarding the structure of a <strong><em>Struts Configuration File</em></strong>. Then the second section primarily focusses on the new <strong><em>Struts Validation Features</em></strong> with the various types of Validations that can be performed on field components.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/05/struts-2-0-introduction-and-validations-using-annotations/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What&#8217;s new in Struts 2.0? &#8211; Struts 2.0 Framework</title>
		<link>http://www.javabeat.net/2007/04/whats-new-in-struts-2-0-struts-2-0-framework/</link>
		<comments>http://www.javabeat.net/2007/04/whats-new-in-struts-2-0-struts-2-0-framework/#comments</comments>
		<pubDate>Thu, 12 Apr 2007 12:56:41 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Struts 2.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=185</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction In this article we will talk about the new features in Struts 2.0. Over the years, every developers believes that struts is the best and simple framework to implement. Since last two years, more new frameworks come to the market and the use of Struts is declined. Lack of updation in the Struts framework [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p>In this article we will talk about the new features in Struts 2.0. Over the years, every developers believes that struts is the best and simple framework to implement. Since last two years, more new frameworks come to the market and the use of Struts is declined. Lack of updation in the Struts framework is the main reason for developers choosing alternative framework. To answer this, Struts team comes with the Struts 2.0, an integration of Struts 1.0 with Webwork. Here we will look into the prominent features in the new framework.</p>
<h2>Action classes</h2>
<p>An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.</p>
<h2>Threading Model</h2>
<p>Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)</p>
<h2>Testability</h2>
<p>Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.</p>
<h2>Servlet Dependency</h2>
<p>Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.</p>
<h2>Harvesting Input</h2>
<p>Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects.</p>
<h2>Expression Language</h2>
<p>Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called &#8220;Object Graph Notation Language&#8221; (OGNL).</p>
<h2>Binding values into views</h2>
<p>Struts 2 uses a &#8220;ValueStack&#8221; technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types.</p>
<h2>Type Conversion</h2>
<p>Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.</p>
<h2>Validation</h2>
<p>Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.</p>
<h2>Control Of Action Execution</h2>
<p>Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2007/04/whats-new-in-struts-2-0-struts-2-0-framework/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>
