Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Thursday, March 22, 2012

Generate Javadoc Through Command Line


Here's a quick tip on generating Javadoc HTML files for your Java classes via command line.

javadoc  < MySourceFileName > .java -d <Destination Directory>

You need to make use of the 'javadoc' command.
You can specify multiple files separated by a white space or you can simply specify a directory name containing all your source files.

javadoc -sourcepath  < Source Directory >  -d  < Destination Directory>

Although I havent worked with eclipse, I believe it has an option where you can specify the javadoc command and then you would be able to easily generate documents via some menu option. Just FYI, if you work on windows, the javadoc command is located in the same directory as the java.exe command.

For more help and options on this command, check out the references

References

  1. http://www.mcs.csueastbay.edu/~billard/se/cs3340/ex7/javadoctutorial.html - Contains a list of other available options. Its short, sweet and cool.
  2. http://docs.oracle.com/javase/1.4.2/docs/tooldocs/windows/javadoc.html
  3. http://www.myeclipseide.com/PNphpBB2-viewtopic-t-5191.html



Happy Programming :)
Signing Off

Ryan

Thursday, September 29, 2011

Reference Types In Java - Part 1


Lately, I have been learning a thing or two about the JVM internals. And one of the most interesting things that I came to know about was, the existence of different types of references in Java.

To go about it, there are actually 4 kinds of reference types in Java.

  1. Strong references.
  2. Soft references.
  3. Weak references.
  4. Phantom references.

These references are different solely because of the existence of a garbage collection mechanism in the JVM. That is because, the decision of reclaiming memory from the object heap depends not only on the fact that there are active references to an object, but also on the type of reference to the object.

Lets try to see how each of them differ from one another.




Strong references

As a normal programmer(that is, if you consider programmers to be 'normal'), we are most likely to encounter only the most ubiquitous form of references - Strong references. The name of this reference type should by itself give you an idea of the importance of the reference in the opinion of the garbage collector. Any object with an active strong reference to it, will never be garbage collected(except in rare circumstances, such as cyclical references).

Say, for example, when you create a class Employee, and you create a reference to a new employee object like this

Employee emp = new Employee();

you are actually creating a strong reference. An object to which a reference is created in this way will be eligible for garbage collection only when the reference is to it is pointed to null.
So, if you write this

emp=null;


and there are no more references created to this object until the garbage collector runs again, this object will become eligible for garbage collection, and is most likely to be garbage collected.

So, strong references are pretty simple to understand, probably because most of the code that you commonly write mainly consists of strong references. And we let the smart garbage collector take care of cleaning up the memory for us.

However, there might be cases where you need more control over the lifetime of an object. What if you want to keep some kind of a pool of objects, but still want it to be garbage collected if your JVM is running out of memory? In such cases although you may want a reference to the object most of the time, you are willing to let go of a memory reference for a better JVM performance, when times are crucial. This is where the other kinds of references come into the picture.

The 3 remaining Reference types that I discuss here are subclasses of an abstract class Reference.




Soft references

The soft reference class is used to create a soft reference to an existing object that is already referred to by a strong reference. The actual object on the heap that is being referred to is called the referent.

In order to create a SoftReference to an object, you first need to create a strong reference to that object and then pass that object as a parameter to the constructor of the SoftReference object, as shown in the code below.

Employee emp = new Employee(); //1

SoftReference<Employee> softRef = new SoftReference<employee>(emp);

In the above code, a few interesting things have happened.

  • In line #1,a (referent)object is created and allocated memory on the heap that represents the Employee object.
  • Again, in line #1, a strong reference is created to the newly created employee object. We call this reference 'emp'.
  • In line #2, a new SoftReference object is created and allocated memory on the heap. This is a special object because it contains an internal reference to the (referent) object passed to it in the constructor, i.e. in our case, the actual Employee object on the heap.
  • Again in line #2, a strong reference is created to the SoftReference object on the heap. We call this reference 'softRef'.


So, in total, we have 2 strong references created. And the object that represents the soft reference, internally holds a reference to the actual employee object.

So what is it that makes soft references useful? Soft references are considered to be a special kind of reference by the garbage collector. Let us assume that at a later point of time, we nullify the 'emp' reference as follows and no new strong references were created to this emp object.


emp=null;


Now lets assume that the garbage collector decides to run at this point of time. What it will see is that the current employee object only has a soft reference pointing to it, and no strong references. The garbage collector may optionally choose to reclaim the memory occupied by the employee object. But what makes soft references even more special is the fact that the garbage collector will always reclaim the memory of objects that have only soft references pointing to them before it throws an OutOfMemory Error. This gives the garbage collector some sort of a last chance to save the life of the JVM.

At any given point of time, if the garbage collector has not yet reclaimed the memory of the actual referent object, you can get a strong reference to the referent via the get method.


Employee resurrectedEmp = softRef.get();


The above code resurrects the employee object in the sense that the garbage collector will not consider it a candidate for garbage collection because it now has a Strong Reference pointing to it.

This makes soft references highly useful in creating object pools, where the size of the pool needs to be dynamic. If you do not know the size of a pool when you begin, or choose not to set a minimum or a maximum size on the object pool, instead you want it to grow dynamically, and at the same time, you want to give the JVM a chance to cleanup unused objects, in that case SoftReferences are a perfect fit.




Weak References

Weak references are even more awesome. Thats because seemingly the garbage collector has no regard for an object that only has a week reference. What that means is that the garbage collector will make it eligible for garbage collection because object only has a week reference pointing to it. Not only is that awesome and useful, but desirable as well in some scenarios.

For example, let  us assume that you need to maintain some metadata related to a user per database connection. In such a case you will be tempted to use a hashmap where you can store the database connection as the key and the user metadata as the value. However, this approach has one drawback. When the database connection has been cleaned up by some other part of the application, then you need to ensure the removal of the connection from the hashmap as well. If you forget to do such a thing, a reference to the connection will remain in the hashmap thereby preventing it from being garbage collected. This means that over a period of time, you are bound to end up with a very large hashmap, a clear indication of a memory leak. And the JVM will eventually spit out a OutOfMemoryError.

So, what do you do in such cases? Oh, of course, Weak referencnes to the rescue!

You can simply create a weak reference to the object, in the same way that we created a soft reference.


DBConnection emp = new Employee(); //1

WeakReference<DBConnection> weakRef = new WeakReference<DBConnection>(emp);



This creates a weak reference to the DBConnection object. This means that if at any future point in of time during the execution of the program, if the garbage collector detects that the only reference to the actual DBConnection object is a Weak reference, then it will mark the object for garbage collection.

Weak references are primarily used in conjuction with a WeakHashMap. This is a special kind of hashmap where the keys are all made of weak references. So, in our database example, we could effectively create a weak reference of the Database connection and store it in the WeakHashMap and the metadata of the user as the value in the hashmap. In this way, when the application no longer holds a strong reference to the Database connection, the only reference to the database connection object will be the one that we have via the WeakReference entry in the WeakHashMap. When the garbage collector detects this, it will mark the object for garbage collection. When the object is garbage collected, the entry from the WeakHashMap will be removed. And then, finally, we can all go home and rest in peace.

So, colloquially speaking, this is what the Soft reference and the Weak reference tell us about themselves.

Soft Reference : Hey! I am a soft reference. Ill take your shit as long as the JVM has patience. When it begins running out of patience(i.e. about to throw an OutOfMemoryError), i take no more. Your object will be gone. And then you simply have to create a new object.

Weak Reference : Hey! You know what. I am even cooler than the WeakReference. Coz I wont take your shit at all. The moment you lose me, if the JVM detects that you're no longer around, am gonna punch you in the face and run away! (i.e. Marked for garbage collection). Can you dig it sucka!

As you see, our two awesome friends, Softy and Weaky, certainly have some ego there. But they are pretty useful, at crucial times.

Before I proceed any further, there is one more puny lil thing that you might need to know. Oh! Did i just say 'might'. Oh no.. I meant, you should know. And that is ReferenceQueues. ReferenceQueues are some sort of a queue where the JVM can store objects of type reference once it has decided to take some action on the objects to which they refer.

What I mean to say is, let us suppose you have a weak reference which points to an object in the heap. And that object has been left lonely and desolate by the rest of the application.i.e. No strong references to it. And the garbage collector detects this object during its garbage collection cycle. Since this object only has a weak reference to it, the garbage collector will mark it for garbage collection. But at the same time, it looks if there is a reference queue associated with the weak reference that points to this object. If yes, it puts this weak reference in the reference queue to indicate that the object has been marked for garbage collection. The subtle point to be noted here is that even though the object has been marked for garbage collection, garbage collection may not have happened yet. This may be because the object has a finalize method, which the JVM needs to execute before reclaiming memory.

This also means that you can, but should not,unless deemed necessary, resurrect an object in the finalize method and create a strong reference to it. But when you do that, the weak reference still remains en-queued in the ReferenceQueue. Overriding the finalize method to resurrect an object is a rare case, but since it is one of the options that the JVM supports, it is therefore something that needs to be considered. Nevertheless, when you do such things, its almost equivalent to artificially manipulating the life of an object. That's because the second time when the object becomes eligible for garbage collection, the finalize method wont run, which is a good thing because if you run it again, its simply gonna revive itself. So, practically speaking, an object in the JVM has only one spare life. You get just one medical kit at the max. And thats it. You screw up again, and ur doomed. Your object will be on mars, having a boss fight with the garbage collecting thread of the JVM, which will eventually win, and reclaim the memory of the object.

The same facts about the reference queue hold true for Soft references as well.

In order to associate a weak or a soft reference with a reference queue, you can use the 2 argument constructor as shown below.


Employee emp1 = new Employee();
Employee emp2 = new Employee();

ReferenceQueue softQueue = new ReferenceQueue();
ReferenceQueue weakQueue = new ReferenceQueue();

SoftReference softRef = new SoftReference(emp1, softQueue);
WeakReference softRef = new WeakReference(emp2, weakQueue);




Now, aint that simple? Yes of course it is.
Then again, you haven't met the Phantom yet, have ya?

The phantom reference is a place where it gets all the more interesting.




Phantom References

Phantom references tell a long tale themselves and its a topic that warrants a blog post of its own. However, in this blog post, ill give a brief idea about what they are. Phantom references are quite similar to Strong and Weak references in the sense that the garbage collector will collect the referent object if the only reference to it is the phantom reference. But that's where the similarity ends. 

What makes Phantom references are unique is the way in which they are used along with a reference queue. A phantom reference is always associated with a references queue during construction time. This is because phantom references are enqueued in the queue only when the the object is about to be garbage collected, after the finalize method(if any) has been executed on it. Calling a get() on the Phantom reference always returns null. And that is quite appropriate because the finalize function has already run on the referent object. So, there should be no 'legal' way of resurrecting the object (resurrecting i.e. creating a strong reference). This may at first seem to make no sense, since, what use is a phantom reference if we cant extract the referent from it? But on giving it a deep thought, you would realize that this is not the reason why phantom references are meant to be useful in the first place. It is the time at which the JVM puts a phantom reference in the reference queue that makes its use so intuitively amazing.

That's something that I will be discussing in more detail in the next post. So stay tuned, because, it might just turn out to be a weird crazy experiment. And of course, its possible that some so called 'laws' will be violated. I am still working on it right now. Ill put it up sooner or later.

So folks, see you on the other side! (Hint : That's what phantom references say too).

Happy Programming :)
Signing Off
Ryan

Thursday, March 17, 2011

Runtime Class and Method information


Here is a small snippet that can be used to find the name of the currently executing method in Java.

Throwable t = new Throwable(); 
StackTraceElement[] elements = t.getStackTrace(); 
System.out.println(elements[0].getMethodName());


Create a Throwable object in your method. During the creation of a Throwable instance, the JVM stores information of the currently executing method on the stack trace. Extract the stack trace and print the name of the zeroth element to get your method name.

Here is another small snippet to find the name of the class at runtime.

Thread.currentThread().getStackTrace()[1].getClassName()

Tiny little things, aren't they!

Happy Programming :)
Signing Off

Ryan

Sunday, February 27, 2011

Creating a copy of JavaBeans


In this post, we shall see how to make a copy of an object in Java.

In our applications, JavaBeans play a very important role. However sometimes we simply need to make a copy of our JavaBeans so as to make changes to the copy and keep the original object intact.

There are two ways in which this can be achieved in Java, depending upon the level of access you have to your beans.

  1. Using Object.clone()
  2. Using BeanUtils

Copying using Object.clone()

This method can be used when you have access to the source code of your bean classes. This method requires your JavaBeans to implement the cloneable interface. The Cloneable interface is a marker interface that indicates that the object allows itself to be cloned. We can call the Object.clone() method on only on objects whose classes implement the Cloneable interface. If we attempt to invoke the clone() method on an object of a class that does not implement the Cloneable interface, we get a CloneNotSupportedException.

Also note that the clone() method is a protected method, so you will most likely need to create a public method on your bean class named clone() to mimic the functionality.

We are going to demonstrate both the above methods using a simple Employee class. This class will contain an instance of another javabean 'Address'. We shall see in the below example, how we can obtain a deep copy of our beans.

The following code demonstrates the usage of Object.clone()

Address.java
class Address {

    private int houseNo;

    public int getHouseNo() {
        return houseNo;
    }

    public void setHouseNo(int houseNo) {
        this.houseNo = houseNo;
    }

    @Override
    public String toString() {
        return "houseNo : " + houseNo;
    }
    
}


Employee.java
class Employee implements Cloneable {

    private String name = null;

    private Address address=null;


    @Override
    public String toString() {
        return "name " + this.getName()+ " address : "+ address;
    }
    
    public Employee clone() {

        Employee emp = null;
        try {
            emp = (Employee) super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println(e);
        }
        return emp;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
}

Note that in the above classes, the Employee class and the Address class is declared with a visibility of default. We did not have to make them public, although we could have.

Also note the way the clone() method has been written in the Employee class. I explicitly declared it as as a public method and called the superclass implementation of the clone method. Then, I downcasted it to am Employee object before returning.

Lets see the code in action.

public static void main(String[] args) {

        Employee emp1 = new Employee();
        Address add1= new Address();
        add1.setHouseNo(100);

        emp1.setName("ryan");
        emp1.setAddress(add1);

        Employee emp2 = emp1.clone();
        emp2.setName("ryan2");

        print("emp1 : " + emp1);
        print("emp2 : " + emp2);

        print("emp1==emp2 "+(emp1==emp2));

    }

If you execute the following code, you will get the below output

emp1 : name ryan address : houseNo : 100
emp2 : name ryan2 address : houseNo : 100
emp1==emp2 false

You can replace the print statement with your logger statement to run the code.
Note that the == operator indicates that both the objects are created independently on the heap. Moreover, the fields of the Address bean have also been copied.

One crucial thing to be noted here is that you only needed to implement the Cloneable interface in the Employee class. The Address class does not need to implement Cloneable, although there wont be any serious repercussions if you do so!


Now lets see the second method

Using the BeanUtils.cloneBean() class

This method makes use of the BeanUtils class provided by the apache foundation. In order to use this class, you need to have at least the following jar files in your classpath
commons-beanutils-1.7.0.jar
commons-collections-3.1.jar
commons-logging-1.0.4.jar


The version numbers may differ, but you can get the details from the here if the dependencies change.

The BeanUtils class provides us a method called cloneBean that clones all the accessible properties of your beans. Here is the code in Action.

Employee2.class
public class Employee2{

    private String name = null;

    private Address address=null;


    @Override
    public String toString() {
        return "name " + this.getName()+ " address : "+ address;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }    
}

Note the declaration of the Employee2 class. We did not implement the Cloneable interface. Moreover, we made the class "public". Making the class public is required for the BeanUtils class to extract the data from the Bean. Also note that we did not have to write a clone() function in this class.

We can reuse the existing Address class from the previous example, as no changes need to be done to it.

You need to import the following line in your main class

import org.apache.commons.beanutils.BeanUtils;

Now lets take a look at the main function.

public static void main(String[] args) throws Exception{

        BeanUtils bu = new BeanUtils();
        Employee2 emp1 = new Employee2();

        Address add1= new Address();
        add1.setHouseNo(100);

        emp1.setName("ryan");
        emp1.setAddress(add1);

        Employee2 emp2 = (Employee2)bu.cloneBean(emp1);
        emp2.setName("??");



        print(emp1);
        print(emp2);

        print("emp1==emp2 : "+(emp1==emp2));

    }

As you see above, we did not have to do much but simply call the cloneBean method on the BeanUtils object and downcast it to our Employee2 bean. As was expected, a deep copy of the object was created.

If you run the code, you get the following output

name ryan address : houseNo : 100
name ?? address : houseNo : 100
emp1==emp2 : false

As expected, both the objects are considered to be different objects on the heap. They just have the same values for their properties.

In the methods discussed above, you can see that the BeanUtils method can be used in a much wider scope because most of your JavaBeans will be public, but you may not always have access to the code of your JavaBeans to write a clone method.

Thats all for now folks!

Happy Programming :)
Signing Off
Ryan

Tuesday, April 20, 2010

Implementing Dependency injection using Annotations

Today in this blog post I am going to elaborate a strategy to implement the Dependency Injection pattern using annotations in Java.

Since their introduction in Java 5, annotations have been widely debated. However, as powerful as they are, Annotations are here to stay. This post requires that the reader has basic knowledge of Annotations and a little bit of reflection. Annotations are extremely handy when used in conjunction with the Reflection API.

In the following examples, i will demonstrate a way to inject fields and methods into a class using annotations.
We will use annotations to indicate that the fields need to be injected.

I have a very simple class hierarchy- ParentClass and ChildClass. The ChildClass extends the ParentClass as indicated by the name.

Lets see the declaration of these basic classes.

ParentClass.java
package annotationExp.di2;

/**
 *
 * @author ryan
 */

class ParentClass {

    public void method() {
        System.out.println("Parent Class");
    }
}



ChildClass.java
package annotationExp.di2;

/**
 *
 * @author ryan
 */
class ChildClass extends ParentClass{

    public void method() {
        System.out.println("Child Class");
    }
}

As seen, there is nothing out of the ordinary in these classes.

Now lets create a class called SampleClass that contains a reference of a parent class.

SampleClass.java (Without any annotations)
import java.util.Date;

/**
 * This is the class that needs dependecy injection of
 * the implementation class of the ParentClass reference.
 * @author ryan
 */
class SampleClass {

    
    private ParentClass parentReference;

    private Date startDate;
    private Date endDate;

    public ParentClass getParentReference() {
        return parentReference;
    }

    public void setParentReference(ParentClass parentReference) {
        this.parentReference = parentReference;
    }

    public Date getEndDate() {
        return endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    
    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }


    
    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    
}

Now suppose, at runtime, we need to inject an object of the child class in the parent class reference. And also, we need the startDate and endDate fields to have default values.

If we were to implement this in the normal way, we would have to write the initialization code for the parentReference and the dates in the main class where we create the object of our SampleClass, by using getters and setters.


But since such a requirement may exist at several places, we may end up writing the same piece of code redundantly at all the places where such an initialization is required.

Let us now see how annotations can help us clean up this mess.

We first begin by declaring the annotations.

FieldInject.java
package annotationExp.di2;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This is a field level injector
 * @author ryan
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldInject {
}



DateInject.java
package annotationExp.di2;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * This is a method level injector
 * @author ryan
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DateInject {int delay() default 0;}



As you can see, these annotations have been marked with a retention policy of RUNTIME because we need to inspect the annotations at runtime to inject the necessary values.

The annotation DateInject also specifies the parameter to indicate the offset number of days from the current date that should be used when calculating the date.


Now, lets declare our sample class again, but this time we use annotations to indicate that we need certain methods and fields to be injected.

SampleClass.java (With Annotations)
import java.util.Date;

/**
 * This is the class that needs dependecy injection of
 * the implementation class of the ParentClass reference.
 * @author ryan
 */
class SampleClass {

    @FieldInject
    private ParentClass parentReference;

    private Date startDate;
    private Date endDate;

    public ParentClass getParentReference() {
        return parentReference;
    }

    public void setParentReference(ParentClass parentReference) {
        this.parentReference = parentReference;
    }

    public Date getEndDate() {
        return endDate;
    }

    public Date getStartDate() {
        return startDate;
    }

    @DateInject(delay=10)
    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }


    @DateInject
    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }
    
}


Now lets write our main class that creates an object of SampleClass and also handles dependency injection by using a few methods.


TestDI.java

package annotationExp.di2;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;

/**
 * This class demonstrates handling dependency injection for annotations placed
 * methods and variables.
 * @author ryan
 */
public class TestDI {

    public static void main(String[] args) throws Exception{

        SampleClass sc = new SampleClass();

        /*
        * This function handles dependency injection(DI) for the given object.
        * In a framework,this can be handled by interceptors or preprocessors.
        */
        handleAnnotations(sc);

        /*
        * There is no need to initialize the parentReference as
        * it has already been initialized via dependency injection.
        * Hence we will not get a null pointer exception here
        * as long as the function that handles DI is executed and
        * the field is marked for DI.
        */
        sc.getParentReference().method();
        System.out.println("Start Date : "+sc.getStartDate());
        System.out.println("End Date : "+sc.getEndDate());

    }

    public static void handleAnnotations(T object) throws Exception
    {
        handleFieldAnnotations(object);
        handleMethodAnnotations(object);
    }


    public static  void handleFieldAnnotations(T object) throws Exception{
        Field[] fields = object.getClass().getDeclaredFields();
        handleFieldInject(fields, object);
        //handle other field level annotations one by one
    }

    public static  void handleMethodAnnotations(T object) throws Exception{
        Method [] methods = object.getClass().getMethods();
        handleDateInject(methods, object);
    }

    public static void handleDateInject(Method[] methods,T object) throws Exception{
       System.out.println("Method : "+methods.length);
        for (Method method : methods) {
            System.out.println("Method : "+method.getName());
            System.out.println("Annotations : "+method.getAnnotations().length);
            System.out.println("Is DateInject Present : "+method.isAnnotationPresent(DateInject.class));
            if (method.isAnnotationPresent(DateInject.class)) {
                Class[] parameterTypes = method.getParameterTypes();
                if(parameterTypes.length==1&&parameterTypes[0].equals(Date.class))
                {
                    Annotation[] annotations= method.getAnnotations();
                    DateInject annotation = method.getAnnotation(DateInject.class);
                    if(annotation.delay()==0)
                    {
                        method.invoke(object, new Object[]{new Date()});
                    }
                    else
                    {
                        int delay = annotation.delay();
                        Calendar c = Calendar.getInstance();
                        c.add(Calendar.DAY_OF_MONTH,delay);

                        method.invoke(object, new Object[]{c.getTime()});
                    }
                }
                else
                {
                    System.out.println("Method "+method.getName()+" : Cannot be injected with a Date");
                }
            }
        }
    }

    public static void handleFieldInject(Field[] elems,T object) throws Exception{
        System.out.println("Fields : "+elems.length);
        for (Field elem : elems) {
            System.out.println("Field : "+elem.getName());
            System.out.println("Annotations : "+elem.getAnnotations().length);
            System.out.println("Is Inject Present : "+elem.isAnnotationPresent(FieldInject.class));
            if (elem.isAnnotationPresent(FieldInject.class)) {
                if(elem.getType().equals(ParentClass.class))
                {
                    elem.setAccessible(true);
                    elem.set(object, new ChildClass());
                    System.out.println("Child class is set");
                }
            }
        }
    }

}


As can be seen in the main function, the task of handling the dependency injection has been delegated to a separate method that analyzes the annotations present on the SimpleClass and injects the necessary values into the fields.
In a framework like struts, you can easily use this feature to handle dependency injection in an interceptor and mark the fields in your struts action to be injected using annotations. This will also help in centralizing the point of object creation an open the doorway to ways of implementing other creational design patterns such as the AbstractFactory and FactoryMethod.

I hope this helps.

Happy Programming :)

Signing Off
Ryan

Tuesday, December 22, 2009

Struts 2 environement setup

Here is a sample web.xml to add struts functionality to a web application. The most important part is the struts filter.

Remember to include the following jar files in the classpath to use struts 2 fuctionality. i.e. lib directory.

commons-logging-1.0.4.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.14.jar
xwork-2.0.7.jar

As is visible from the name of the struts jar file, these are the jar files that are required for struts 2. The dependencies of the jar files may change depending upon the version of struts you use. For now, these versions are compatible with each other.



    
        
            30
        
    
    
        struts2
        org.apache.struts2.dispatcher.FilterDispatcher
    
    
        struts2
        /*
    
    
        index.jsp
    




This should be enough to set up the environment for Struts 2. Additional functionality can be provided to struts 2 by adding more jar files, but i am not concerned with that in this post. As of now, i just want to be able to have the bare minimum environmental settings for creating a struts 2 application, and this resolves my problem.

Signing Off
Ryan Sukale

Monday, August 24, 2009

Java Inheritance - Explained

Today, in this blog post, i am going to try to explain the concept of inheritance in Java. There are many people who are in a dilemma when it comes to explaining about the inheritance model of Java especially when they come across interfaces. The most common doubt that how does Java claim that it does not implement multiple inheritance when instead we use classes that inherit other classes and implement multiple interfaces.

So, this blog post intends to answer the following questions
  1. What is the difference between implementing an interface and extending a class?
  2. Why can we say that implementing an interface is not a concept related to inheritance?

First of all one need to know that there is a huge difference between the multiple inheritance model of java and that of C/C++.

One of the primary reasons why the multiple inheritance model was removed from the Java language was because it eliminated one of the most notorious problem caused due to multiple inheritance - The Diamond Problem. If you dont know about it, I suggest that you google it once you have read this article.

Whenever we speak of inheritance in Java the first thing that must come to one's mind must be - Classes. Not interfaces. Because inheritance in java is strictly constrained to Classes. Since java does not allow a class to have more than one superclass, hence it leaves no doubt that multiple inheritance is not supported in java.

Then how do we explain the case when a class extends one base class and implements one or more interfaces? Is that not multiple inheritance? Well, I must say that thought this might look like multiple inheritance, it certainly is not.

Let me illustrate this idea with an example.

Suppose there is a class 'Mammal' and a class 'Human'. If you were to relate these two classe, how would you relate them? Of course, the answer is plain and simple(as all answers are!) Mammal is the parent class of Human. Programatically, we could write this relationship in java as the following code :

class Human extends Mammal{
...
...
...
}


All of us know that humans are an intelligent species(Though sometimes i am not so sure about that) Now, supppose we had a class called Intelligent that had a function called thinkStupidThings() ,how would you relate it to Human? Of course, you would say- Human is Intelligent.

If java were like C/C++, then we could have easily written the following code

class Human extends Mammal extends Intelligent{
...
...
...

thinkStupidThings(){...}

}

BUT! Java is NOT C/C++. So the above code is not valid and our intelligent Java compiler will throw a compile time error if you try to compile this.

So, now the question is, How do we depict this relationship in Java? Dont worry folks, this is where Interfaces come to our rescue. Well, why Interfaces? And how to decide which one of them needs to be made an interface?

Lets analyze our problem clearly. We have Mammal,Human and Intelligent. Now if we notice carefully, we see that no matter what happens, all humans are mammals. But the same cannot be said about Intelligent. What i mean is that intelligence is a characteristic of not only Humans but also many other species like dolphins and apes. Some of them are even more intelligent than humans(Had we been more intelligent, we would have solved the mystery of the universe by now!).

So, now as we see, the problem is that we have tried to tie down intelligence to Humans and have been very unjust in not acknowledging the intelligence of other species. Thus after careful observation, it seems like a better option to use Intelligence as an interface because it is more like a characteristic feature in humans. So, a much better way of denoting this relationship in Java would be like this :

class Human extends Mammal implements Intelligent
{
...
...
...
thinkStupidThings(){...}
}

where the thinkStupidThings() function is declared in the Intelligent interface. This way each class has to explicitly define the thinkStupidThings() function from its own point of view. Thats useful because i believe that both humans and dolphins have a very different perspective of stupid things.

So, deciding what is supposed to be an interface and what should be a base class is a design consideration and should be looked into carefully depending upon your business requirements.

As far as the question of implementing multiple interfaces come, lets assume that we have interfaces like Footballer, Cricketer,Artist,Moveable,Nocturnal etc etc. The human class can choose to implement all of these interfaces or any combination of them. So, if i were to make a joke out of it, i can say that you can choose to become a Footballer or an Artist or any other profession by simply implementing the appropriate interface and still somehow manage to remain a Mammal! Isin't that great? Is sure is. Oh, how i wish it were that easy in real life!

Well, thats all that there is to it. At least thats how i felt like explaining it. (lol)
Hope that you find it useful.

Happy Programming :)

Signing Off
Ryan

Tuesday, March 3, 2009

Saving Form Parameters In Strtuts 2

This post intends to answer the following questions : -
  1. How to store details entered in a form in a Struts 2 application?
  2. Do we have an action form class in struts 2?
  3. How to use my action class to store form data?
The most important question that needs to be answered here is question number 2. We do not have any action form in struts 2 like it used to be in struts 1.

Struts 2 makes it possible to make use of the action class itself as the class that can store the details submitted by the user in a form or sent as parameters in the request. This task is performed by the ParametersInterceptor. It is the task of the parameters interceptor to inject the values passed in the request to the struts 2 instance fields. This interceptor is used to call the appropriate setter method of the action class to inject the parameter into the instance variable. The only requirement is that you the name of the parameter and the setter must be the same.

For example, suppose that you have a form in which you have a textfield called 'age' which is submitted with the form. Now, to automatically save this value in the action class, you need have a method called setAge(int age), in the action class. The Parameters interceptor takes care of parsing the arguments to the appropriate data type. You can now save the age in a private instance variable. If you create a getter method such as getAge(), then this can also be called directly form the jsp page by using the property tag, if the action class in the value stack. Just make sure that the getter and setter methods are public so that they can be accessibe anywhere.

Happy Programming ;)

Signing Off
Ryan

Specifying Action Method In Struts 2

This post intends to answer the following questions : -
  1. How call multiple methods of the same action class as separate actions?
  2. How to configure different methods as action methods?
  3. Can we configure methods other than execute() to be called when we have call an action?
Struts 2 makes it possible to call any ppublic method in a class instead of the execute() method. This is possible by simple making a small configuration change in the struts.xml file for the required action.

By using this feature you can actually create a single action class and have many methods that perform different tasks. You can have as many different actions as there are methods in your class. You need not make any changes anywhere in your action class to enable it to service more than one type of action request. This is simply done by using the struts.xml file. However your functions must have the following syntax

public String fucntionName()
{
}

Consider an action class with the following two functions

MyActions.java
------Source Code Starts Here------
.
.
import .......
.
.
public class MyActions extends ActionSupport
{
.
.
.
public String method1()
{
//some code
//return SUCCESS/ERROR etc etc
}


public String method2()
{
//some code
//return SUCCESS/ERROR etc etc
}
------Source Code Ends Here------

Now, in order to call these methods on different action requests, the following configuration in struts.xml will suffice :-

struts.xml
------Source Code Starts Here------
.
.
.
<action name="action1" class="MyActions" method="method1">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
<result name="input">/error.jsp</result>
</action>
<action name="action2" class="user.My" method="method2">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
<result name="input">/error.jsp</result>
</action>

.
.
.
------Source Code Ends Here------

Notice the 'method' attribute that is used to specify the method that needs to be called for an action. All the rest of the code is the same as in regular action classes.

Happy Programming ;)

Signing Off
Ryan

Monday, March 2, 2009

Using The if, else and elseif tags in Struts 2

This post intends to answer the following questions :-
  1. How to use the if tag in Struts 2?
  2. What are the uses of the if else tag in Struts 2?
  3. How many flavors of the if else tag are there in Struts 2?
The all the flavors of the if else tag are control tags in the Struts 2 framework. As in every programming language, such control structures are used to evaluate a condition and then do something if the condition is true and do something else if the condition is false. But then you already knew that, didn't you? There are three basic flavours of this tag. I shall demonstrate each with an example.


Flavour1-Chocolate!

<s:if test="condition">

This will be printed if the condition is true.
</s:if>


Flavour2-Vanilla!
<s:if test="condition">
This will be printed if the condition is true.
</s:if>
<s:else>
This will be printed if the condition is false.
</s:else>

Flavour3-Strawberry!!
<s:if test="condition">
This will be printed if the condition is true.
</s:if>
<s:elseif test="second_condition">
This will be printed if the second_condition is true.
</s:elseif>
<s:else>
This will be printed if the second condition is false.
</s:else>

So, there you go, three delicious flavors to add to your ice cream bowl. you can eat them separately or you can mix them all up! Its all in your hands, or I would rather say, all over your hands! Feast on it!

Happy Programming ;)

Signing Off
Ryan

Using property tag in Struts 2

This blog post intends to answer the following questions :-
  1. What is the usage of the property tag in Struts 2?
  2. How can I display a default value if a property is not present on a jsp page?
  3. What does the property tag do in Struts 2?
The property tag in Struts 2 is highly useful when you need to display contents on the screen, especially those associated with the session or context objects. The struts 2 framework makes use of the OGNL and value stack, which makes accessing these scoped attributes easier than before, enabling you to completely eliminate the need of any scriplet code or expression in your pages. The property tag can access any object that is visible in the value stack. All that you need to do is to provide the name of the object to the 'value' attribute of the tag.

As an example assume that there is an attribute in the session scope called 'username'. Now, to print the value of this attribute, I need to do the following.

<s:property value="#session.username"/>

Consider another scenario, when you submitted a form with a textfield called 'location' and it calls an action. This action has a setter and a getter method for the location field. The action does some processing and results in a jsp page being displayed. Now, in order for you to display this 'location' field on your resulting jsp page, all that you need to type is : -

<s:property value="session"/>

This is because since the action was the last thing that was called in the calling chain, the instance of the action class was on the top of the stack and hence we did not have to write any code to specify the instance whose getLocation() method we were attempting to call.

Sometimes, it is useful to display sensible defaults on your jsp page when the property tag retrieves value that is null. i.e. the value is not on the stack. For example, you might want to display a message saying that a user needs to login if the username is not in the session. This can be done as follows.

Welcome !! <s:property value="#session.username" default="Login To Use Your Superpowers"/>

Happy Programming ;)

Signing Off
Ryan

Sunday, March 1, 2009

Using url and param tags in Struts 2

This blog post intends to answer the following questions : -
  1. How to make use of the url tag in Struts 2?
  2. How to invoke an action from a url link in Struts 2?
  3. How to pass parameters to an action from a url link in Struts 2?
  4. How to use the url tag to invoke actions in Struts 2?
The url tag in Struts 2 can come in very handy if you need to use a url in many places and dont want to repeat the code again and again. The url tag is simple and extremely easy to use. You need to specify an id attribute for your url and you can also use actions instead of simple links in the url. Adding parameters to the url is simple and is done by using the param tag.

...
...
<s:url id="someId" value="http://myurl.com"/>
<s:a href="%{someId}">Click Me</s:a>
...
...
You can also specify a relative url.


Actions can also be called instead of url's. This is done as follows.
...
...
<s:url id="someId" action="actionName"/>
<s:a href="%{someId}">Click Me</s:a>
...
...

Here is an example where you can pass parameters to the action by using the param tag in the url.
...
...
<s:url id="someId" action="actionName">
<s:param name="parameterName">parameterValue</s:param>
</s:url>
<s:a href="%{someId}">Click Me</s:a>
...
...

That's all there is to it folks!

Happy Programming ;)

Signing Off
Ryan

Creating Action Classes In Struts 2

This blog post intends to answer the following questions : -
  1. How to create Action classes in Struts 2?
  2. Can we use POJO's as action classes in Struts 2?
  3. How to use a POJO as an action class in Struts 2?
  4. What are the interfaces or classes one needs to extend to create an action class in Struts 2?
The Struts 2 programming model makes it very easy to create action classes. The Dependency Injection pattern enables us to add Struts 2 functionality to a variety of classes.

Basically Struts 2 allows you to create Action classes in three different ways :-
  1. Implement the org.apache.struts.action.Action interface.
  2. Extend the com.opensymphony.xwork2.ActionSupport class.
  3. Or simply use any POJO as an Action class.
Implementing the Action interface is very useful in cases when your class belongs to some other class hierarchy. Extending the ActionSupport class enables us to to make use of a large number of features and constants that are available through the various interfaces implemented by the ActionSupport class. ActionSupport provides empty implementations of a large number of abstract methods for many interfaces.

Using a POJO is quite simple as well. All that is required of you is to create method in the POJO with the following signature : -

public String execute()
{
//method code
}

So finally, getting down to the actual business details is not gonna take millions of years! Have fun!

Happy Programming ;)

Signing Off
Ryan

Return Type String Constants In Action Interface

This blog post intends to answer the following questions :-
  1. What are the String constants defined in the Action interface?
  2. What are the different String constants in the Action interface used for?
  3. What is the use of the following- SUCCESS, INPUT, ERROR, LOGIN, NONE?
The Action interface defines fines String constants that can be used as return types from any function in a Struts 2 Class. Since we use the execute method in most Struts 2 applications as our method where all the so called action takes place, these string constants are mostly used as return values in this function.

All the five string constants have a different purpose to solve in the Struts 2 framework.
  1. SUCCESS :- This return type is used to indicate that the result of the operation has been successful and the application is eligible to flow as in normal operating conditions.
  2. INPUT :- This return type is used to indicate that the requested action cannot be completed due to inappropriate or insufficient data entered by the user.
  3. ERROR :- This return type is used to indicate that a certain error condition was produced while performing the requested operation.
  4. LOGIN :- This return type is used to indicate that the action need proper authentication before it can perform the operation.
  5. NONE :- This return type indicates that the completion of the action is not associated with the display of a view component to the user.
You can also return your own strings form your action classes instead of the above mentioned ones. But then be sure to map your custom return value to a view in the struts.xml file using the result element as follows.

<result name="my_own_string">/myview.jsp</result>

Happy Programming ;)

Signing Off
Ryan

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