Tuesday, December 22, 2009

Using struts 2 tags

In order to use the struts 2 tags in you .jspx files, you need to add the following lines to your source code at the beginning of your page.

For jspx files, add the following :


xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:s="/struts-tags"
version="2.0">

For jsp pages, add the follwing :

<%@ taglib uri="/struts-tags" prefix="s" %>


This will help you to use the prefix 's' in order to use the struts tags in your .jspx and jsp pages.

Struts 2 iterator tag sample

Here is a small example of using the iterator tag in struts 2.

    


Its a very simple example. I will keep posting more complex ones over here as and when i get a chance to work with them.



Signing Off
Ryan

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

Sunday, October 11, 2009

Accessing JSF Backing Beans From Another JSF Backing Bean

Here is a simple piece of code that lets you access a backing bean from another backing bean. i.e. in the java code of a backing bean in JSF 1.1. A backing bean that exists in the session cannot be directly accessed from the map containing the other session objects. So here is a small workaround.

FacesContext context=FacesContext.getCurrentInstance();
Object obj=context.getApplication().createValueBinding("#{"+ "visit" + "}").getValue(context);

Cast the object to the appropriate backing bean type. That solves the problem.
Hope it helps.

Happy Programming :)

Signing Off
Ryan

Accessing the session from JSF backing beans in JSF 1.1

One of the problems that I faced while developing applications using JSF was the issue of how to access the map containing the session objects in JSF backing beans. I wanted to access the current users session after he makes an attempt to log in and then store a User object in the session on successful login after retrieving his relevant details from the backend.

After a bit of searching i came across a simple and elegant solution. Here is a small excerpt from code.

FacesContext context=FacesContext.getCurrentInstance();
Map session =context.getExternalContext().getSessionMap();

This gets me a handle of the session map. And thats pretty much there is to it.
I hope it helps you if you are struggling with the same issue.

Happy Programming
:)

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

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

Saturday, January 31, 2009

Servlet Filters

This blog intends to answer the following questions :-
  1. What is a Filter?
  2. Why should I use filters in my web application?
  3. How do I use Filters in a web application?
Here is what I have :-
  1. An local installation of tomcat that listens on port number 8080.
  2. A web application called FilterApplicationExample placed in the tomcat-installation-directory/webapps.
  3. The directory structure of every web-application in java should have a format. If you are unaware of the format, please refer to my other posts.
  4. Now I create a java file - MyFilter.java in the WEB-INF/src/examples directory.
  5. This file would house the code that would be executed as a filter for this application.
  6. I also create a Servlet named - 'MyServlet.java' in the WEB-INF/src/examples directory.
  7. This file will house the code for the the servlet that is actually requested by the client.
  8. I also have a file - 'web.xml' in the WEB-INF directory that houses the code that will be used to associate my Filter with the Servlet.
Here is the explanation :-

First and foremost lets know something about a filter. I believe everyone of us has seen a basic water filter. What does it do? Of course, it filters water so that we get pure and clean dringking water so that we can stay healthy. Similarly, when web applications were created, the developers presumably chose to use the same concept for web applications as well.

Just as in a normal water filter, a Filter in a web application in a piece of code that is supposed to execute when a client requests for a particular web resource. For example, in this application, the client will request for a servlet file, but before the code in the servlet file is executed, the code in the Filter will execute without the client being aware of this fact.

So, why do we use filters? Well, filters are intended to do important pre-processing of client requests. What kind of pre-processing? Well, normally, when we talk about pre-processing, we mean performing certain basic tasks that are not directly related to the client request. For example logging, authentication, authorization, encryption - decryption, data compression etc.

All these tasks are supposed to run without the client requesting for them directly. We also notice an important feature about these pre-processing tasks. Most of them will be required for a large number of resources in a web-application. For example, i may have 3 servlets in my application whcih may require encryption to be done. Since this is a common task, I can use an encryption filter in my web application and assiciate these servelts with the encryption filter. The advantage that i gain by doing this is that that encryption code that is common to all these three filters does not become redundant in the three servlets. MoreOver, if i later on need to extend my application, and have more servlets require the encryption filter, all that I have to do is to associate the new servlet with the filter thereby reducing development effort and time. Over and above, if the encryption algorithm need to be changed, then io need to make changes in only a single location and it will be automatically be reflected in all the servlets associated with the encryption filter.

Filters are used in web-application declaratively. This means that I just tell the web application, through an xml file that I want to associate a particular filter with the given request-URL or a servlet. This mysterious xml file is the same old web.xml that we use all along.

Here is how I do it :-

MyFilter.java
//------Start Of Source Code------
package examples;

import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;

public class MyFilter implements Filter
{
FilterConfig fc;

public void init(FilterConfig fc) throws ServletException
{
this.fc=fc;
}

public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain) throws ServletException, IOException
{
HttpServletRequest hreq=(HttpServletRequest)req;
HttpServletResponse hresp=(HttpServletResponse)resp;

PrintWriter pw=hresp.getWriter();
hresp.setContentType("text/html");

pw.write("inside filter, before going to the servlet");

chain.doFilter(req,resp);

pw.write("inside filter, after returning from the servlet");

pw.flush();
pw.close();
}

public void destroy()
{
}
}
//------End Of Source Code------



MyServlet.java
//------Start Of Source Code------
package examples;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class MyServlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter pw=resp.getWriter();

pw.write("<br/>");
pw.write("inside the servlet");
pw.write("<br/>");

}
}

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



web.xml
//------Start Of Source Code------
<web-app>
<servlet>
<servlet-name>SampleServlet</servlet-name>
<servlet-class>examples.MyServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SampleServlet</servlet-name>
<url-pattern>/go</url-pattern>
</servlet-mapping>

<filter>
<filter-name>SampleFilter</filter-name>
<filter-class>examples.MyFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>SampleFilter</filter-name>
<url-pattern>/go</url-pattern>
</filter-mapping>
</web-app>

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


Compile the java files and copy the .class files obtained into the WEB-INF/classes/examples directory.
Now Start tomcat and type the following url in your address bar :-
http://localhost:8080/FilterExample/go
Now press the Enter/Return key.

You should get the following output :-
inside filter, before going to the servlet
inside the servlet
inside filter, after returning from the servlet

This is jsut a bare bones example do demonstrate how to use filters. Kindly ignore the malformed html. I have not followed any good programming practice just to keep the code as simple as possible and to focus on the problem at hand. Hope that you find this demonstration useful.

Happy Programming ;)

Signing Off
Ryan

Saturday, January 24, 2009

Updating JPanels

This blog post intends to answer the following questions.
  1. How to update a JPanel?
  2. How to dynamically change the contents of a JPanel based on user interaction?
Here is what I have :-
  1. A File called MainFrame.java that has a button labeled 'Click Me', and a panel called displayPanel.
  2. A file called Panel1.java that has a button labeled as 'Button1'.
  3. A file called Panel2.java that has a button labeled as 'Button2'.
Here is what I have done :-
  1. The constructor of my MainFrame class initializez the button 'Click Me' and initializes the displayPanel to Panel1.
  2. So now when i run the application i get 2 buttons on my screen - 'Click Me' and 'Button 1'.
  3. When the user clicks on the 'Click Me' Button, i intend to make the displayPanel refer to the Panel 2 and hence display the 'Button 2 on my MainFrame.
Here is how I do it :-

Panel1.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.*;

public class Panel1 extends JPanel
{
JButton button1;

public Panel1()
{
this.setSize(250,250);
button1=new JButton("Button 1");
this.add(button1);
}

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

Panel2.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.*;

public class Panel2 extends JPanel
{
JButton button2;

public Panel2()
{
this.setSize(250,250);
button2=new JButton("Button 2");
this.add(button2);
}

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

MainFrame.java
//------Start of Source Code------
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MainFrame extends JFrame
{
JPanel displayPanel;
JButton myButton;

public MainFrame()
{
super("MainFrame");

myButton=new JButton("Click Me");
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
updateMainUI();
}
});

this.setSize(400,400);
this.addWindowListener (new WindowAdapter() {
public void windowClosing (WindowEvent e )
{
System.exit( 0 );
}
}
);

displayPanel=new Panel1();

Container c=getContentPane();
c.setLayout(new BorderLayout());
c.add(myButton,BorderLayout.NORTH);
c.add(displayPanel,BorderLayout.SOUTH);
this.setVisible(true);
}

public void updateMainUI()
{
this.getContentPane().remove(displayPanel);
displayPanel=new Panel2();
this.getContentPane().add(displayPanel,BorderLayout.SOUTH);
this.getContentPane().validate();
}

public static void main(String [] args)
{
MainFrame mf=new MainFrame();
}

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

I wrote this piece of code after toiling for about 3 hours on the internet. At all the places where I searched, the people who had solved a similar problem, just explained the procedure of how they had done it. Nobody had posted any code for the solution(at least in the forums where i searched). For those of you who feel that I am bad at 'googling', I already know that i am bad at it (lolz).I sincerely hope that this piece of code comes in handy to anyone and everyone who stumbles upon it.

Happy Programming ;)

Signing off.
Ryan

Tuesday, January 20, 2009

A Random Integer Array

Here is a sample program that creates an array of a given size containing random values with the 'size' as the range.
The function 'createRandomArray' generates the random array.

RandomArray.java

//--------Start Of Source Code------
public class RandomArray
{
public static void main(String [] args)
{
int [] sample=createRandomArray(30);

for(int i=0;i<sample.length;i++)
{
System.out.println(sample[i]);
}

}

//This function performs all the randomization task
public static int[] createRandomArray(int size)
{
int [] randomArray=new int[size];

for(int i=0;i<size;i++)
{
randomArray[i]=i;
}

for(int i=0;i<size;i++)
{
int pos=(int)(size*Math.random());

int temp=randomArray[i];
randomArray[i]=randomArray[pos];
randomArray[pos]=temp;
}

return randomArray;
}

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

Happy Programming. ;)

Signing off.
Ryan

Saturday, January 10, 2009

Command Line Echo

The program in this blog answers the following questions:
  1. How to read input from the command line?
  2. How to echo data read from the command line?
  3. What wrapper must be used to read a line of input from the command line?

This simple program demonstrates the use of the java.io package to read command line data.

CommandLineReader.java

//--------Start of source code------

import java.io.*;

public class CommandLineReader
{
public static void main(String [] args)
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

try{
System.out.println(br.readLine());
}
catch(IOException ioex)
{
System.out.println("An IOException was thrown");
}
}
}

//--------End of source code-------

Compile this program using:
javac -cp . CommandLineReader.java

Run this program using:
java -classpath CommandLineReader

When you execute this program, you will be prompted to enter some text on the command line. Enter some text and see how it is echoed back to you on the command line itself.

Explanation:
What this program does is that it makes a new InputStreamReader that takes input from the command line(represented by System.in), because data from the command line is treated as an Input Stream. Now since my intention is to read one line at a time, i need to save each character entered by the user in a buffer. The BufferedReader class does this for me. Now when a complte line is entered(i.e. the usr presses the enter/return key), i retrieve this line from the BufferedReader and print it back on the command line.

Happy Programming ;)

Signing Off
Ryan

Tuesday, January 6, 2009

XML Friendly Pages

Now, this post was intended to solve a problem that i faced while blogging. As you see, i post code snippets in this blog. However, since my code can sometimes contain XML unfriendly characters like < and > so i had to find a way around it. Well, i tried using CDATA as well, but google just wont let me post. The savvy programmer that i am , i decided to make a simple and short program to find way around this.
What i did was that i made a program that would replace the above mentioned XML unfriendly characters from my source file into XML friendly ones.

This program takes an argument a file that needs to be converted.

The code goes as follows:

MakeXmlFriendly.java

//--------Start of source code----------------
import java.io.*;

public class MakeXmlFriendly
{
static File inputFile;
static File outputFile;
static StringBuffer inputFileBuffer;
static StringBuffer outputFileBuffer;


public static void main(String [] args) throws IOException
{
if(args!=null&& args.length>0)
{
inputFile=new File(args[0]);
outputFile= new File("XmlFriendly"+args[0]);

inputFileBuffer=new StringBuffer();
outputFileBuffer=new StringBuffer();

BufferedReader inputFileReader=new BufferedReader(new FileReader(args[0]));
BufferedWriter outputFileWriter =new BufferedWriter(new FileWriter(outputFile));

String separator=System.getProperty("line.separator");


String line=inputFileReader.readLine();
while(line!=null)
{
System.out.print(line);
outputFileBuffer.append(line);
outputFileBuffer.append(separator);
line=inputFileReader.readLine();
}


String replaceString=outputFileBuffer.toString();
System.out.print(replaceString);
replaceString=replaceString.replaceAll("<", "&lt;");
replaceString=replaceString.replaceAll(">", "&gt;");

outputFile.createNewFile();

outputFileWriter.write(replaceString);
outputFileWriter.flush();
outputFileWriter.close();
}
}
}

//--------End of source code---------------

With little more improvement, i suppose that it will come in quite handy.

Happy Programming ;)

Signing Off
Ryan

Sunday, January 4, 2009

A First AJAX Program

This post should be able to answer the following questions:
  1. How to create the simplest AJAX program?
  2. I need a simple AJAX template from where I can begin coding.
The code sample given below has been executed on Mozilla Firefox version 3.0.5 and uses Apache Tomcat 6.0 as the application server.

I make use of 2 files. Ajax1.html and data.txt. Both these files have been placed in a folder named 'myajax' in the 'webapps' directory of tomcat.

My first file is a simple html file that contains a small amount of javascript that does the magic trick for us. The second file contains the a few lines of text that is magically transferred using AJAX.


-------------------Start Of Sample Code--------------------
Ajax1.html

<html>
<head>
<script language="javascript">

var ajaxObj=false;

if(window.XMLHttpRequest)
{
ajaxObj=new XMLHttpRequest();
}

function magicByAjax()
{
var obj=document.getElementById('target1');
if(ajaxObj)
{
ajaxObj.open("GET","http://localhost:8080/myajax/data.txt",true);
ajaxObj.onreadystatechange=function()
{
if(ajaxObj.readyState==4&&ajaxObj.status==200)
{
obj.innerHTML=ajaxObj.responseText;
}
}
ajaxObj.send(null);
}
}

</script>

</head>
<body>
<input type="button" value="Click Me To See Some Ajax Magic" onclick="magicByAjax()" id="b1"/>
<br/>
<div id='target1'>
Data fetched from server goes here
</div>
</body>
</html>


data.txtWush! Bang! Here I come from server-land.

----------------------End of sample code-------------------------

Start the tomcat server.
Type the following url in Mozilla Firefox:

http://localhost:8080/myajax/Ajax1.html

Click on the button and enjoy the magic.

Happy Programming ;)

Signing Off
Ryan