Sunday, 19 February 2012

learn candle stick


bullish engulfing trend


Saturday, 11 February 2012

how to load css files in struts2


I was facing a problem since a very long time. Many a times when a request is made to my website, it doesn't gets properly rendered as if the CSS is not functioning and 3 weeks later I found the bug.
For adding CSS I was doing this :
<link rel="stylesheet" href="<s:url value="/"/>css/style.css" type="text/css">

due to which in case of the first request to my site it was rendered as
<link rel="stylesheet" href="/onlinexamples;jessionid=13241342154797/css/style.css" type="text/css">

As you can see above, due to the presence of jessionid the whole href url goes wrong. And with further subsequent requests, tomcat figured out that the cookies were enabled so it started rendering as
<link rel="stylesheet" href="/onlinexamples/css/style.css" type="text/css">
and hence from second request onwards everything worked fine.

The solution I applied is instead of using <s:url> I used EL's pageContext.request.contextPath as
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css" type="text/css">


Struts2 Jquery SubGrid


Hello,
Are you amazed by the Struts2 Jquery Grid Showcase and trying to implement a Struts2 Jquery SubGrid but unable to figure out whats going wrong. Already spent hours figuring out the solution? Then you are at the right place.
This is a complete working example project in Netbeans 6.9 showcasing Struts2 Jquery SubGrid functionality, simply resolve the references and get going.

Description:

This is the structure of the Netbeans Project


Models- 1. Student (idstudent,name,address,email,phoneno)
               2. StuTrans (idstudent,amount,desc)
As specified Student.java and StuTrans.java depicts the above mentioned structure as a POJO with getters/setters of attributes.

StudentDAO.java

package dao;

import java.util.ArrayList;
import java.util.List;
import model.Student;

public class StudentDAO {

    private static List<Student> stuLst = new ArrayList<Student>();
    static {
        for (int i = 1; i < 30; i++) {
            stuLst.add(new Student(i*10, " name " + i, "address " + i, "email " + i, 999999999 + i));
        }
    }
    public static List<Student> buildList() {
        return stuLst;
    }

    public static int count() {
        return stuLst.size();
    }

    public static List<Student> find(int o, int q) {
        return stuLst.subList(o, q);
    }

    public static void save(Student c) {
        stuLst.add(c);
    }

    public static Student findById(Integer id) {
        for (Student c : stuLst) {
            if (c.getIdstudent() == id) {
                return c;
            }
        }
        return null;
    }

    public static void update(Student c) {
        for (Student x : stuLst) {
            if (x.getIdstudent() == c.getIdstudent()) {
                x.setName(c.getName());
            }
        }
    }

    public static void delete(Student c) {
        for (Student x : stuLst) {
            if (x.getIdstudent() == c.getIdstudent()) {
                stuLst.remove(x);
            }
        }
    }
}

StuTransDAO.java
package dao;

import java.util.ArrayList;
import java.util.List;
import model.StuTrans;

public class StuTransDAO {

    private static List<StuTrans> stuLst = new ArrayList<StuTrans>();

    static {
        for (int i = 1; i < 30; i++) {
            for (int j = 1; j < 5; j++) {
                stuLst.add(new StuTrans(i*10, i * Math.PI + 100, "desc " + i));
            }
        }
    }

    public static List<StuTrans> buildList() {
        return stuLst;
    }

    public static int count() {
        return stuLst.size();
    }

    public static List<StuTrans> find(int o, int q) {
        return stuLst.subList(o, q);
    }

    public static void save(StuTrans c) {
        stuLst.add(c);
    }

    public static List<StuTrans> findById(Integer id) {
        List<StuTrans> temp=new ArrayList<StuTrans>();
        for (StuTrans c : stuLst) {
            if (c.getIdstudent() == id) {
                temp.add(c);
            }
        }
        return temp;
    }

    public static void update(StuTrans c) {
        for (StuTrans x : stuLst) {
            if (x.getIdstudent() == c.getIdstudent()) {
//                x.setName(c.getName());
            }
        }
    }

    public static void delete(StuTrans c) {
        for (StuTrans x : stuLst) {
            if (x.getIdstudent() == c.getIdstudent()) {
                stuLst.remove(x);
            }
        }
    }
}

actTransaction.java & actStudent.java are almost similar in the fashion that their task is to supply JSON to be displayed in the JQGrid. Both of them returns the fore-mentioned POJOs as JSONs.

actStudent.java
package actions;

import com.opensymphony.xwork2.ActionSupport;
import dao.StudentDAO;
import java.util.ArrayList;
import java.util.List;
import model.Student;

public class actStudent extends ActionSupport {// get index row - i.e. user click to sort.

    private String sidx;
    // Search Field
    private String searchField;
    // The Search String
    private String searchString;
    // he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    private String searchOper;
    // Your Total Pages
    private Integer total = 0;
    //Your result List
    private List<Student> gridModel;
    private List<Student> myList;
    //get how many rows we want to have into the grid - rowNum attribute in the grid
    private Integer rows = 0;
    //Get the requested page. By default grid sets this to 1.
    private Integer page = 0;
    // sorting order - asc or desc
    private String sord;
    private boolean loadonce = false;

    public boolean getLoadonce() {
        return loadonce;
    }

    public void setLoadonce(boolean loadonce) {
        this.loadonce = loadonce;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public List<Student> getGridModel() {
        return gridModel;
    }

    public void setGridModel(List<Student> gridModel) {
        this.gridModel = gridModel;
    }

    public Integer getPage() {
        return page;
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRecords() {
        return records;
    }

    public void setRecords(Integer records) {
        this.records = records;
        if (this.records > 0 && this.rows > 0) {
            this.total = (int) Math.ceil((double) this.records / (double) this.rows);
        } else {
            this.total = 0;
        }
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
    // All Record
    private Integer records = 0;

    public String execute() {
        System.out.println("grid action execute called");
        myList = StudentDAO.buildList();
        setRecords(myList.size());

        int to = (getRows() * getPage());
        int from = to - getRows();
        if (to > getRecords()) {
            to = getRecords();
        }

        System.out.println("loadonce : " + loadonce);
        if (loadonce) {
            System.out.println("returned from loadonce");
            setGridModel(myList);
        } else {
            if (searchString != null && searchOper != null) {
                //All searches here....
            } else {
                setGridModel(StudentDAO.find(from, to));
            }
        }
        total = (int) Math.ceil((double) getRecords() / (double) getRows());
        return SUCCESS;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public String getJSON() {
        return execute();
    }
}

actTransaction.java
package actions;

import com.opensymphony.xwork2.ActionSupport;
import dao.StuTransDAO;
import java.util.List;
import model.StuTrans;

public class actTransaction extends ActionSupport {

    private Integer records = 0;
    private Integer id;
    private String sidx;
    // Search Field
    private String searchField;
    // The Search String
    private String searchString;
    // he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
    private String searchOper;
    // Your Total Pages
    private Integer total = 0;
    //Your result List
    private List<StuTrans> gridModel;
    private List<StuTrans> myList;
    //get how many rows we want to have into the grid - rowNum attribute in the grid
    private Integer rows = 0;
    //Get the requested page. By default grid sets this to 1.
    private Integer page = 0;
    // sorting order - asc or desc
    private String sord;
    private boolean loadonce = false;

    public Integer getId() {
        return id;
    }

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

//    public boolean getLoadonce() {
//        return loadonce;
//    }
    public void setLoadonce(boolean loadonce) {
        this.loadonce = loadonce;
    }

    public String getSearchField() {
        return searchField;
    }

    public void setSearchField(String searchField) {
        this.searchField = searchField;
    }

    public String getSearchOper() {
        return searchOper;
    }

    public void setSearchOper(String searchOper) {
        this.searchOper = searchOper;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public List<StuTrans> getGridModel() {
        return gridModel;
    }

    public void setGridModel(List<StuTrans> gridModel) {
        this.gridModel = gridModel;
    }

    public Integer getPage() {
        return page;
    }

    public String getSidx() {
        return sidx;
    }

    public void setSidx(String sidx) {
        this.sidx = sidx;
    }

    public String getSord() {
        return sord;
    }

    public void setSord(String sord) {
        this.sord = sord;
    }

    public void setPage(Integer page) {
        this.page = page;
    }

    public Integer getRecords() {
        return records;
    }

    public void setRecords(Integer records) {
        this.records = records;
        if (this.records > 0 && this.rows > 0) {
            this.total = (int) Math.ceil((double) this.records / (double) this.rows);
        } else {
            this.total = 0;
        }
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }
    // All Record

    public String execute() {
        System.out.println("gridaction actTransaction called");
        int to = rows * page;

        if (id != null) {
            gridModel = StuTransDAO.findById(id);
        }
        records = gridModel.size();
        // Set to = max rows
        if (to > records) {
            to = records;
        }

        // Calculate total Pages
        total = (int) Math.ceil((double) records / (double) rows);

        return SUCCESS;
    }

    public Integer getRows() {
        return rows;
    }

    public void setRows(Integer rows) {
        this.rows = rows;
    }

    public String getJSON() {
        return execute();
    }
}

Now comes the very important struts.xml.
struts.xml
<!Doctype.... tag (as usual)

<struts>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default,json-default">
       
        <action name="ntable" class="actions.actStudent">
            <result name="success" type="json"/>
        </action>

        <action name="nstutrans" class="actions.actTransaction">
            <result name="success" type="json"/>
        </action>

    </package>
</struts>

and following is the code for index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib  prefix="s" uri="/struts-tags" %>
<%@taglib  prefix="sj" uri="/struts-jquery-tags" %>
<%@taglib  prefix="sjg" uri="/struts-jquery-grid-tags" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <sj:head jqueryui="true" jquerytheme="start"/>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Struts2-Jquery SubGrid</title>
    </head>
    <body>
        <s:url  id="remoteurl" action="ntable"/>
        <s:url  id="nremoteurl" action="nstutrans"/>
        <sjg:grid
            id="gridtable"
            caption="Student Entry"
            dataType="json"
            href="%{remoteurl}"
            pager="true"
            gridModel="gridModel"
            rowList="5,10,15,20"
            rowNum="5"
            rownumbers="true"
            >

            <sjg:grid id="nsubgrid"
                      subGridUrl="%{nremoteurl}"
                      gridModel="gridModel"
                      rowNum="-1"
                      footerrow="false"
                      userDataOnFooter="false"
                      >
                <sjg:gridColumn name="idstudent" title="StudentId" sortable="false"/>
                <sjg:gridColumn name="amount" title="Amount" width="100" sortable="false"formatter="number"/>
                <sjg:gridColumn name="desc" title="Description" width="100" sortable="false"/>
            </sjg:grid>

            <sjg:gridColumn name="idstudent" index="idstudent" title="ID" formatter="integer" sortable="false" key="true"/>
            <sjg:gridColumn name="name" index="name" title="Name" sortable="true" editable="false"/>
            <sjg:gridColumn name="address" index="address" title="Address" sortable="true" editable="false"/>
            <sjg:gridColumn name="email" index="email" title="Email" sortable="true" editable="false"/>
            <sjg:gridColumn name="phoneno" index="phoneno" title="Phoneno" sortable="true" editable="false"/>
        </sjg:grid>
    </body>
</html>

Above two lines have been mentioned in bold, first one:         <sj:head jqueryui="true" jquerytheme="start"/> corresponds to the use of Jquery UI
and the second one: <sjg:gridColumn name="idstudent" index="idstudent" title="ID" formatter="integer" sortable="false" key="true"/> specifies that when an element of the outer grid is expanded then the key value(idstudent) is passed as id to the subGridUrl action of the inner action, according to which data is being fetched and returned as JSON in the inner grid. If key is set to false then the usual serial number of the record being selected for expansion(clicking on plus sign) is passed as id. Therefore, in both cases the action which populates the inner grid must have an attribute named id with its corresponding getter and setter.

Download the project.
Hope so this will we be useful to you. Comments are always welcome in case of any kind of problem/issue in the given example.

Struts2 - Nested Iterators


Hey Googler,
Unable to find out a more versatile solution of having a nested iterator in Struts2. Want to know the naming convention to be used in JSP, in case of nested iterator so that it can be submitted through a form ?Here comes the solution.

This is how the JSP code will look like:

        <s:form action="saveaction" >
            <s:iterator value="lstBean" id="lstBean" status="outerStat">
                <s:textfield value="%{name}" name="lstBean[%{#outerStat.index}].name"/>
                <s:textfield value="%{amt}" name="lstBean[%{#outerStat.index}].amt"/>
                <s:textfield value="%{id}" name="lstBean[%{#outerStat.index}].id"/>
                <s:iterator value="%{lstString}" status="myStat">
                    <s:textfield name="lstBean[%{#outerStat.index}].lstString[%{#myStat.index}]"/>
                </s:iterator>
            </s:iterator>
            <s:submit value="Click me to submit lstBean"/>
        </s:form>

Following is the bean(XBean) whose List is used in the JSP:

public class XBean
{
    private ArrayList<String> lstString=new ArrayList<String>();
    private String name;
    private Double amt;
    private Integer id;
      //Getters and setters of fields
}

Now you can simply have a field lstBean with setters in your submitting action (saveaction) and hey you are done!!!!

Download an example project. (Netbeans 6.9 project)


Want to have a very basic JTree example, then you are at the right place.

Example 1
Code:

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;

public class SimpleJTree
{
    public static void main(String[] args) {
      
        JFrame frame = new JFrame();

        DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Color", true);
        DefaultMutableTreeNode black = new DefaultMutableTreeNode("Black");
        DefaultMutableTreeNode blue = new DefaultMutableTreeNode("Blue");
        DefaultMutableTreeNode nBlue = new DefaultMutableTreeNode("Navy Blue");
        DefaultMutableTreeNode dBlue = new DefaultMutableTreeNode("Dark Blue");
        DefaultMutableTreeNode green = new DefaultMutableTreeNode("Green");
        DefaultMutableTreeNode white = new DefaultMutableTreeNode("White");

        DefaultMutableTreeNode adsf=new DefaultMutableTreeNode();

        parent.add(black);
        parent.add(blue);

        blue.add(nBlue);
        blue.add(dBlue);

        parent.add(green);
        parent.add(white);

        JTree tree = new JTree(parent);
        frame.add(tree);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setVisible(true);
    }
}


Download : SimpleJTree.java

Description: 
The program is self explanatory in itself. One can use a IDE say Netbeans to explore the full feature of various methods and constructors used in the program. Here the Tree is hard-coded, required to make up the basics.




Example 2
Code:

import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;


public class AdvancedJTree
{
    public static void main(String[] args)
    {
        JFileChooser fchoose=new JFileChooser();
        fchoose.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fchoose.showOpenDialog(fchoose);

        File f=fchoose.getSelectedFile();
        //File f=new File(".");
//        System.out.println(f.getParentFile());
      
//        JTree tr=new JTree(createTree(f.getParentFile()));
        JTree tr=new JTree(createTree(f));
        JScrollPane scp=new JScrollPane(tr);

        JFrame frame=new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,400);
        frame.add(scp);
        frame.setVisible(true);

    }
  
    public static DefaultMutableTreeNode createTree(File fil)
    {
        DefaultMutableTreeNode root=new DefaultMutableTreeNode(fil.getName(), true);

        String []list;
        DefaultMutableTreeNode temp;

        if(fil.isDirectory())
        {
            list=fil.list();
            if(list==null){ return root;    }
          
//            System.out.println("Files in Directory");
            for(String s:list){
                System.out.println(s);
            }

//            System.out.println("Files in Directory End");
          
            int index=0;

            while(index<list.length)
            {
                File tempFile=new File(fil.getPath()+fil.separatorChar+list[index]);

                if(tempFile.isFile()){
                    temp=new DefaultMutableTreeNode(tempFile.getName());
                    root.add(temp);
                }
                else {
                    temp=createTree(tempFile);
                    root.add(temp);
                }
                index++;
            }
        }
        return root;
    }
}


Download : AdvancedJTree.java

Description:
This is an advanced version of the previous program. Here the Tree is built dynamically by selecting any folder of your choice at the time of startup of this program. Since at the startup an Open Dialog is shown, to select a particular folder whose Tree will be built dynamically. The Tree is built recursively. The technique used is such that, traverse every file in a folder and add it to Tree, but if the file is itself a folder, call the function recursively.

Swing - LAN Chat Application


Hi friends,

Are you looking for a simple GUI based LAN chat application ?
Here's the solution :



Description:
This rar comprises of two .java files which are namely ClientOne.java and ClientTwo.java. These .java files can be run simultaneously on the same machine. Both the files are similar in coding excepting listening and sending ports. In order to understand the basics of JavaSockets for chatting, this application is must. It forms the basics of GUI and Java UDP Socket Programming. Hope you will like this program.
In case of any query, comments are welcome.



Description:
This rar comprises of a single .java file which is namely NChat.java. Simply copy this program to the machines in your LAN. Now run the program on different machines, you will find a better GUI and better chatting functionality with little automation. This forms the basics of Advanced Chat Application and better Java UDP Socket use. Hope you will like this.
In case of any query, comments are welcome.

Struts2 Jquery Grid


Working on Struts2 Jquery grid plugin ?
Unable to find out what's going wrong?
Have u spend more than 72 hours, but still unable to find a solution ?
Then u found the right place.

Following is the list of working Netbeans 6.9 projects, taking you from novoice to professional using Struts2 Jquery Grid.
All you need to do is to resolve the references and get going.

Struts2 - Iterator over an array/list of objects/beans


Well it seems you have googled almost everything you can, but still unable to find out the answer to

How to Iterate over an array objects using Struts2 Iterator and also how to recreate the List on submission of form ?

Then here you go now.
Here is a working example project on Netbeans 6.9, all you need to do is to resolve references and get going.

And believe me, you'll not be disappointed.

Struts2 Tiles2 Integration


Here is a working Netbeans6.9 Project, showing you the integration of Struts2 with Tiles2.

So you will be able to find out what to write in struts.xml,tiles.xml and where to place each and every file.
This example covers the very basics of Struts2 Tiles2 Integration.
This project is actually the realization of the most commonly found example on Internet, so that a beginner can get it quickly.

Struts2 Login filter




Trying to secure your Struts2 web application and googling gives only information in chunks. A single person/blog/site doesn't explain all required things. Moreover, if you are a Netbeans user and unable to understand the hierarchy given in examples in Eclipse? Then this particular post may be of very use to you. I am posting my experience so that people like me may benefit from it in the future and save hours of time.

To implement URL Filter you need to make the following changes in web.xml

web.xml
     <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
    <filter>
        <filter-name>URLFilter</filter-name>
        <filter-class>MyFilter</filter-class>
        <init-param>
            <param-name>onError</param-name>
            <param-value>/login.jsp</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>URLFilter</filter-name>
        <url-pattern>/admin/*</url-pattern>
    </filter-mapping>
                                       //other tags here      

As you can see apart from normal Struts2 filter, now we have a custom filter defined by the name URLFilter and this filter applies to all URLs consisting of "admin/xyz.jsp" in the URL.


As is clear from above the class MyFilter corresponds to URLFilter filter and here is the code:

MyFilter.java              
import com.opensymphony.xwork2.ActionContext;
import java.io.IOException;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFilter implements Filter {

    private String errorURL;

    public void init(FilterConfig filterConfig) throws ServletException {
        errorURL = filterConfig.getInitParameter("onError");
        if (errorURL == null) {
            errorURL = "/login.jsp";
        }
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Map session = ActionContext.getContext().getSession();
        if (session.containsKey("login")) {
            chain.doFilter(request, response);
        } else {
            request.setAttribute("errorMsg", "Authentication required");
            request.getRequestDispatcher(errorURL).forward(request, response);
        }
    }

    public void destroy() {
//        throw new UnsupportedOperationException("Not supported yet.");
    }
}
The above code can easily be searched out using Google. Above I have simply extended the Filter interface and provided very basic implementation of its methods.


This image shows the structure of the project in Netbeans.

adminpage.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello Admin!</h1>
        <s:a href="../index.jsp">HOME</s:a>
    </body>
</html>

index.jsp
        <s:if test="#session['login']!=null">
            <!--<s:property value="#session['login']"/>-->
            <s:url id="logout" action="logoutaction"/>
            <s:a href="%{logout}">Logout</s:a>
        </s:if>
        <s:else>
            <s:a href="login.jsp">Login</s:a>
        </s:else>
        <s:a href="admin/adminpage.jsp">Admin Page</s:a>

login.jsp
         <s:if test="#request['errorMsg']!=null">
            <s:property value="#request['errorMsg']"/>
        </s:if>

        <s:actionerror/>
        <s:fielderror/>
       
        <s:form action="loginaction" method="post">
            <s:textfield name="username" label="Username" />
            <s:password name="password" label="Password"/>
            <s:submit value="submit"/>
        </s:form>

struts.xml
<struts>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default" namespace="">

        <action name="loginaction" class="actions.MyAction">
            <result name="success">index.jsp</result>
            <result name="error">login.jsp</result>
            <result name="input">login.jsp</result>
        </action>

        <action name="logoutaction" class="actions.MyAction" method="logout">
            <result name="success" type="redirect">index.jsp</result>
        </action>
    </package>
</struts>

 Now the only file left is
MyAction.java
package actions;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;

public class MyAction extends ActionSupport {

    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String execute() {
        if (username.equalsIgnoreCase(password)) {
            Map sess = ActionContext.getContext().getSession();
            sess.put("login", true);
            return SUCCESS;
        }
        addActionError("Invalid username/password");
        return INPUT;
    }

    public String logout() {
        Map sess = ActionContext.getContext().getSession();
        sess.remove("login");
        return SUCCESS;

    }
}

Download this project.

So this is the way how we can implement URL Filters in Struts2. Hope so you enjoyed reading.
Let me know if you face problems in the given code. Comments are always welcome.