Thursday, February 26, 2009

Validation Within The Action Class In Struts 2

This blog post intends to answer the following questions :-
  1. How to perform simple validation in Struts 2?
  2. How to make use of the ValidationAware interface in Struts 2?
  3. What can the validate method be used for in Struts 2?
Validaton in Struts 2 within your action class can be performed by using the validate method. If your Struts class is a POJO(Plain Old java Object), then you need to implement the Validation aware interface and implement the validate() method so that the Struts 2 framework is able to call an interceptor for your POJO to perform the validation. If your class already extends the ActionSupport class, then you do not need to implement the ValidationAware interface because the ActionSupport class already provides a default implementation of the validate() method that does nothing.

The signature of the validate method is a follows :-

public void validate()
{
//your validation code goes here.
}

Now, the validate method can be used for any kind of validation, such as checking whether the user has not entered any null values into any form field, or if the form field has valid values. But, in my personal opinion, all such minor checks should be performed in the client itself using javascript. Because performing client side validation certainly avoids a round-trip to the server.

However the validate method can come in handy at certain times, when client side validation just cannot get the task done. Suppose that your jsp page has a user registration form. And you need to check that the user does not use a username that already exists in the system. This kind of validation is not possible on the client side alone. here you can use your validate() method to access the required database and then send a response back to the client asking him/her to enter a different username from the one that has just been entered.

Performing validation on the server can be a very frustrating to the client since he/she has to wait a long time until the server informs him of his mistakes. So, i suggest that you keep your server side validation as minimal as possible, and user javascript at the client side to perform simple validations such as those for empty fields or field lengths.

Happy Programming ;)

Signing Off
Ryan

Iteration/Iterator in Struts 2

This blog post intends to answer the following questions :-
  1. How to iterate over a collection using Struts 2?
  2. How to display the contents of an ArrayList in struts 2 on a jsp page?
  3. How to access the servlet context object from Struts 2?
iterating over a collection is an easy task in Struts 2. All that you need to do is to user the iterator tag. This tag is well designed to loop over any Collection/map/iterator/array/enumeration.

In the following example in I demonstrate how to make use of the iterator tag to iterate over an ArrayList that is stored in the servlet context.

MyPage.jsp
------Start Of Source Code------
...
...
<s:iterator value="#application.userDetailsList">
<s:property value="userName"/>
<br/>
</s:iterator>

...
...
------End of source Code------

Explanation :-
In the above example, I try to retrieve an ArrayList from the servlet context object using. The servelt context object can be accessed from a jsp page by using the '#application'. the ArrayList was stored in the servlet context as an attribute with the binding name as-'userDetailslist'. This Arraylist contained a large number of 'UserDetails' objects. Each UserDetails object has a property called -'userName'. So the above example iterated over all the UserDetails objects in the ArrayList and prints the userName for each every iteration.

I guess it couldn't get anymore simpler than this!

Happy Programming ;)

Signing Off
Ryan

Monday, February 23, 2009

Accessing Servlet Container Objects in Struts 2

This blog post intends to answer the following questions :-
  1. How to access the servlet container objects from a Struts 2 Action class?
  2. How to use the ApplicationAware, SessionAware, ParameterAware, ServletRequestAware and ServletResponseAware interfaces in a Struts 2 application?
  3. How to access the jsp implicit objects from a Struts 2 application?
  4. How to access the jsp implicit objects from a Struts 2 Action class?
As is very common in Struts 2, we solve the problem of accessing the container objects by making use of Dependency Injection. In the following example, I access the servlet context object and add an attribute to the context object- my name.


MyClass.java
------Start Of Source Code------
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ApplicationAware;
import java.util.*;

public class MyClass extends ActionSupport implements ApplicationAware{

Map app;

public void setApplication(Map app)
{
this.app=app;
}

public String execute() throws Exception{

app.put("name","ryan");

return SUCCESS;
}
}

------End Of Source Code------


Explanation : -
Here, I implemented the ApplicationAwareInterface and implemented the corresponding method- setApplication. This method takes a map pbject as an argument. This map is injected into the method by the struts container. Since I am implementing the ApplicationAware interface, the map injected will be of the Servlet Context. The rest of the code is a no brainer.

Similarly, the following interfaces and methods are required to inject the corresponding objects into your action class. Kindly scroll down to see the table.



















Interface NameMethod NammeInjected Object Type
ApplicationAwaresetApplicationMap
SessionAwaresetSessionMap
ParameterAwaresetParametersMap
ServletRequestAwaresetServletRequestHttpServletRequest
ServletResponseAwaresetServletResponseHttpServletResponse



Happy Programming ;)

Signing Off
Ryan

Sunday, February 22, 2009

Using Model Classes With Actions

This blog post intends to answer the following questions :-
  1. How to use the Prepareable and Model Driven interface in Struts 2?
  2. How to store data entered in a struts 2 form in a separate class instead of storing it in the Action class itself?
  3. How to use a POJO to store data entered by the user?
To begin with, lets first describe a POJO. POJO is an acronym for Plain Old Java Object. A POJO mainly consists of a large number of getter and setter method, thereby it can also be used as a JavaBean.

My motive is to store the data that is posted by the user via a form element in a POJO. My Action class is requred to store all the data entered in the form in the POJO on my begalf. And to receive this service I have to just add a few methods to my Action class.

In the following code example, a user enters his name and age as user details. This information reaches the Action class. These user details have to be stored in a JavaBean class called UserDetails. And all of this stuff is supposed to happen automatically instead of me having to call each setter method from the execute method.

Here is how I do it :-

UserDetails.java
------Start Of Source Code------
package user;

public class UserDetails
{
String name;
int age;

public String getName(){
return name;
}

public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
}
------End Of Source Code------


Register.java
------Start Of Source Code------
package user;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.ModelDriven;

public class Register extends ActionSupport implements ModelDriven, Preparable{

UserDetails user;

public void prepare()
{
user=new UserDetails();
}

public UserDetails getModel()
{
return user;
}

public String execute() throws Exception{
if(user.getName().equals("") || user.getName()== null || user.getAge()== 0){
return ERROR;
}
else{
return SUCCESS;
}
}
}
------End Of Source Code------


Struts.xml(Snippet)
------Start Of Source Code------
<action name="registerUser" class="user.Register">
<result name="success">/registrationSuccessful.jsp</result>
<result name="error">/error.jsp</result>
<result name="input">/error.jsp</result>
</action>
------End Of Source Code------

Explanation :-
In the above code, UserDetails is called the model class, Register is my action class. All of the task is done for us by the interceptors. All that we need to do is to initially prepare the userDetails object and then make it available to the Struts interceptor to call its setter methods. The preparable interface allows us to take any action before the setters are called. Hence it its the appropriate place to initialize the userDetails instance variable. The ModelDriven interface provides a means to inform the framework about the object whose setter methods need to be called and hence be used as the model. It does this by returning a model object (the object that will store the data entered by the user) from the getModel method.
So the task is easily handled. Initialize the object in the prepare method if you haven'd done so already. Then return the object to framework through the getModel method. Cheers!

Happy Programming ;)

Signing Off
Ryan

Monday, February 9, 2009

struts.xml in Struts 2

This post intends to answer the following questions :-
  1. Where should I place the struts.xml file in a Struts 2 application.
  2. What should be the contents of a struts.xml file to demonstrate the use of Struts 2.
  3. A minimalist configuration for a seemingly useful Struts 2 application.
As I have already mentioned in my previous post, Struts 2 application is basically just a simple framework that is built to make the life of a web developer easy (At least that's what they say). After you have configured your web deployment descriptor to add Struts 2 capabilities as shown in my previous post here, you need to make a struts.xml file that houses the configuration of Struts 2. This file needs to be placed directly under the 'classes' directory of your web application. In case you are not aware how a web application is structured or where a 'classes' directory is placed, kindly refer here.

Below I am posting a fully configured struts.xml file for a simple Struts 2 application :-

struts.xml
//------Source Code Starts Here------

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">


<struts>
<include file="struts-default.xml"/>
<package name="default" extends="struts-default">
<action name="someAction" class="packageName.ActionClassName">
<result name="success">/somePage.jsp</result>
<result name="error">/someErrorPage.jsp</result>
<result name="input">/someOtherPage.jsp</result>
</action>
</package>
</struts>


//------Source Code Ends Here------

This code snippet demonstrates the use of a struts.xml in a simple Struts 2 application. the only mandatory tags in struts.xml that are required to make your application 'useful' in a minimalist way are :-

<struts>
<include file="struts-default.xml"/>
<package name="default" extends="struts-default">
<action name="someAction" class="packageName.ActionClassName">
<result name="success">/somePage.jsp</result>
</action>
</package>
</struts>

This should be it. Now all that is required of you is to write an action class - 'packageName.ActionClassName' that performs the required action. And off you go. Oh, and dont forget to place the class file that you obtain by compiling the ActionClassName file in the 'classes' directory according to package hierarchy.

Happy Programming ;)

Signing Off
Ryan

Sunday, February 8, 2009

Struts 2 Configuration

This blog intends to answer the following questions :-
  1. How to configure a Struts 2 application in web.xml.
In order to make use of the features of Struts 2, one needs to configure the web application to make use of the Struts 2 api. Struts 2 can be used in your web application by adding a simple filter in your web.xml file that takes control of user requests. In the following snippet of the web.xml I demonstrate how this is done.

web.xml
//------Start Of Source Code------
.
.
.
. . . other web.xml elements. . .
.
.
.
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
.
.
.
. . . other web.xml elements. . .
.
.
.

//------End Of Source Code------

The Struts filter takes care of all the Struts 2 capabilities by by making use of all the pre-configured Interceptors and performs the DI(Dependency Injection) into the action classes.

So thats all that is required in the deployment descriptor to make your application 'strutified' !!!!

Happy Programming ;)

Signing Off
Ryan

Struts 2 jar files

This blog post intends to answer the following questions :-
  1. What are the 'jar' files that are required to run my Struts 2 application?
  2. Where do I keep the jar files required by Struts 2 in my web application?
  3. From where do i get the jar files required by Struts 2?
Well, a Struts 2 application is no different from a normal web-application and requires no 'special' container like JBoss or Glassfish to execute. Even our dear friend - Tomcat will suffice. The reason is the fact that Struts 2 is a simple framework that is based upon the MVC architecture(MVC-2, to be precise) and all that is required of you is to copy a few jar files to your web application. As I have already mentioned about how a simple web application is structured here, i am only going to mention the names of the files that will be required by you to run your application.

The following jar files will be required :-
  1. commons-logging-x.x.jar
  2. freemarker-x.x.jar
  3. xwork-x.x.jar
  4. struts2-core-x.x.jar
  5. ognl-x.x.jar
On my system, I use the following jar files for Struts 2:-
  1. commons-logging-1.1.jar
  2. freemarker-2.3.8.jar
  3. xwork-2.0.1.jar
  4. struts2-core-2.0.6.jar
  5. ognl-2.6.11.jar
Now, where do we place these files? Of course, since all of them are jar files, like all other good web applications, even they have to be placed in the 'lib' directory in your web application.

From where to get these jar files? Our brethren at Apache have it all sorted out. Just click here and ye shall get all that ye might ever ask for!

Happy Programming ;)

Signing Off
Ryan

Sunday, February 1, 2009

Web Application Structure

This blog intends to answer the following questions :-
  1. What is the structure of a simple web appliation in java using jsp pages, servlets.
  2. What are the contents of a web archive(war) file?
  3. How to create a web archive?
A web application is an application that is designed to respond to requests from web client and can be executed only on a server. In most of my application, I use the Topmcat server for running simple web applications.

Firstly a web application must has the following componenets/files/folders :-
  1. An application root folder. e.g myapp. This would be the name of your application.
  2. A folder called 'WEB-INF'. No lower case.
  3. An xml file called 'web.xml' called the deployment descriptor.
  4. A folder called 'classes'.
  5. A folder called 'src'.
  6. A folder called 'lib'.
All these folders have to be arranged in the following structure.
  1. myapp.
  2. myapp/WEB-INF.
  3. myapp/WEB-INF/web.xml.
  4. myapp/WEB-INF/src.
  5. myapp/WEB-INF/classes
  6. myapp/WEB-INF/lib.
This is all there is to the strucure of a web aplication so that it can be automatically be deployed by the container.

The usage of the different componenets is as follows :-
  1. web.xml :- This is the most important heart and soul of your web application. It contains information about the web application in the form of xml configuration. It is used to link servlets and jsps and filters to the various user requests.
  2. src :- This folder is used to contain the source code of yout applications i.e. all java files.
  3. classes :- This folder is supposed to contain al the compiled class files in the proper directory/package structure.
  4. lib :- This folder is supposed to contain all the jar files that would be required by your applications at runtime.
Apart from these files and folders you can have any number of files and folders in your application. But the only thing that you need to keep in mind is that all files and folders placed inside the WEB-INF directory are not available to the client 'directly', i.e. the client cannot access them via typing in a url in the browser.

For example, if you have a 'fun.jsp' file in WEB-INF, the client just cannot type 'http://myserver/myapp/WEB-INF/fun.jsp' to get the file. This would result in an http 404 error. To access this 'fun.jsp', this file should have an approprite mapping in the web.xml file.

All the 'files and folders' that need direct client access vial the browser should be placed outside the WEB-INF folder.

Creating a war file is simple.

Just go to your application directory. Here my application directory is 'myappp'. So I execute the following commands on my windows machine.
  1. cd myapp
  2. jar -cvf myapp.war *.*
This command creates a new web archive called 'myapp.war'. This can then be deployed by any servlet container. For how ro deploy web applications, refer to your server manual.

I suppose that this introduction should be good enough to give you a head start.

Happy Programming ;)

Signing off
Ryan