Friday 5 December 2014

Building your own interceptor


I am going to explain step by step. I am going to develop a timer interceptor, which is used to calculate total time taken to process this request. We use the same example “simple form which takes a number from user, and displays success message if it is even number, else failure message”

numCheck.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>Simple struts2 Application</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <body>
      <form method="post" action="check">
          Enter a Number<input type="text" name="number" /><br />
          <input type="submit" value="submit" />
      </form>
  </body>
</html>


NumberCheckAction.java
public class NumberCheckAction {
    private int number;    
    private static String SUCCESS = "success";
    private static String FAILURE = "failure";

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String execute(){
        if(getNumber() %2 == 0){
            return SUCCESS;
        }
        else{
            return FAILURE;
        }
    }
}


success.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Success Page</title>
    </head>
    <body>
        <h1>Hurray you entered even number</h1>
    </body>
</html>


failure.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Failure page</title>
    </head>
    <body>
        <h1>Sorry, you entered odd number</h1>
    </body>
</html>


How to add custom interceptor to NumberCheckAction class

Step 1: To create custom interceptor, you must implement ‘com.opensymphony.xwork2.interceptor.Interceptor’ interface.

public interface Interceptor extends Serializable {
    public void destroy();
    public void init();
    public String intercept(ActionInvocation ai) throws Exception;
}


Init and destroy are life cycle methods, you can perform initialize and clean up operations in these methods. Real task of interceptor happened in intercept method. 

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

public class Timer implements Interceptor{

    @Override
    public void destroy() {
        throw new UnsupportedOperationException("Timer destroyed");
    }

    @Override
    public void init() {
        throw new UnsupportedOperationException("Timer initialized");
    }

    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        long time1 = System.currentTimeMillis();
         String result = ai.invoke();
        long time2 = System.currentTimeMillis();

        System.out.println("Time taken is " +(time2-time1));
        return result;
    }
}


ai.invoke()
In the interceptor intercept() method, you must call the ai.invoke()and return it’s result. This is the method responsible for calling the next interceptor or the action. The action will failed to continue without calling the ai.invoke()method.
 
Step 2: configure struts.xml class

<!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" namespace="/" extends="struts-default">

    <interceptors>
  <interceptor name="timerCheck" class="Timer"></interceptor>

         <interceptor-stack name="newStack">
        <interceptor-ref name="timerCheck"/>
    <interceptor-ref name="defaultStack"/>
          </interceptor-stack>

    </interceptors>

    <action name="check" class="NumberCheckAction" >
  <interceptor-ref name="newStack"/>
  <result name="success">success.jsp</result>
        <result name="failure">failure.jsp</result>
     </action>

   </package>
</struts>


Run numCheck.html, you can get below messages in server console.

INFO: Timer initialized
INFO: Time taken is 2010

 

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment