Showing posts with label STRUTS 2. Show all posts
Showing posts with label STRUTS 2. Show all posts

Sunday, June 12, 2011

Simple theming in Struts 2

I was just designing a page in struts. I had already designed the structure of the page using a text editor and also setup the necessary css and javascript for the layout.

But when I introduced a struts tag into the page by replacing the elements with struts tag, somehow the entire layout turned into a huge mess.

Reason? My page contained a form, and struts automatically applies a theme to the form that causes the elements to be rendered in the form of tables. I was like, WTF! When i saw my perfectly looking page utterly distorted coz of no mistake of my own.

If you are facing the same issue, you can simply resolve it by using the simple theme instead of whatever theme struts is using.

In my case, I did the following in my struts form.



Yea, that works. Piece of cake. I guess there should be a way to default the theme for the entire project instead of doing it one form at a time, especially since I like to do the styling of the web pages by myslef. Will have to check that.

Happy Programming :)
Signing Off
Ryan

Thursday, January 13, 2011

Using Struts 2 with JSON and jQuery

It took a decent amount of time to figure out how to set up struts 2 with JSON. and how to extract the data using jQuery. So, i thought that i'd better make a note of the stuff i learned and just restate the rules, few as they are, so that me or someone else can cross verify them when writing code.

There are a few things that need to be done in order to use JSON with struts 2. Basically, struts provides you with a few result types. For JSON, you will require a new Result Type, because, obviously, since the response is a JSON response, you dont have a page to redirect to.

So, first you need to download the JSON plugin, if you already dont have it in your struts download. As usual, keep it in the lib folder of your application.

The struts 2 JSON plugin allows you to create an action that can be serialized into a JSON object. Ok, what that means in basic terms is that in the response that is sent back to the client, the response is the Javascript object that represents the Action class, and the attributes of the javascipt object are actually named after the public getter methods of the action. If the value of any getter method returns a null, the value of the javascript attribute will be null and vice versa.

The plugin not only handles basic types but also complex types like lists and arrays. We will see a code snippet shortly.

First things first. Lets see what needs to be done for setting up our action for JSON.

Keep the json plugin jar in your lib directory.
In struts.xml, create a new package that extends json-default. If you want to use an existing package, you can simply use a comma separated value for the package names as the value of the extends parameter of the package tag. That is what I will be doing here. (TIP : json-default package extends struts-default.)
Specify the result type of your action class to be 'json'

Thats pretty much all you need to do to get things going from the struts configuration perspective.

The json-default package contains an interceptor and the result type configuration for JSON requests and responses.

Now lets get to the code.


  1. From the browser perspective : jQuery
    jQuery allows you to issue an ajax request that expects a JSON object as a response by the getJSON method. Like all other ajax requests, the syntax for making the call is the same. You need to pass the url, a javascript object representing the form parameters, and a function that will be invoked upon the return of the invocation. In the returned function, the data that is returned from the server can be treated as a JSON object.

  2. From the server's perspective : Struts 2 
    All you need to do is to create instance variables and respective getter and setter methods for variables that need to be accessed via javascript. Once in the execute method, you can simply set the values of these instance variables. Then the action need to be configured to return a json object in the struts configuration file.


The point to be noted here is that all the variables that have a setter can be set to the values as received by the form parameters. And all the variables that have a getter method can be retrieved in the client javascript code.

In the following code sections, we will see how we can not only handle simple data types, but also, lists and maps as JSON objects.

First the HTML. This is just an ordinary form that contains nothing but a text field for the user to enter a name. The struts action that we will write will just be used to say Hi to the user.



The form id is introForm. Lets handle the submit event of this form in the code to return false, since we do not want to be going anywhere when the user submits. All the action must stay on this page itself.

$(function(){

 $("#introForm").submit(function(){
 
  return false;

 });
 
});

So, now that we know that the action will stay here, what we need to do is serialize the form inputs and issue a request to the server with the form inputs. But before we do that, we must first create the action class and then configure the action and its url in the struts configuration file. So, lets jump towards the server code for once.

Creating the action class is as simple as it has ever been. Since this is a demo, I have created a few instance variables of type List and Map and will populate some dummy values in them so that they can be retrieved using javascript later. Also note that for all my instance variables, I have created getter methods so that their values can be retrieved.

public class AjaxActions extends ActionSupport{

    private String name;
    private String greeting;
    private List countryList;
    private Map countryMap;

    public String sayHi(){
        
        greeting="HI " +name;

        countryList=new ArrayList();
        countryList.add("US");
        countryList.add("UK");
        countryList.add("Russia");

        countryMap= new HashMap();
        countryMap.put("US",1L);
        countryMap.put("UK",2L);
        countryMap.put("Russia",3L);

        return ActionSupport.SUCCESS;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGreeting() {
        return greeting;
    }

    public void setGreeting(String greeting) {
        this.greeting = greeting;
    }

    public List getCountryList() {
        return countryList;
    }

    public void setCountryList(List countryList) {
        this.countryList = countryList;
    }

    public Map getCountryMap() {
        return countryMap;
    }

}

So, basically what i have done here in the sayHi() function is to initialize an instance variable call greeting, that says hi to the user. Then i populated a dummy list with the names of a few countries. Then i populated a dummy map with the country codes of those countries. My objective is to fetch the greetig, the list and the map on the action from the javascript code.

In the struts configuration file, the following lines would be sufficient to configure the JSON action.


    
        
            
                
            

    


Now my server side code is ready.

Getting back to the javascript code, I am simply going to print the values on the firefox console, you can choose to do whatever you feel like!

$(function(){

 $("#introForm").submit(function(){
  
  var formInput=$(this).serialize();
  
  $.getJSON('ajax/sayHi.action', formInput,function(data) {
   
   $('.result').html('' + data.greeting + '
');

   $.each(data.countryList,function(index, value){
    console.log("value " + value);
   });

   $.each(data.countryMap,function(key, value){
    console.log("key "+ key + ", value " + value);
   });
  });

  return false;

 });
 
});


That does it! Last but not the least, many thanks to the programmers to write such a easy to use plugin. Kudos to all of you!

Happy Programming :)
Signing Off
Ryan

Friday, November 5, 2010

Struts 2 : Creating and accessing maps.

Today, in this post, I am going to discuss how to create and access HashMaps in Struts 2.

My environment has the following jar files.
struts2-core-2.1.8.1.jar
ognl-2.7.3.jar

Struts 2 makes extensive use of OGNL in order to retrieve the values of elements. OGNL stands for Object Graph Navigation Language. As the name suggests, OGNL is used to navigate an object graph. In this post, i am going to use the OGNL syntax to create Map on a jsp page, and show you how to iterate over it to fetch the keys and values from the map.

In the following example, i will create a map, on they fly in the iterator tag, and will use it in the body of the iterator tag.







Note the syntax that has been used to create a Map on a jsp page in struts 2 using OGNL. Once the map is created, the iterator tag can be used to iterate over each element of the map.

Now suppose the map that we want to access is in a map inside the HttpRequest. Assume that some action somewhere in the chain has kept a map in the request using the key "myMap". In order to iterate over the elements of the map, we can do the following







Okey now, enough with iterating over maps. I don't think there are any more permutations for accessing maps. But if i do find more, ill document them down here.

Consider a case where you dont want to iterate over the entire map. Instead, all that you want to do is to extract a value form the map based upon a key that is already known to you in your jsp page.

Assume that you have a variable in page scope called "runtimeKey" that you set using the s:set tag. The value of this variable is a string key that can be used to get a value from a map.

Here is how you can fetch the value from the map without iterating over it.




As you see, since the variable "runtimeKey" is an OGNL variable and is available on the value stack, it can be referenced using the # notations. Also not that instead of using the dot notation, I have used square brackets to fetch the key. This is because the value of my expression "#runtimeKey will only be evaluated when its inside the brackets. Also note that the value of the key runtimeKey is contained within single quotes to direct OGNL to evaluate it as a string when setting as the value for my key.


Consider another situation where your keys follow a pattern. For example key_1, key_2. And you have the values 1 and 2 as page scoped variables. So, now instead of having the string value of the key directly, you may have to construct the key using concatenation.



Your key pattern was set above. And you Map has a key called key_1. So, here is how you would have to concatenate your strings in order to construct the key and fetch the value.



Huh. So easy!

Thats all for now folks.. Stay tuned for more!

Happy Programming :)
Signing Off
Ryan

Monday, October 18, 2010

Struts 2 - Creating Dynamic results

Hi everyone,

Today, in this blog post, I am going to jot down a way to create dynamic results in struts 2.

Lets first begin with a few questions.

What do i mean by dynamic results?


We all know that struts allows us to configure the pages to which request must be dispatched to redirected to, via the "result" tag. However, at times, it may be hard to determine at configuration time itself, which pages need to be set as the result. For example, your business logic may determine the action or the jsp that you need to forward to. In the following example, I am going to try and allow the dynamic results in Struts 2.


Whats my objective?


To create an action class that determines the jsp page name that we need to forward to based upon some business logic.
Configure the action in my struts configuration file(struts.xml) for dynamic results
Invoke the action.


Now, lets begin.

Firstly, we create an action class called DummyAction2. (STATUTORY WARNING : The naming conventions in this post, and for the record, many others, might sound bit weird, but i have a tonne of experiments, and its really hard to settle on a proper name for every whim that comes to my mind. So, please bear with me on that note. :> )

My action class is like any other action class. It contains an execute method. But in my case, the execute method does not do anything, except return a "success" string. Thats because i have another business method, which i am going to name as(surprise! surprise!) anotherMethod. This is the method that i am going to invoke using my action mapping.

In order to be able to identify the page that we need to display, we need to create an instance variable that holds the name of the page that we need to forward to. And we create getter/setter methods for this instance variable.
Ill just keep the business logic simple, and store the name of the next page to be displayed, in this instance variable when the action is invoked.

Lets take a sneak peek at the code in the action class.


public class DummyAction2 extends ActionSupport{

    private String nextPage;

    public String execute()
    {
        return ActionSupport.SUCCESS;
    }

    public String anotherMethod(){
        String actionStatus=ActionSupport.INPUT;
        System.out.println("Another Method in Dummy Action");
        
        nextPage = "myPage.jsp";

        actionStatus=ActionSupport.SUCCESS;
        return actionStatus;

    }
    /**
     * @return the nextPage
     */
    public String getNextPage() {
        return nextPage;
    }

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

As you see, there's nothing much going on in my anotherMethod. All i do is to set the value of the next page in the instance variable. And then i simply return a success response from the action class.

The mapping is where the real magic takes place. In your mappings, you can dynamically determine the value of a variable in an action using ordinary EL. Lets see the code first.


                ${nextPage}
            

Okey, i was lying. Its no magic. Its just that, in your struts configuration file, you can access the properties in your current action class using ordinary EL. Thats exactly what we have done here. The string ${nextPage} is used to extract the value of the property named "nextPage" from the current action. And since that action is a jsp page in our case, that's the page that will be rendered to the user.

Invoking the action is done in the same old fashioned way.

Invoke Dynamic Result

I guess, the idea is pretty clear.

Thats all for now. See you folks next time!

Happy Programming :)
Signing Off
Ryan

Sunday, January 17, 2010

struts 2 tags demo : select tag

In this post we are going to see examples of how to use the struts 2 select tag in our jsp pages.

NOTE : The examples in this post are just bare bones examples and do not necessarily demonstrate the way that you should design the flow of your code.

To begin with, I would like to list down the prerequisites for these examples that are set up on my system.

Struts version : struts-2.1.8.1

jar files to include in your lib directory :

  • commons-fileupload-1.2.1.jar
  • commons-logging-1.0.4.jar
  • freemarker-2.3.15.jar
  • ognl-2.7.3.jar
  • struts2-core-2.1.8.1.jar
  • xwork-core-2.1.6.jar

Although the code that is written here does not mandate the need of an IDE and can be written using a simple text editor, however, during my experiments, I have been using Netbeans 6.8.

Server : Tomcat 6.0

That takes care of the runtime environment.

Now about our examples.

In the code sample below, i am going to create something of the sort of an ice cream parlor that gives the user an option to select the flavor of his choice by using the struts 2 select tag. The user can submit his choice to an action that prints the user's choice on the server logs using the omnipresent System.out.println().

First, our Flavor class :


public class Flavor {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}





The Bean that handles the creation of a list of flavors that will be used in the select tag.

package sample;

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author ryan
 */
public class IceCreamCorner extends ActionSupport{
    
    private List flavors;

    public List getFlavors() {
        return flavors;
    }

    @Override
    public String execute()
    {
        System.out.println("Inside IceCreamBean : Method : Execute.");
        /*
         * Please note that this way of initializing is just for demonstration purposes
         * In real applications, you will fetch this data using a DataAccessObject (DAO).
         * Or if you are using spring/hibernate/EJB, the Flavor class can be an entity.
         * The only objective in this example is to populate a list with Flavor objects.
         */
        Flavor f1=new Flavor();
        Flavor f2=new Flavor();
        Flavor f3=new Flavor();

        flavors=new ArrayList();

        f1.setName("Vanilla");
        f1.setId(1);

        f2.setName("Chocolate");
        f2.setId(2);

        f3.setName("Strawberry");
        f3.setId(3);

        flavors.add(f1);
        flavors.add(f2);
        flavors.add(f3);

        System.out.println("Flavor list size : "+flavors.size());
        return ActionSupport.SUCCESS;
    }
}




Following is the class that the user will submit his flavor choice for further processing.


package sample;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;

/**
 *
 * @author ryan
 */
public class FormAnalyzer extends ActionSupport{

    @Override
    public String execute()
    {
        System.out.println("Inside FormAnalyzer : Method : execute");
        ActionContext ac = ActionContext.getContext();

        HttpServletRequest request=(HttpServletRequest)ac.get(ServletActionContext.HTTP_REQUEST);

        Enumeration paramNames= request.getParameterNames();

        while(paramNames.hasMoreElements())
        {
            String param=(String)paramNames.nextElement();
            System.out.println("\nParameter Name : "+param);
            System.out.println("Parameter Values : ");
            
            String[] paramValues=request.getParameterValues(param);
            
            for(String paramVal:paramValues)
            {
                System.out.println(paramVal);
            }
            
        }

        return ActionSupport.ERROR;
    }
}


The struts.xml configuration file.



 

        
            
             
                /success.jsp
            
            
                /failure.jsp
                /success.jsp
            

        



First let me demonstrate using the struts 2 select tag with a dynamically created list



            
            
            
        

In this example, the value that is sent to the FormAnalyzer class is the value of the text that is displayed in the drop down menu.

Before we use the list of flavors of ice creams in the select tag, first the list needs to be initialized. In our example here, we will achieve that by calling an action in the page that will do nothing but populate our list. We will store this action object as a variable on our page and later access this action object to retrieve the list of flavors.

The action object that will be used here is an object of class IceCreamCorner. Thw following line will have to be included before executing any select tag for the examples given in this post.




Now, you can use the given examples and see for yourself the effects of setting the different tag attributes of the struts 2 select tag.

Example 1 : Demonstrating the use of the s:select tag with the listKey and listVaue attributes


            
            
            
        



Example 2 : Demonstrating the use of the s:select tag without the listKey attribute In this case, the String representation of the list object,i.e. toString() value, itself is sent as the paramter value which is not a very useful thing to do. Hence, it makes more sense to use the listValue attribute with the listKey attribute.



            
            
            
        


Example 3 : Demonstrating the use of the s:select tag with a predefined selected value


            
            
            
        



Example 4 : Demonstrating the use of the s:select tag which can have multiple selections



            
            
            
        


I Hope that helps.

Signing Off
Ryan

Sunday, January 10, 2010

Creating Custom Interceptors in Struts2

In this post, i am going demonstrate how to create your own custom interceptor in Struts 2.

In my previous post here I demonstrated how to declare and configure interceptors in the struts.xml file. In this post we will see how to create a simple interceptor that will execute and print a few lines to the server logs, both before and after an action is executed.

A few points need to be kept in mind before writing your own interceptors ;
  1. You can create your own custom interceptor in two ways
    Implement the Interceptor interface
    Extend the AbstractInterceptor class.

  2. If You are implementing the Interceptor interface, you have to provide implementations to three methods :
    void destroy();
    void init();String intercept(ActionInvocation invocation) throws Exception;

  3. The 'init' method is called before the 'intercept' method is called. An interceptor instance is created once and is reused over many requests. Hence the interceptor code must be written to be thread safe.

  4. The 'intercept' is the place where you write the business logic code of your interceptor.

  5. The 'destroy' method is executed on application shutdown and is used to release resources used by the interceptor that have been allocated in the init method.

  6. If you are extending the AbstractInterceptor class, you only need to override the method :
    String intercept(ActionInvocation invocation) throws Exception method to provide your own implementation.

  7. In our example we will be extending the AbstractInterceptor class.
I first begin by creating a dummy action.



package sample;

import com.opensymphony.xwork2.ActionSupport;

/**
 *
 * @author ryan
 */
public class DummyAction1 extends ActionSupport{

    public String execute()
    {
        System.out.println("Inside DummmyAction1");
        return ActionSupport.SUCCESS;
    }
}


Now i create two interceptor classes.


package interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 *
 * @author ryan
 */
public class MyInterceptor1 extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        System.out.println("Inside MyInterceptor1- Before Executing Action");
        //System.out.println("Next Invocation will invoke : "+ai.invoke());
        String invocationResult = ai.invoke();

        System.out.println("Inside MyInterceptor1- After Executing Action");
        return invocationResult;
    }

}



package interceptors;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 *
 * @author ryan
 */
public class MyInterceptor2 extends AbstractInterceptor{

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        System.out.println("Inside MyInterceptor2- Before Executing Action");
        
        String invocationResult = ai.invoke();

        System.out.println("Inside MyInterceptor2- After Executing Action");
        return invocationResult;
    }

}




The following code shows the configuration of struts.xml



 

        
            
                
                
            

            
                
                
                /success.jsp
            
        
        



You can test this code by adding the following two lines on your jsp page to invoke your action.



Click To Test Interceptors

Since the action is already configured such that the two interceptors will be called before and after it is executed, you can check your server logs to ensure that the interceptors are executing in the order as specified in the configuration.

My Tomcat logs show the following : 


Inside MyInterceptor1- Before Executing Action
Inside MyInterceptor2- Before Executing Action
Inside DummmyAction1
Inside MyInterceptor2- After Executing Action
Inside MyInterceptor1- After Executing Action


Now lets see what is happening in the code.

Consider the intercept method of MyInterceptor1. This method is called with an argument of type 'ActionInvocation'. The ActionInvocation object is created by the struts framework and is used as a handle to the execution environment of the interceptor. It contains several useful methods. You can find the list of methods in this extremely useful class at its documentation here.

The ActionInvocation object is the heart and soul of your interceptor class. As we have already seen earlier, we can have several interceptors for a given action. The information of the sequence in which these interceptors are executed for the action is stored in the ActionInvocation object. The next interceptor in the sequence is called by calling the invoke() method of the ActionInvocation object. For the first Interceptor, the invoke() method is called by the ActionProxy object.

Since the invoke method causes the next interceptor/action in the sequence to be executed, the interceptor is in absolute control of the execution and can decide at any moment whether to proceed with the next step in the sequence or to return an error to the caller without proceeding.

A point to be remembered is that String value returned by the the invoke() method is the value that is retrieved after the action and its result have been executed. In our example, when the myInterceptor1 interceptor calls its invoke, control is passed on to the myInterceptor2, which in turn calls the action. The action upon execution returns "success" as the string, which is in turn returned to the myInterceptor2, which is in turn returned to 'myInterceptor1'. At this point of time, the result has already been executed or your jsp page has already been rendered.

As done in the above example, you can save the return value in a local variable, perform some tasks. And if everything seems to be fine, you can simply return the value in the local variable at the end of the method.

So, we have finally created and configured a custom interceptor in a simple struts 2 application.

Signing Off
Ryan

Saturday, January 9, 2010

Struts 2 interceptors overview


Interceptors are are one of the most powerful features in struts 2. Interceptors are useful because they enable you to perform common tasks across actions withoug having the need to recompile the code. Interceptors are configured in the struts onfiguration file for an action.

Interceptors are executed in the sequence in which they are declared. A set of interceptors that are required to execute in a sequence can be grouped together to form an interceptor stack.

Interceptors are declared in the struts.xml file inside a package.
Following is an example of interceptor declaration in struts.xml





 
 


As already mentioned Interceptors are executed in a sequence. They can be grouped together and the grouping is given a name. For example :




 
 
 
 
  
  
 


The 'name' attribute of interceptor-ref element can take an interceptor name or an interceptor stack name as its value. For example,




 
 
 
 
 
  
  
 
 
 
  
  
 


So, now we are done with interceptor declaration. So, how do we use these interceptors for our action classes? Following is an example of using the above interceptors for an action class.




 .
 .
 interceptor declarations
 .
 .
 
 
  
  /success.jsp
 



In the above example, we have cofigured the 'iName1' interceptor to execute before the methods of the action class get executed. You can also configure an interceptor stack to execute for an action. Example :




 .
 .
 interceptor declarations
 .
 .
 
 
  
  
  /success.jsp
 


When a package extends another package, it inherits all the configuration of the parent package including interceptors and interceptor stacks. So by extending the struts-default package, we get access to several useful preconfigured interceptor stacks namely




  • defaultStack
  • completeStack
  • basicStack

and many other interceptor stacks, and also a number of interceptors namely



  • exception
  • servlet-config
  • prepare
  • static-params
  • params
  • conversion-error
  • validation
  • workflow
  • model-driven
  • chain
  • i18n
  • execAndWait


Sometimes you need to execute a given interceptor/interceptor stack for all the actions in a package, and it can become quite frustrating to configure the same interceptor for each action. This can be avoided by configuring the package to have a default interceptor for all its actions. For example, in our code sample, if we want the 'myInterceptorStack' interceptor stack to be the default interceptor stack of that package, then we need to simply add one more element to the package element. Example :




 .
 .
 interceptor declarations
 .
 .
 
 .
 .
 action declarations
 .
 .
 
 


Well, thats it. :>



Signing Off
Ryan

Struts 2 Namespaces

Here are a few things that I learnt about struts 2 namespaces during my silly experiments.


  1. The namespace attribute of element in struts.xml is an optional attribute. The default namespace is "" . i.e. an empty string.

  2. The value of your namespace must always begin with a "/".

  3. Namespaces are used to group together a set of actions.

  4. An action with the same name can exist in several namespaces. The action that will be invoked depends upon the namespace in which it is called.

According to the struts 2 documentation, struts 2 tags are meant to be namespace aware. i.e. you should not need to append the namespace name in the url's and links in on a jsp page when creating links. However, it does not seem to be working for me. So, i use the namespace attribute whenever necessary.

However, if an action with the same name exists in multiple namespaces then the action in the default namespace is called if no namespace is specified in the link.

An important point to note is that when you declare a package with a namespace, all the results that you configure for an action usuing the result tag are assumed to be relative to that namespace if they are not preceded by a /.

For example suppose you have the following configuration in struts.xml such that the same action name is present in two packages but the namespaces are different. Let us assume that the name of your web application root is 'struts2app'



            
                success.jsp
            
        
 
            
                failure.jsp
            
        


In your jsp page, you can access action1 in namespace1 by writing the following code




Click Me To Test Namespace


Struts will look for the page success.jsp in struts2app/namespace1/success.jsp

However, if your success.jsp is exists direcly under the root directory, the you need to specify the result configuration as follows.




/success.jsp




The leading "/" indicates that the page is located at the web application root.
          
In this case, struts will try to find the page success.jsp in struts2app/success.jsp

That takes care of the bare basics of using namsepaces in struts 2.

Signing Off
Ryan

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

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