Pages

Wednesday, November 9, 2011

Interceptors with Struts 2


Well another mile stone to me and learning all by yourself is such a pain. Now I understand the interceptors better. After all I was having a lot of issues with them

An interceptor as the name signifies gets triggered when an action is invoked provided the action is associated with the interceptor

 First of all following is my action class

import com.opensymphony.xwork2.ActionSupport;

public class TestLoggerAction extends ActionSupport{

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


Following is a my interceptor class. I have imported Action support class here as well in order to overrule the return value of the action. You would understand the same when you uncomment a specific code indicated in the following block of code

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class MyLoggingInterceptor extends ActionSupport implements Interceptor  {

       private static final long serialVersionUID = 1L;


       public String intercept(ActionInvocation invocation) throws Exception {
      
             
              System.out.println("Finishing execution stack for action //TestLogger");

                     //----------  Un comment this line and you will see the result of the prevention of action
                     //----------  from being executed

                     //if(true) return ERROR;  


                     //----------------------------------------------------------------------------------

              String result = invocation.invoke();
              // Post processing
      
              System.out.println("Finishing execution stack for action //TestLogger");
              return result;
       }

          //called during interceptor destruction
              public void destroy() {
                     System.out.println("CustomInterceptor2 destroy() is called...");
              }
        
              //called during interceptor initialization
              public void init() {
                     System.out.println("CustomInterceptor2 init() is called...");
              }

}

Finally my struts file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
       <package name="default" extends="struts-default">

              <interceptors>
                     <interceptor name="logger"
                           class="MyLoggingInterceptor">
                     </interceptor>

                     <interceptor-stack name="loggingStack">
                           <interceptor-ref name="logger" />
                           <interceptor-ref name="defaultStack" />
                     </interceptor-stack>

              </interceptors>

              <action name="TestLogger" class=" TestLoggerAction">
                     <interceptor-ref name="loggingStack" />
                     <result name="error">/InterceptorFailure.jsp</result>
                     <result name="success">/InterceptorSuccess.jsp</result>
              </action>

       </package>
</struts>
             
Be very very precise with the characters you type in. Case sensitivity is hell lot of issue for me. L

You will get the following page if you un comment the block of code I have indicated in the interceptor class



And the following line page if you proceed as such



And your console would contain the following info


Hope this helps  :)

Working with s:bean in Struts 2 - Beware Begineers


Well well... this simple silly stuff gave me a head ache for a while. Because I broke the rules and so paid the price.
I was wondering why s:bean won’t work for me while I was able to work with other stuffs like controls, context params, stream processing, Ajax etc….
My Eclipse IDE kept telling that it was not able to recognize what s:bean is. Neither did it realize s:param and s:property.

I was puzzled. Even a few java guys felt that it was a problem with the IDE. How demoralizing. I stopped toying with it for a while and later after a couple of days, I found the culprit.

It was so simple. I got a bit comfortable with basic JSPs and Struts that I did not notice this.

The following was my jsp page’s content

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bean Tag Example</title>
</head>
<body>
<s:bean name="currencyConverter">
 <s:param name="dollars" value="100" />
 100 Dollars = <s:property value="rupees" /> Rupees
</s:bean>

</body>
</html>

And the issue was I did not add the following code to the top of that page

<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>

God bless me…. I just want to cry now. How could I ever forget to miss it … bummer

Hope this saves some one else at least :)

Thursday, November 3, 2011

Configuring Struts.xml for Interceptors

Well learning curve is quite breath taking with java technologies. I got curious about the interceptors feature in Struts 2 and eventually I ended up trying to sample them out for my reference and understanding. I am not yet successful on it, but at least I have had some progress on the same.


The first wall I had to jump over was that whenever I added the interceptors tag in struts.xml, I was having a heap of issues and my page/ project wont load up on the browser.


I searched through out the innernet and all spoke about how to use them and what tags to add and I was so puzzeled that I followed them exactly as per my understanding and it wouldn’t work.


Gosh…. I found the culprit at last. It was the way in which these  tags needs to be ordered in the xml file.


The interceptors tag needs to be present on top of all other action tags. So much to my observation !!!!!  It was always there and yet it took me an hour to find it. L So much to experience with the RAD technology I am associated with, for the past 4 yrs… I never had to think about these silly stuffs


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
             
       <package name="default" extends="struts-default">
             
             
              <interceptors>
                     <interceptor name="logger" class="interceptor.MyLoggingInterceptor">
                     </interceptor>
                     <interceptor-stack name="loggingStack">
                           <interceptor-ref name="logger" />
                           <interceptor-ref name="defaultStack" />
                     </interceptor-stack>
                    
              </interceptors>           
             
              <!-- <constant name="struts.devMode" value="true" /> -->
             
              <action name….>
                     <result ….">/index.jsp</result>
              </action>

              <action name….>
                     <result ….>
                           ……
                     </result>
              </action>

              <action name="TestLogger" class="TestLoggerAction">
                     <interceptor-ref name="loggingStack" />
                     <result name="success">/InterceptorSuccess.jsp</result>
              </action>
             
       </package>   
</struts>
             
       Hope this xml interpretation gives you an idea of how to configure em…

Hope this helps some one J
      

Tuesday, November 1, 2011

Ajax in Strut 2 using XmlHTTPRequest


Ajax with Struts 2, I think I have had a good start with Struts 2. I was just toying around with what was provided in vaannila. It’s a real good stuff and in no time I got this idea of trying AJAX with Struts 2.


It took me some time though to understand how stuffs work with Struts.


Following is the fragment of struts.xml file that did the trick for me at last


            <action name="AjaxTest"  class="AjaxTest">
                     <result type="stream">
                           <param name="contentType">text/html</param>
                           <param name="inputName">inputStream</param>
                     </result>
              </action>


The class I Used to output the response is as follows


import java.io.InputStream;
import java.io.StringBufferInputStream;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("deprecation")
public class AjaxTest extends ActionSupport  {
    private InputStream inputStream;
    public InputStream getInputStream() {
        return inputStream;
    }

    public String execute() throws Exception {
        inputStream = new StringBufferInputStream("Hello World! This is a text string response from a Struts 2 Action.");
        return SUCCESS;
    }
}


The javascript I used to perform the AjaxRequest is as follows
function triggerAjaxForExperiment()      {
       xmlHttp=new AjaxProcess("http://localhost:8080/myNewHelloWorld/AjaxTest.action",false);
       //initiate and asynchronous request to check whether the current reporthas any open chid documents
       xmlHttp.initiate();

       //this results in a boolean object isChildActive which is either true or false
       alert(xmlHttp.getHtmlFilteredResponseText())
}

About the AjaxProcess function that I have used here, it is a custom API I have created and can be found in the following location

And to your jsp file add the following line of html code to perform the test

       <input type="button" value="Ajax Experiment" onclick="triggerAjaxForExperiment()"/>

In the end what I got was as follows

It feels good to me J

Hope this helps you as well J

Monday, October 31, 2011

Hello world – Struts 2

It took awe fully a lot of time for me to do this simple stuff as I was not too comfortable with JSP, tomcat and eclipse Indigo. Though I followed most of the hello world tutorials available out there, I always ended up with some errors or the other.

Some of the important lessons that I have learnt with this sufferings are,

1.       Java frameworks are not reverse compatible. I hate that.

2.       Code developed with say jdk1.5 environment probably won't work with jdk1.6 and vice versa

3.       Only use prescribed files by all means and do not try including any new stuffs before u know what it is as far as the java technology is concerned.

Since I come from a technology which is RAD and reverse compatibility is never an issue, IT IS REALLY HARD FOR ME TO DIGEST ABOUT THIS IN JAVA WORLD L   

Any ways I am starting to getting used to this and here is my hello world to Struts 2.

Prerequisites,

1.       Tomcat server version 6.0 or 6.0.33 needs to be installed. No other versions. Probably other versions in 6 might support but I am not sure

2.       JDK 1.5 is required. Don't switch to higher version or u might end up having a tough time finding what the problem is. Well if you are a java guy, you would know it better than me.

Following is the folder structure that you need to have

The lib directory should contain all of the following files

         

 

All the files that you find in the above screen shot are frame work files that comes with Struts 2 package version 2.1.2 I guess. You can google down with the names of the files to find the appropriate sub version of struts 2. Believe me it did not work with version 2.1.6.

Please don't blame me if you can do it better. I am very new to this technology J

Key in the following code to HelloWorldAction class

You web.xml file should have the following code

The popup text that you find in the above image shows the filter class that helps your web.xml file understand the presence of struts.xml file.

Following is how my struts.xml file looks like.

 

The action name "helloworldAction" can be any name of your choice.

The class name "web.HelloworldAction"  tells the compiler to look into this specific class to execute the specific method

The method name "helloWorld" asks the compiler to look for this particular method and perform the necessary action inside the provided class in the class name parameter

Finally the index.jsp is as follows

Now save your work, move your project to the tomcat server, by doing the following

After doing this click finish.

 

Now restart your tomcat server or simply start it if its not already running.

Now key in the following url in your browser. I did this one with the browser provided by eclipse it self

http://localhost:8080/HelloWorld/

http://localhost:8080/HelloWorld/helloworldAction.action

Note the differences in the above mentioned images,

When you provide the url for helloworldAction class directly you can see the print statements provided inside the helloWorld method in the console. Possibly you can use this one to your advantage

Hope this helps J

Saturday, October 29, 2011

Configuring ODBC Connection for Oracle in Windows 7

1. In order to configure a ODBC connection for Oracle in windows 7 follow the following steps

2. Goto Start->Control Panel->Administrative Tools->Data Sources (ODBC)

3. The following screen titled “ODBC Data Source Administrator” will be opened up


4. Now choose the System DSN tab and click on add.

5. This will open up a new window titled “Create New Data Source”

6. Scroll down to “Microsoft ODBC for Oracle” and click Finish



7. This will result in the following window. Provide the credentials as required and click ok

About TNSNames.ora

This is in continuation to my previous article where I mentioned about TNSNames.ora.
Again this is my understanding and am a beginner1. The Location where you would find tnsnames.ora file inside a oracle client directory is typically inside the NETWORK\ADMIN folder

2. In My case it is inside d:\oracle\product\11.2.0\client_1\NETWORK\ADMIN

3. This is one file that you should know to create if you want to create connections in SQL Developer client to databases in sever.

4. A sample copy of tnsnames.ora file will be available in the SAMPLE Directory. When in doubt copy paste it and make necessary modification to it



5. The various elements that should be understood in this file are as follows