Jul 22, 2009

Using hibernate and struts together

    This article is to use hibernate with struts. As when we use hibernate, we have to set values of all fields externally. If we use struts with hibernate then all the values are set by struts. So it helps decreasing the number of lines of code. As well struts also helps in organizing the application

(1)    Configure the struts configuration in web.xml. If you don't know how to do so then first read a little about struts. At: Struts Action Example

(2)    In struts-config.xml define the action and form.
        e.g.
        <!-- ========== Form Bean Definitions ================= -->
        <form-beans>
            <form-bean name="User" type="com.persistence.UserVO"/>
        </form-beans>

        <!-- ========== Action Mapping Definitions ============ -->
    <action-mappings>
            <action path="/user" type="com.control.UserController" name="User" input="/home.jsp">
                <forward name="success" path="/home.jsp"/>
                <forward name="failure" path="/room.jsp"/>
            </action>

        </action-mappings>

(3)    Now create bean class as per the requirement the database as well HTML form. E.g.
        import org.apache.struts.action.ActionForm;

        public class UserVO extends ActionForm {
            private int id;
            private String userName;
            private String userPassword;
            private String userFirstName;
            private String userLastName;
            private String userEmail;

            // ----- getter and setter methods for all fields
        }

        But keep one thing clear that the fields of bean class must have same name as the fields of HTML form you submit from. Here I created this class as my HTML form is as like below.

        <form action="user.do" method="post"><br />
            Name:<input type="text" name="username" /> <br />
            Password:<input type="password" name="userPassword" /> <br />
            First name:<input type="text" name="userFirstName" /> <br />
            Last name:<input type="text" name="userLastName" /> <br />
            E-mail:<input type="text" name="userEmail" />
            <input type="submit">
        </form>

(4)    Now configure hibernate configuration files. First of all create hibernate.cfg.xml file as per your requirements. If you don't know how to create then please read about hibernate first. Hibernate tutorial

        Then after create *.hbn.xml file to map bean class with database table (here * in the name means you can give name as per your choice). As below

        <hibernate-mapping>
            <class name="com.persistence.UserVO" table="contact">
                <id column="USER_ID" name="id" type="int">
                    <generator class="native" />
                </id>
            <property column="USER_NAME" name="userName" type="java.lang.String" />
            <property column="USER_PASSWORD" name="userPassword" type="java.lang.String" />
            <property column="USER_FIRST_NAME" name="userFirstName" type="java.lang.String" />
            <property column="USER_LAST_NAME" name="userLastName" type="java.lang.String" />
            <property column="USER_EMAIL" name="userEmail" type="java.lang.String" />
        </class>
        </hibernate-mapping>

        PLEASE NOTE:
            This is main part where you have to take enough care. In class tag value of attribute name must be equal to the value of attribute type in tag form-bean.
            As well in id and property tags column name must contain the name of column of your table and name tag must contain the value you define in bean class.

(5)    Now define the class extending Action class of struts' action class as below.

        public class UserController extends Action {
            public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){
                try {
                    UserVO user = (UserVO)form;

                    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
                    Session session = sessionFactory.getCurrentSession();
                    Transaction t = session.beginTransaction();
                    session.saveOrUpdate(user);
                    t.commit();

                    return mapping.findForward("success");

                } catch (Exception e) {
                    return mapping.findForward("failure");
                }
            }
        }

May 25, 2009

Struts – Action – Example

    In my earlier post (Struts - What & Why?) I have explained the basic architecture of struts base application. Now I gonna explain you how to create application through struts.

    There is a predefined structure to implement struts in our web application.

(1)    First of all create web.xml. Declare a servlet as below.
e.g.
<servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
    <init-param>
        <param-name>application</param-name>
        <param-value>ApplicationResources</param-value>
    </init-param>
    <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>
<!-- Standard Action Servlet Mapping -->
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

    We are not declaring any controller servlet here. As we are going to use struts. In struts controller servlet are being declared in struts-comfig.xml.

(2)    Create one file struts-config.xml. place this file in WEB-INF directory.
e.g.
<struts-config>

    <!-- Form Bean Definitions -->
    <form-beans>
        <form-bean name="submitForm" type="com.forms.SubmitForm"/>
    </form-beans>

    <!-- Action Mapping Definitions -->
    <action-mappings>
        <action path="/submit" type="com.action.SubmitAction" name="submitForm">
            <forward name="success" path="/index.jsp"/>
            <forward name="failure" path="/submit.jsp"/>
        </action>

    </action-mappings>
        <message-resources parameter="ApplicationResources"/>
    </struts-config>

    Here we declared one action named submitForm. SubmitForm defines path /submit so whenever server request for /submit.do submitForm action will be called.

    forward tag defines that where to forward request after its processing. Here we define submit.jsp for failure. So if request been failed to process then server will forward the request to submit.jsp. As well for success we define index.jsp.

(3)    Now define a class SubmitAction extending org.apache.struts.action.Action class.
As in servlet, we defines a method as doPost or doGet to process. Here define a method execute as in example.
e.g.
public class SubmitAction extends Action {
    public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response){

        /* here we gets object of ActionMapping, ActionForm, HttpServletRequest and HttpResponse.*/

        SubmitForm submitForm = (SubmitForm)form;

        /* if lastName field left blank then procees will be stoped and control will go to submit form again */
        if(submitForm.getLastName()==null)
            return mapping.findForward("failure");

        String lastName = submitForm.getLastName();
        request.setAttribute("lastName", lastName.toUpperCase());

        return mapping.findForward("success");
    }
}

mapping : this object is used to forward request after processing as in example.
form : explain later in this post.

(4)    Now just look at the struts-config.xml, there is tag defined by form-beans. This tag defines the form class. The form class is a simple javabean which contains the fields, we are going to pass through the form from jsp or html. Fields' name must match with the names of the parameter of the request.
e.g.
public class SubmitForm extends ActionForm {
    private String lastName = "";
    private String address = "";

    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
}

    Here parameter passed through the /submit.do request must be lastName and address.

    Whenever one submit the form from submit.jsp all the fields of form class will be set with the values passed in the request. So the object we are getting in action class as argument have all the field filled by the user.

(5)    Now for the testing create one jsp named submit.jsp.
e.g.
<form action="/submit" method="post">
    Last name: <input type="text" name="lastName">
    address:<br/><textarea name="address" rows="2" cols="30"> address</textarea>
</form>

    This is how the whole structure of a struts action implemented. This is a very basic functionality. This may be extend to a large application where more one controller are defined as well as forms.

Apr 21, 2009

Servicemix - HttpConnectorDemo – Example

This post explains how to create a servicemix httpconnector component using spring so if you are not using spring don’t waste your time.

(1) First of all create one configuration file containing component declaration. Put this file in your configuration folder (e.g. WEB-INF).
E.g.
<sm:activationspec componentname=" HttpConnectorDemo" service="foo:MobileHttpBinding">
    <sm:component>
        <bean class="com.component.pollar.MobileHttpBinding">
            <property name="defaultInOut" value="false">
        </property>
        </bean>
    </sm:component>
</sm:activationspec>

(2) Map the configuration file from your web.xml file so that your component takes part in web application.
E.g.
<context-param>
    <param-name>contextConfigLocation
    <param-value>/WEB-INF/applicationContext.xml
</param-value>

Then after to load this component whenever container starts, add following snippet of code to your web.xml.

<context-param>
    <param-name>contextClass</param-name>
    <param-value>
       org.apache.xbean.spring.context.XmlWebApplicationContext
    </param-value>
</context-param>
<listener>
    <listener-class>
       org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

(3) Now make a class file containing implementation of HttpConnector class of servicemix. Add your actual logic to processInOnly method as we have defined that <property name="defaultInOut" value="false"> so a call to this class will go to processInOnly method. Yet for safety define processInOut method and call processInOnly method from there.
E.g.
public class HttpConnectorDemo extends HttpConnector {
    public void processInOnly(HttpServletRequest request, HttpServletResponse response){
        // Your actual logic.
    }
    public void processInOut(HttpServletRequest request, HttpServletResponse response){
        processInOnly(request, response);
    }
}

(4) Now this class can act as a servlet. All we have to do is define a servlet in web.xml and map it to this class.
E. g.
<servlet>
    <servlet-name>MobileServlet</servlet-name>
    <servlet-class>
       org.apache.servicemix.components.http.SpringBindingServlet
    </servlet-class>
    <init-param>
       <param-name>endpoint</param-name>
       <param-value>MobileHttpBinding</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
        <servlet-name>Mobile<servlet-name>
        <url-pattern>/form.do</url-pattern>
</servlet-mapping>

(5) Now the part left is most easy part just make a war file and deploy it in your server. Start your browser, hit the URL and see the picture, your job is done. Just include necessary jar files in lib folder so that server can load your component properly.

Now start making components and Enjoy Servicemix ESB.

Mar 6, 2009

Java - Inner Classes - for SCJP

If anonymous class is created for interface, it extends Object class and implement that interface, if it is created for a class then it extends that class.
Earlier, Non-static inner classes were not allowed to have static fields at all. This rule is now modified and the new rule says that: 'The third paragraph of the section Members that can be marked static is amended to make an exception and allow inner classes to declare static FIINAL fields that are compile time constants as members.'
Ex.:
public class Outer{
class Inner
{
static final int k = 10;
}
}
(Top level classes mean, classes defined in package scope and STATIC inner classes of classes defined in package scope) Consider the anonymous inner class for catching action events:

ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent e)
{
}

};

Here, the anonymous class implicitly extends Object and implements the interface ActionListener. Explicit extends or implements clauses are not allowed for such classes. Other inner class (ie. non anonymous) can have them. Consider the following (although of no use) class:
public class TestClass
{
public TestClass(int i) { }

public void m1()
{

TestClass al = new TestClass(10)

{

public void actionPerformed(ActionEvent e)
{
}

};
}

}
This illustrates 4 points:
  1. Instance Methods can also have inner classes. (But they cannot have static inner classes).

  2. Inner class can extend the outer class.

  3. Anonymous inner class can be created for classes. (Not just for interfaces). They implicitly extend the class.(Here, TestClass)

  4. Anonymous inner class can have initialization parameter. (If the class they extend has a corresponding constrctor).

Non-static inner classes can contain final static fields (but not methods).
Anonymous classes cannot have explict constructors, since they have no names.
A static inner class is also known as A Top Level Nested class. So,there are two types of Top level classes. One, that is a standard class and other an inner class which is static.
Eg.
public class A //This is a standard Top Level class.
{
class X

{

static final int j = 10; //compiles fine!

}

public static class B //This is also a Top Level class (but nested!)

{
}

}
You can create objects of B with having objects of A. Eg. A.B b = new A.B();
Members in outer instances are directly accessible using simple names. There is no restriction that member variables in inner classes must be final.
Nested classes define distinct types from the enclosing class, and the instanceof operator does not take of the outer instance into consideration.

Every non static inner class object has a reference to it's out class object which can be accessed by doing OuterClass.this. So the expression B.this.c will refer to B's c, which is 'a'. Inside a non-static inner class, 'InnerClass.this' is equivalent to 'this'. so 'C.this.c' refers to C's c which is 'c'. The expression super.c will access the variable from A, the superclass of C which is 'd'.

Only classes declared as members of top-level classes can be declared static. Such a member is a top-level nested class if it is declared static, otherwise it is a non-static inner class.
Package member classes, local classes(ie. classes declared in methods) and anonymous classes cannot be declared static.

Mar 2, 2009

Prevent Duplicate Form Submission

Duplicate form submissions can occur in many ways :
  • Using Refresh button
  • Using the browser back button to traverse back and resubmit form
  • Using Browser history feature and re-submit form.
  • Malicious submissions to adversely impact the server or personal gains
  • Clicking more than once on a transaction that take longer than usual
Effect :

Think about a online shopping site, You are buying from a online shopping store. You hava submitted the form by clicking submit button screen comes with "Please wait...." and stays for a long you worried and press submit again what happens the first click submitted first shopping and second click requests for the same order again. And you have to pay for same item twice.

This is only the one case you may be pay twice, there are many others factors which can affects.

Solution :
  1. Disable submit button on first time it is clicked.
    This helps prevent duplicate form submission from user aggresion impatient. But not from the others mentioned above.
    E.g. <input type="submit" name="submit" onclick="this.disabled='true';/*your other function calling*/">

  2. Using Struts :
    1. By forwarding twice :

      The easy solution to this problem is to use HTTP redirect after the form submission. Suppose that the CustomerForm submission results in showing a page called Success.jsp. When HTTP redirect is used, the URL in the URL bar becomes /App1/Success.jsp instead of /App1/submitCustomerForm.do. When the page refreshed, it is the Success.jsp that is loaded again instead of App1/submitCustomerForm.do. Hence the form is not submitted again. To use the HTTP redirect feature, the forward is set as follows:

      <forward name=”success” path=”/Success.jsp” redirect=”true” />

      However there is one catch. With the above setting, the actual JSP name is shown in the URL. Whenever the JSP name appears in the URL bar, it is a candidate for ForwardAction. Hence change the above forward to be as follows:

      <forward name=”success” path=”/GotoSuccess.do” redirect=”true” />

      Where GotoSuccess.do is another action mapping using ForwardAction as follows:

      <action path=”/GotoSuccess” type=”org.apache.struts.actions.ForwardAction” parameter=”/Success.jsp” validate=”false” />

      Now, you have now addressed the duplicate submission due to accidental refreshing by the customer Problem : It does not prevent you from intentionally going back in the browser history and submitting the form again. Malicious users might attempt this if the form submissions benefit them or adversely impact the server.

    2. Synchronizer Token :

      Struts provide a token system which help solving this problem. Steps of implementation :

      1. add follwing line in the first(the page containing form you like to prevent from duplication) page or servlet,

      2. <% String token = TokenProcessor.getInstance().generateToken(request); session.setAttribute("org.apache.struts.action.TOKEN"
        , token); %>
      3. make a hidden field in the form as follow,

      4. <input type="hidden"
        name="<%=.TOKEN_KEY%>"
        value="<%=token%>"/>

      5. Now in the Action class you created, change code as follow,

      6. .... if(isTokenValid(request)){
        // your code if form submitted first time
        } else {
        // your code if form is duplicate.
        }
        saveToken(request);
        .....

Feb 27, 2009

Struts - What & Why?

What is Struts?
Struts is a Java MVC framework for building web applications on the J2EE platform.

How and where Struts fits in the big picture?

Presentation Tier Strategies Technologies used for the presentation tier can be roughly classified into three categories:
• Markup based Rendering (e.g. JSPs)
• Template based Transformation (e.g. XSLT)
• Rich content (e.g. Macromedia Flash)

We will start by introducing the two modes of designing JSPs - Model 1 and Model 2 architectures in the next two sections and then arrive at Struts as an improvement over the Model 2 architecture.

Model 1 Architecture

Let us illustrate the operation of Model 1 architecture with an example. Consider a HTML page with a hyperlink to a JSP. When user clicks on the hyperlink, the JSP is directly invoked. The servlet container parses the JSP and executes the resulting Java servlet. The JSP contains embedded code and tags to access the Model JavaBeans. The Model JavaBeans contains attributes for holding the HTTP request parameters from the query string. In addition it contains logic to connect to the middle tier or directly to the database using JDBC to get the additional data needed to display the page. The JSP is then rendered as HTML using the data in the Model JavaBeans and other Helper classes and tags.

Problems with Model 1 Architecture

• In Model 1 architecture, the presentation logic usually leads to a significant amount of java code embedded in the JSP in the form of scriptlets. This is ugly and maintenance nightmare even for experienced Java developers.

• Application control is decentralized in Model 1 architecture since the next page to be displayed is determined by the logic embedded in the current page. Decentralized navigation control can cause headaches.

Model 2 Architecture - MVC

The main difference between Model 1 and Model 2 is that in Model 2, a controller handles the user request instead of another JSP. The controller is implemented as a servlet.

Advantages of Model 2 Architecture

• Since there is no presentation logic in JSP, there are no scriptlets. This means lesser nightmares.

• With MVC you can have as many controller servlets in your web application. In fact you can have one Controller Servlet per module.

Why do we need Struts? (Controller gone bad – Fat Controller)

If MVC is all that great, why do we need Struts after all? The answer lies in the difficulties associated in applying bare bone MVC to real world complexities. In medium to large applications, centralized control and processing logic in the servlet – the greatest plus of MVC is also its weakness. Consider a mediocre application with 15 JSPs. Assume that each page has five hyperlinks (or five form submissions). The total number of user requests to be handled in the application is 75. Since we are using MVC framework, a centralized controller servlet handles every user request. For each type of incoming request there is “if” block in the doGet method of the controller Servlet to process the request and dispatch to the next view. For this mediocre application of ours, the controller Servlet has 75 if locks. Even if you assume that each if block delegates the request handling to helper classes it is still no good. You can only imagine how bad it gets for a complex enterprise web application. So, we have a problem at hand. The controller Servlet that started out as the greatest thing next to sliced bread has gone bad. It has put on a lot of weight to become a Fat Controller.

First Look at struts

In Struts, there is only one controller servlet for the entire web application. This controller servlet is called ActionServlet and resides in the package org.apache.struts.action. It intercepts every client request and populates an ActionForm from the HTTP request parameters. ActionForm is a normal JavaBeans class. It has several attributes corresponding to the HTTP request parameters and getter, setter methods for those attributes. You have to create your own ActionForm for every HTTP request handled through the Struts framework by extending the org.apache.struts.action.ActionForm class. Consider the following HTTP request for http://localhost:8080/App1/create.do?firstName=John&lastName=Doe. Suppose class MyForm extends the org.apache.struts.action.ActionForm class and contains two attributes – firstName and lastName. It also has getter and setter methods for these attributes. For the lack of better terminology, let us coin a term to describe the classes such as ActionForm – View Data Transfer Object. View Data Transfer Object is an object that holds the data from html page and transfers it around in the web tier framework and application classes.

The ActionServlet then instantiates a Handler. The Handler class name is obtained from an XML file based on the URL path information. This XML file is referred to as Struts configuration file and by default named as struts-config.xml. The Handler is called Action in the Struts terminology. And you guessed it right! This class is created by extending the Action class in org.apache.struts.action package. The Action class is abstract and defines a single method called execute(). You override this method in your own Actions and invoke the business logic in this method. The execute() method returns the name of next view (JSP) to be shown to the user. The ActionServlet forwards to the selected view.