Tuesday, 7 April 2015

How to create Action Filter in Liferay

How to create Action Filter in Liferay

1) Create a filter class inside portlet

    Here is the sample code for the ActionFilter
   
    package com.test;

    import java.io.IOException;    
    import javax.portlet.ActionRequest;
    import javax.portlet.ActionResponse;
    import javax.portlet.PortletException;
    import javax.portlet.filter.ActionFilter;
    import javax.portlet.filter.FilterChain;
    import javax.portlet.filter.FilterConfig;
    
    public class ActionTestFilter implements ActionFilter {
    
    public void init(FilterConfig arg0) throws PortletException {
    System.out.println("Hey I am in init method of filter");
    }
    
    public void doFilter(ActionRequest arg0, ActionResponse arg1,
    FilterChain arg2) throws IOException, PortletException {
    System.out.println("Hey I am in doFilter");
    }
    
    @Override
    public void destroy() {
    System.out.println("Hey I am in destroy method of filter");
    }
    
    }
   
So far, we have decided what action needs to be performed before "init" , "destroy" and  "processAction" method gets called of a portlet.

2) Use portlet.xml file to specify for which portlet we need to call above filter
    (It is possible that in one war we might have created more than one portlet)

3) Below entries need to be added after <portlet> tag inside "portlet.xml" file  
    <filter>
<filter-name>Action</filter-name>
<filter-class>com.test.ActionTestFilter</filter-class>
<lifecycle>ACTION_PHASE</lifecycle>
</filter>

<filter-mapping>
<filter-name>Action</filter-name>
<portlet-name>*</portlet-name>
</filter-mapping>

4) We have configured "*" inside "<portlet-name>*</portlet-name>" which means filter will be called across all the portlet available in same war file.

Thats it! Custom filter is configured.

Now, Lets test it.

1) Deploy portlet and you will see below message inside log file

    Hey I am in init method of filter

2) Call processAction method and you will see below message inside log file.

    Hey I am in doFilter
   
3) Undeploy portlet and you will see below message inside log file

    Hey I am in destroy method of filter
   
Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics     

No comments:

Post a Comment