Monday, 13 July 2015

How to use ServletRequestAttributeListener in Java EE

In dynamic web application if we want to keep track or we want to do some operation like log the attribute which is being added, replaced, deleted then we can
use "ServletRequestAttributeListener". In short web application receives notification as and when any operation is done on the attribute of a ServletRequest.

"ServletRequestAttributeListener" has below three methods which will be triggered at the time of attribute added, replaced and deleted respectively from and to "ServletRequest".

1) public void attributeAdded(ServletRequestAttributeEvent arg0)
2) public void attributeRemoved(ServletRequestAttributeEvent arg0)
3) public void attributeReplaced(ServletRequestAttributeEvent arg0)

Here are the steps to implement "ServletRequestAttributeListener"

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "ServletRequestAttributeListener"
3) Run and Verify

Lets see the steps in detailed:

1) Modify web.xml (deployment descriptor) file to add listener

web.xml file will be read / looked upon by the container while loading any of the project. To inform container about "ServletRequestAttributeListener" we need to add below
lines in it:

 <listener>
  <listener-class>com.listener.ServletRequestAttributeListener</listener-class>
 </listener>

Here we assume that we have created a class with the name "MyServletRequestAttributeListener" which implements "ServletRequestAttributeListener"

2) Add a class which implements "ServletRequestAttributeListener"

Here is the code snippet for the  quick reference:

public class MyServletRequestAttributeListener implements ServletRequestAttributeListener {

    public MyServletRequestAttributeListener() {
    }

    public void attributeAdded(ServletRequestAttributeEvent arg0) {
    System.out.println("Attribute Added in Request (Name -> " + arg0.getName() + ", Value ->" + arg0.getValue() + ")");
    }

    public void attributeRemoved(ServletRequestAttributeEvent arg0) {
    System.out.println("Attribute Removed in Request (Name -> " + arg0.getName() + ", Value ->" + arg0.getValue() + ")");
    }

    public void attributeReplaced(ServletRequestAttributeEvent arg0) {
    System.out.println("Attribute Replaced in Request (Name -> " + arg0.getName() + ", Value ->" + arg0.getValue() + ")");
    }
}

As we can see there are three methods "attributeAdded","attributeReplaced" and "attributeRemoved" which will be called at the time of attribute being added,replaced,removed
from and to the Request scope.


3) Run and Verify

To verify same lets create a dummy servlet called "StoreInstitute" which has a below "doGet" method.

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 request.setAttribute("institute", "ABC"); //Line #1
 request.setAttribute("address", "India"); //Line #2
 request.setAttribute("institute", "XYZ"); //Line #3
 request.removeAttribute("address"); //Line #4
 }

Now to verify our listener, we need to call our "StoreInstitute" servlet in which we have done operation on the attribute of the "HttpServletRequest".
In "StoreInstitute", Line #1 & #2 adds an attribute. Line #3 replaces attribute added in Line #1. Line #4 removes attribute.

When "doGet" method of the "StoreInstitute" servlet gets called then inside log we can see below entries:

Jul 14, 2015 6:24:21 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 312 ms
Attribute Added in Request (Name -> institute, Value ->ABC)
Attribute Added in Request (Name -> address, Value ->India)
Attribute Replaced in Request (Name -> institute, Value ->ABC)
Attribute Removed in Request (Name -> address, Value ->India)


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics 

Sunday, 12 July 2015

When to use ServletRequestListener in java

In a dynamic web application if we want to track when any request is initialized or destroyed then "ServletRequestListener" listener we need to use.

"ServletRequestListener" has below two methods which will be triggered at the time of request is destroyed and request is initialized.

1) public void requestDestroyed(ServletRequestEvent arg0)
2) public void requestInitialized(ServletRequestEvent arg0)

Here are the steps to implement "ServletRequestListener"

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "ServletRequestListener"
3) Run and Verify

Lets see the steps in detailed:

1) Modify web.xml (deployment descriptor) file to add listener

web.xml file will be read / looked upon by the container while loading any of the project. To inform container about "ServletRequestListener" we need to add below
lines in it:

<listener>
<listener-class>com.listener.ServletRequestListener</listener-class>
</listener>

Here we assume that we have created a class with the name "MyServletRequestListener" which implements "ServletRequestListener"

2) Add a class which implements "ServletRequestListener"

Here is the code snippet for the  quick reference:

public class MyServletRequestListener implements ServletRequestListener {

    public MyServletRequestListener() {
    }

    public void requestDestroyed(ServletRequestEvent arg0) {
        System.out.println("Hey request is destroyed " + arg0.getServletContext().getAttribute("studentLocation"));
System.out.println("Hey request is destroyed " + arg0.getServletRequest().getParameter("institute"));
    }

    public void requestInitialized(ServletRequestEvent arg0) {
        System.out.println("Hey request is initialized" + arg0.getServletRequest().getParameter("institute"));
        arg0.getServletContext().setAttribute("studentLocation ", "India");
    }
}


As we can see there are two methods "requestDestroyed" and "requestInitialized" which will be called at the time of servlet request gets destroyed and servlet request
is initialized respectively.

3) Run and Verify

To verify same lets create a dummy servlet called "FetchStudentData" which has a below "doGet" method.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().print(getServletContext().getAttribute("institute"));
}

Now to verify our listener, we need to call our "FetchStudentData" servlet in which we have read the value of the "institute" which is passed in the Url.

Here is the log we can see while calling Url : http://localhost:8080/student/FetchStudentData?institute=Australia

Hey request is initialized Australia //Line #1
Hey request is destroyed India //Line #2
Hey request is destroyed Australia //Line #3

We can see that

Line #1 prints the value of "institute" which we have passed in the Url as by that time request was initialized. (Via "requestInitialized" method of the listener)

Line #2 prints the value of the "studentLocation" which is stored in the "ServletContext" (During "requestInitialized" method in a listener).

Line #3 prints the value of the request parameter "institute". (Via "requestDestroyed" method of the listener).

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Saturday, 11 July 2015

When to use ServletContextAttributeListener in java

In dynamic web application when we want to share data among servlet then we need to take help of "ApplicationContext" scope. Every servlet can get the object of "ServletContext"
and store data in it for other servlet to leverage it. If we want to keep track or we want to do some operation like log the attribute which is being added, replaced, deleted then we can
use "ServletContextAttributeListener".

"ServletContextAttributeListener" has below three methods which will be triggered at the time of attribute added, replaced and deleted respectively from and to "ServletContext" scope.

1) public void attributeAdded(ServletContextAttributeEvent arg0)
2) public void attributeReplaced(ServletContextAttributeEvent arg0)
3) public void attributeRemoved(ServletContextAttributeEvent arg0)


Here are the steps to implement "ServletContextAttributeListener"

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "ServletContextAttributeListener"
3) Run and Verify

Lets see the steps in detailed:

1) Modify web.xml (deployment descriptor) file to add listener

web.xml file will be read / looked upon by the container while loading any of the project. To inform container about "ServletContextAttributeListener" we need to add below
lines in it:

<listener>
<listener-class>com.listener.ApplicationContextAttributeListener</listener-class>
</listener>

Here we assume that we have created a class with the name "ApplicationContextAttributeListener" which implements "ServletContextAttributeListener"

2) Add a class which implements "ServletContextAttributeListener"

Here is the code snippet for the  quick reference:

public class ApplicationContextAttributeListener implements ServletContextAttributeListener {

    /**
     * Default constructor. 
     */
    public ApplicationContextAttributeListener() {
        // TODO Auto-generated constructor stub
    }

    public void attributeAdded(ServletContextAttributeEvent arg0) {
    System.out.println("Attribute Added in Context (Name -> " + arg0.getName() + ", Value ->" + arg0.getValue() + ")");
    }

    public void attributeReplaced(ServletContextAttributeEvent arg0) {
    System.out.println("Attribute Replaced in Context (Name -> " + arg0.getName() + ", Value ->" + arg0.getValue() + ")");
    }

    public void attributeRemoved(ServletContextAttributeEvent arg0) {
    System.out.println("Attribute Removed in Context (Name -> " + arg0.getName() + ", Value ->" + arg0.getValue() + ")");
    }
}

As we can see there are three methods "attributeAdded","attributeReplaced" and "attributeRemoved" which will be called at the time of attribute being added,replaced,removed
from and to the ServletContext scope.


3) Run and Verify

To verify same lets create a dummy servlet called "StoreStudentData" which has a below "doGet" method.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
getServletContext().setAttribute("institute", "ABC"); //Line #1
getServletContext().setAttribute("address", "India"); //Line #2
getServletContext().setAttribute("institute", "XYZ"); //Line #3
getServletConfig().getServletContext().removeAttribute("address"); //Line #4
}

Now to verify our listener, we need to call our "StoreStudnetData" servlet in which we have done operation on the attribute of the "ServletContext".
In "StoreStudentData", Line #1 & #2 adds an attribute. Line #3 replaces attribute added in Line #1. Line #4 removes attribute.

When "doGet" method of the "StoreStudentData" servlet gets called then inside log we can see below entries:

Jul 10, 2015 6:24:21 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 312 ms
Attribute Added in Context (Name -> institute, Value ->ABC)
Attribute Added in Context (Name -> address, Value ->India)
Attribute Replaced in Context (Name -> institute, Value ->ABC)
Attribute Removed in Context (Name -> address, Value ->India)


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

How to use ApplicationContextListener in java

Every application deployed on the server has its own lifecycle. Which is known as ApplicationContext Lifecycle.

Application Context has two events / phases in a lifecycle,here are the main events of it:

1) context initialized
2) context destroyed

If we want to perform any action while context is initialized or context is destroyed then we can use "ServletContextListener".

To implement same here are the steps needs to be performed:

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "ServletContextListener"
3) Run and Verify

Lets see the steps in detailed:

1) Modify web.xml (deployment descriptor) file to add listener

web.xml file will be read / looked upon by the container while loading any of the project. To inform container about "ServletContextListener" we need to add below
lines in it:

<listener>
<listener-class>com.listener.ApplicationContextListener</listener-class>
</listener>

2) Add a class which implements "ServletContextListener"

Here is the code snippet for the  quick reference:

public class ApplicationContextListener implements ServletContextListener {

    public ApplicationContextListener() {
    }

    public void contextInitialized(ServletContextEvent arg0) {
    System.out.println("Context Initialzied");
    }

    public void contextDestroyed(ServletContextEvent arg0) {
    System.out.println("Context Destroyed");
    }
}

As we can see there are two methods "contextInitialized" and "contextDestroyed" which will be called at the time of application being deployed and undeployed
respectively.

3) Run and Verify

When Server is getting up we will see below message

INFO: Starting service Catalina
Jul 10, 2015 3:15:11 PM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
Context Initialzied

While unloading "student" application we will see below message:

Jul 10, 2015 7:25:53 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/student] has started
Context Destroyed


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

How to plug filter before and after any request in java

If we want to perform any operation before and after servlet gets executed then filter is the option we can use. In java it is possible to inject filter before and/or after any of the servlet gets called. Because of filter's nature, generally filters are used to perform common operation.

Some of the typical use of Filter are:

1) Intercept request from client side before reaching out to actual server side resource
2) Manipulate Server side response before it reaches to client side

Example where filters are used are:

1) Logging few parameters before every request / response
2) Check Authentication of the user before providing any server response to the Client

We can also plug series of filters to segregate the responsibilities among filters.

Lets see how to use filters in java:

There are  simple two steps:

1) Create a java class which implements "Filter"
2) Modify web.xml file to write "<filter>" and <"filter-mapping>" entry

Here are the steps in detailed:

1) Create a java class which implements "Filter"

Here are the code snippet of the "Authentication" Filter for the quick reference:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
System.out.println("I am in Authentication Filter Before");
// pass the request along the filter chain
chain.doFilter(request, response);
System.out.println("I am in Authentication Filter After");
}

2) Modify web.xml file to write "<filter>" and <"filter-mapping>" entry

<!-- Entry of the Servlet -->
<servlet>
<description></description>
<display-name>Result</display-name>
<servlet-name>Result</servlet-name>
<servlet-class>com.registration.Result</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Result</servlet-name>
<url-pattern>/Result</url-pattern>
</servlet-mapping>


<!-- Entry of the filter which gets fired when any request comes for the "Result" servlet -->
<filter>
<display-name>Authentication</display-name>
<filter-name>Authentication</filter-name>
<filter-class>com.fileter.Authentication</filter-class>
</filter>
<filter-mapping>
<filter-name>Authentication</filter-name>
<url-pattern>/Result</url-pattern>
</filter-mapping>

Now, whenever we hit the Url http://localhost:8080/student/Result at that time we will see output in catalina.out as follows:

I am in Authentication Filter Before (Line#1)
I am in Result Servlet (Line #2)
I am in Authentication Filter After (Line #3)

Assuming that we have one servlet created with the name "Result" whose "doGet" method prints "I am in Result Servlet" in console.

We can observe that filter has wrapped the actual Servlet call. So our filter got called and it has printed line #1 then Servlet got called it has printed line #2 and then after "Result" servlet is completed it again came back to "Authentication" filter and printed remaining statement i.e. line #3.

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Thursday, 9 July 2015

How to use Liferay's IO request module

Liferay AUI has one module called "aui-io-request" which allows to fetch dynamic data based on the user input and show the result back to the browser.

Here are the steps to use AUI autocomplete feature

1) Download and Extract "alloy-1.5.1" (required if bundle is not Liferay,lets say creating dynamic web project)
2) Create JSP file to add aui's js & corresponding stylesheet
3) Load "aui-io-request" module on JSP
4) Create Servlet to return dynamic data based on user input value
5)  Run & Verify

Here are the steps in detailed:

1) Download and Extract "alloy-1.5.1" (required if bundle is not Liferay,lets say creating dynamic web project)

This steps is required only if you are not using Liferay's bundle. Liferay bundle has AUI available by default.
For our example we have used "alloy-1.5.1". Lets download and copy our content to the location "{c:}\alloy-1.5.1".


2) Create JSP file to add aui's js & corresponding stylesheet

In order to use AUI components we need to import below files onto our JSP

We have created dynamic web project with the name "student". We have copied "{c:}\alloy-1.5.1\build" to the location "/student/WebContent/js/build" path.

Once its copied to the above path use below statements to include aui.js & "aui-ski-classic-all-min.css" like below:

<script src="/student/js/build/aui/aui.js" type="text/javascript"></script>
<link rel="stylesheet" href="/student/js/build/aui-skin-classic/css/aui-skin-classic-all-min.css" type="text/css" media="screen" />

<form name="studentForm">
Student id : <input type="text" name="id" id="id" value="45" /> <br />
<input type="button" value="Go" id="go" />
</form>

3) Load "aui-autocomplete" module on JSP

Once aui.js is included on our JSP we need to load one of the modules from AUI.

Here is the code snippet to load "aui-autocomplete"

<script type="text/javascript">
YUI().use('aui-io-request','node',
 function(Y) {
   Y.one('#go').on(
     'click',
     function() {
       var studentId = Y.one('#id').val();          
         Y.io.request(
           '/student/Result?id=' + studentId,
           {             
             on: {
               success: function() {
                 // gets the result of this asynchronous request
                 var result = this.get('responseData');
alert(result);
               }
             }
           });        
     });
 });
</script>

We have use an example of student's result. On the JSP user will have to provide studnetId whose result one wants to see. After that user need to click on the
"Go" button to see the result on the screen. In our case result will be shown in the alertbox. We may show it on location as per our requirements.

4) Create Servlet to return dynamic data based on user input value

In our example we have passed "id" to the server side (Servlet in our case). "Result" servlet will return result based on the inputed "id" value.

Here is the code snippet for the quick reference.

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String id = request.getParameter("id");

if("45".equalsIgnoreCase(id)) {
response.getWriter().print("89%");
} else {
response.getWriter().print("78%");
}
System.out.println("I am in a Result");
}

5)  Run & Verify

By default when we load the result.jsp it will look something like this:


When we enter id as "45" and hit "Go" button it shows result like this:


When we enter id as "4" and hit "Go" button it shows result like this:


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

How to use Liferay AUI's Autocomplete feature

Liferay bundle comes with the AUI module loaded by default. AUI supports many of the client side components one of them is "Autocomplete".

Here are the steps to use AUI autocomplete feature

1) Download and Extract "alloy-1.5.1" (required if bundle is not Liferay,lets say creating dynamic web project)
2) Create JSP file to add aui's js & corresponding stylesheet
3) Load "aui-autocomplete" module on JSP
4)  Run & Verify

Here are the steps in detailed:

1) Download and Extract "alloy-1.5.1" (required if bundle is not Liferay,lets say creating dynamic web project)

This steps is required only if you are not using Liferay's bundle. Liferay bundle has AUI available by default.
For our example we have used "alloy-1.5.1". Lets download and copy our content to the location "{c:}\alloy-1.5.1".


2) Create JSP file to add aui's js & corresponding stylesheet

In order to use AUI components we need to import below files onto our JSP

We have created dynamic web project with the name "student". We have copied "{c:}\alloy-1.5.1\build" to the location "/student/WebContent/js/build" path.

Once its copied to the above path use below statements to include aui.js & "aui-ski-classic-all-min.css" like below:

<script src="/student/js/build/aui/aui.js" type="text/javascript"></script>
<link rel="stylesheet" href="/student/js/build/aui-skin-classic/css/aui-skin-classic-all-min.css" type="text/css" media="screen" />

3) Load "aui-autocomplete" module on JSP

Once "aui.js" is included on our JSP we need to load one of the modules from AUI.

Here is the code snippet to load "aui-autocomplete"

<script type="text/javascript">
AUI().use('aui-autocomplete',function (A) {
var studentData = [
 ['45', 'Scott', 'scott@test.com'],
 ['26', 'Micheal', 'micheal@test.com'],
 ['47', 'Peter', 'peter@test.com']      
];

new A.AutoComplete(
 {
contentBox: '#studentList',
delimChar: ',',
dataSource: studentData,
schema: {
 resultFields: ['id', 'studentName', 'studentEmail']
},
matchKey: 'studentEmail',
typeAhead: true
 }).render();
 });
</script>

We have use an example of student. In our example we have created "studentData" list with three different values i.e. "id","studentName","studentEmail".

We have created sample data with the same structure which is available in "studentData". During auto complete user may use one of these values to fetch student data.
Property, "matchKey" is the one through which we can specify which key to be used for auto complete feature.

4)  Run & Verify

By default when we load the JSP it will look something like this:



When we type "p..." it will show the matching email address starting with "P" letter. Here is the snippet for same:


When we click on the dropdown next to the textbox it shows all the record we have provided in the "studentData". Here is the snippet for the same:



Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics