Thursday, 30 July 2015

How to write hibernate application using MySql

This blog will be helpful to create simple java application using hibernate:

To make things very easy we will be taking an example of student. In this example we will be creating a "StudentRecord" table and will insert dummy student data in it.

We will see how "Hibernate" can create a table for us. Hence we don't need to worry about creating a table manually. Our application will take care of not just insertion
of the student record but creating of table as well.

There are few simple steps we need to perform for writing simple hibernate java application.

Here are the main steps:

1. Create Entity Class
2. Create ".hbm" file for the student 
3. Hibernate configuration XML file
4. Create a Dummy Class to test application
5. Run and Verify
6. Trouble Shoot

Let's see the steps in detailed

1. Create Entity Class

This is a POJO class which holds all the properties related to student along with the  setter and getter methods.

Here is the quick code snippet:

package student.persistence;

public class Student {

private int studentId;
private String studentName;
private String email;
private String gender;

public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}

In our case we have used four properties "studentId", "studentName", "email", "gender". Whose value we will be storing inside the table in the proceeding steps:

2. Create ".hbm" file for the student 

For every "POJO" we need to create ".hbm" file. ".hbm" file contains the mapping of "POJO" (Class) with "Relational Table" (StudentRecord) in our case.
At the same time ".hbm" file contains the association between "attributes" of the "POJO" with the "column" of the "Table".
We can also specify the constraint like "primary key" , "composite key" etc in ".hbm" file.

Here is the quick code snippet:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="student.persistence.Student" table="StudentRecord">
<id name="studentId">
<generator class="assigned"></generator>
</id>
<property name="studentName"></property>
<property name="email"></property>
<property name="gender"></property>
</class>
</hibernate-mapping>

3. Hibernate configuration XML file (.cfg) file

For every application there is one "hibernate.cfg.xml" file. Which is the main mapping file. It contains the details related to database, connection,username,
password,dialect etc. Along with the few hibernate specific properties can also be specified.

Here is the quick reference of "hibernate.cfg.xml" file:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="student.hbm.xml" />
</session-factory>
</hibernate-configuration>

In our application we have used the "MySQLDialect" which means our application will be creating a table inside "MySql" database.
Property "hibernate.connection.url" contains the details like under which databse/schema our tables should get created. In Url "..../student" we have specified
that means that our table "StudentRecord" will be created under "student" schema.

Property "<mapping resource="student.hbm.xml" />", loads the student.hbm.xml file.
Property "<property name="show_sql">true</property>" will print the all the sql which our application will fire. (Its very helpful for the debugging purpose)


4. Create a Dummy Class to test application

In our java application we will be using "StudentDemo" as an entry point for the application. In our dummy class we will be doing following operations

Load Configuration file ("hibernate.cfg.xml")
Build Session Factory
Open Session
Create, Instantiate, Initialize a student pojo
begin the transaction
save/persist student pojo
commit the transaction
Close Session and Factory respectively.

Here is the code snippet for quick reference:

package student.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import student.persistence.Student;

public class StudentDemo {

    public static void main(String[] args) {

        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");

        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Student student = new Student();
        student.setStudentName("Peter");
        student.setGender("M");
        student.setEmail("peter@test.com");
        
        Transaction tx = session.beginTransaction();
        session.save(student);
        
        System.out.println("Student Record Saved Successfully! ");
        
        tx.commit();
        session.close();
        factory.close();
    }
}


5. Run and Verify

When we run the "StudentDemo" class we can see below console output:

Jul 30, 2015 2:55:35 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.0.0.CR2}
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 30, 2015 2:55:35 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jul 30, 2015 2:55:37 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.0.Final}
Jul 30, 2015 2:55:37 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Refer to Hibernate 3.6 Migration Guide!
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/student]
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
Jul 30, 2015 2:55:38 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jul 30, 2015 2:55:40 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 30, 2015 2:55:42 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: 
    drop table if exists StudentRecord
Hibernate: 
    create table StudentRecord (
        studentId integer not null,
        studentName varchar(255),
        email varchar(255),
        gender varchar(255),
        primary key (studentId)
    )
Jul 30, 2015 2:55:43 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Student Record Saved Successfully! 
Hibernate: 
    insert 
    into
        StudentRecord
        (studentName, email, gender, studentId) 
    values
        (?, ?, ?, ?)
Jul 30, 2015 2:55:43 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost:3306/student]


We can see that first of all hibernate goes to drop the table if the table already exist. Then it creates the table using auto generated "Create" script.
and then it insert the record into the "StudentRecord" table.

Here is the snippet we can see in the database:




6. Trouble Shoot

Overall our application package structure should look like this:



For more trouble shoot please refere "http://technoknowledgespread.blogspot.in/2015/07/common-errors-while-configuring.html"

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Common errors while configuring a hibernate application

I have seen that people struggle a lot while setting up the hibernate application.

Here is a blog which will help the user for the common errors and its resolution.

1) NoClassDefFoundError : org/apache/commons/logging/LogFactory

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at org.hibernate.cfg.Configuration.<clinit>(Configuration.java:110)
at student.test.StudentDemo.main(StudentDemo.java:14)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more

Resolution : Need to include jar file "commons-logging-1.2.jar"



2) NoClassDefFoundError : org/dom4j/io/SAXReader

Exception in thread "main" java.lang.NoClassDefFoundError: org/dom4j/io/SAXReader
at org.hibernate.util.XMLHelper.createSAXReader(XMLHelper.java:35)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1168)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1112)
at student.test.StudentDemo.main(StudentDemo.java:15)
Caused by: java.lang.ClassNotFoundException: org.dom4j.io.SAXReader
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 4 more

Resolution : Need to include jar file "dom4j-1.6.1.jar"



3) NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/SequencedHashMap
at org.hibernate.mapping.Table.<init>(Table.java:32)
at org.hibernate.cfg.Mappings.addTable(Mappings.java:120)
at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:251)
at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:236)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:152)
at org.hibernate.cfg.Configuration.add(Configuration.java:362)
at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:400)
at org.hibernate.cfg.Configuration.addResource(Configuration.java:449)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1263)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1235)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1217)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1184)
at org.hibernate.cfg.Configuration.configure(Configuration.java:1112)
at student.test.StudentDemo.main(StudentDemo.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.collections.SequencedHashMap
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 14 more

Resolution : Need to include jar file "commons.collections-3.2.1"



4) NoClassDefFoundError: net/sf/ehcache/CacheException

Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/ehcache/CacheException
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at org.hibernate.cfg.SettingsFactory.createCacheProvider(SettingsFactory.java:323)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:219)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1463)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1004)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: net.sf.ehcache.CacheException
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 10 more


Resolution : Need to include jar file "ehcache-core-2.4.3"



5) NoClassDefFoundError: javax/transaction/Synchronization

INFO: Default entity-mode: pojo
Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/Synchronization
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 2 more


Resolution : Need to include jar file "jta.jar"



6) NoClassDefFoundError: net/sf/cglib/core/KeyFactory

INFO: Default entity-mode: pojo
Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/cglib/core/KeyFactory
at org.hibernate.impl.SessionFactoryImpl.<clinit>(SessionFactoryImpl.java:321)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: net.sf.cglib.core.KeyFactory
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 3 more


Resolution : Need to include jar file "cglib-2.1_3"



7) NoClassDefFoundError: org/objectweb/asm/Type

INFO: Default entity-mode: pojo
Exception in thread "main" java.lang.NoClassDefFoundError: org/objectweb/asm/Type
at net.sf.cglib.core.TypeUtils.parseType(TypeUtils.java:180)
at net.sf.cglib.core.KeyFactory.<clinit>(KeyFactory.java:66)
at org.hibernate.impl.SessionFactoryImpl.<clinit>(SessionFactoryImpl.java:321)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1005)
at student.test.StudentDemo.main(StudentDemo.java:17)
Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 5 more


Resolution : Need to include jar file "asm-1.3.3"

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Monday, 20 July 2015

How to use Error Handlers in Java EE

Client sends a request to the Server for a specific resource. Sometimes it is possible that due to one or another reason server sends an Http status code (related to error) to the client, instead of actual response to the client.

In Java EE it is possible to redirect or show a specific error page as and when any particular error message comes up.

There are two simple steps to be performed for "Error Handlers"

1) Modify web.xml (deployment descriptor) file to add "Error Handlers"
2) Add a JSP to be shown when an error occurs
3) Run and Verify

Here are the detailed steps:

1) Modify web.xml (deployment descriptor) file to add "Error Handlers"

<error-page>
        <error-code>404</error-code>
        <location>/login/errors/pagenotfound.jsp</location>
</error-page>

Here, we have configured "Error Handler" for the Http status code "404". It is the code for the resource not found. As and when we hit the URL or request for the
resource which server can not find at that time server will return Http status code "404".

2) Add a JSP to be shown when an error occurs

Whenever server sends 404 error code at that time JSP available inside folder "WebContent/login/errors/pagenotfound.jsp" will be shown to the user instead of technical message
which layman user can not understand.

In our case we have written a message "Hey requested resource not found"

3) Run and Verify

Once above steps are done just Build and deploy your application on the server. To understand the difference quickly lets look at the two snaps when we hit
URL "http://localhost:8080/student/MyLogin"

Before "Error Handlers"



After "Error Handlers"




Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

How to use HttpSessionBindingListener in Java EE

In dynamic web application user may like to track as and when object gets "bound" and "unbound" from the session object. In Java EE it is possible to achieve through "Listeners".

HttpSessionBindingListener has below two methods:

1) public void valueUnbound(HttpSessionBindingEvent arg0)
2) public void valueBound(HttpSessionBindingEvent arg0)

If we want to perform any action while object is associated or removed from the "HttpSession" then below three steps needs to be performed:

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "HttpSessionBindingListener"
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 "HttpSessionBindingListener" we need to add below
lines in it:

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

2) Add a class which implements "HttpSessionBindingListener"

Here is the code snippet for the  quick reference:

public class Student implements HttpSessionBindingListener {

    public Student() {
    }

    public void valueUnbound(HttpSessionBindingEvent arg0) {
    System.out.println("Student Object is Unbound");
    }

    public void valueBound(HttpSessionBindingEvent arg0) {
        System.out.println("Student Object is Bound");
    }
}


As we can see there are two methods "valueUnbound" and "valueBound" which will be called at the time of "Student" object gets added or removed to and from the HttpSession object respectively.

3) Run and Verify

Lets create a dummy servlet called "HttpSessionBindEventTest" which has below "doGet" method which adds and removes the "Student" object in HttpSession.

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Student student = new Student();
request.getSession().setAttribute("student", student); //Line #1
request.getSession().removeAttribute("student"); //Line #2
}

when we run the Url : "http://localhost:8080/student/HttpSessionBindEventTest" and hit enter below lines we can see inside logs:

INFO: Server startup in 578 ms
Student Object is Bound //Line #1
Student Object is Unbound //Line #2

Line #1 is the result of 1st line of the "doGet" method (HttpSessionBindEventTest)
Line #2 is the result of the 2nd line of the "doGet" method (HttpSessionBindEventTest)

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Thursday, 16 July 2015

How to add liferay portlet under one of the secions of control panel

Many a times it is the requirement that we want to see our custom portlet under one of the sections of the control panel. In liferay it is possible to do it by following few simple steps.

Here are the two simple steps available to get it done:

1) Modify liferay-portlet.xml file to specify where in control panel we want to see our portlet
2) Run and Verify

Here are the steps in detailed:

1) Modify liferay-portlet.xml file to specify where in control panel we want to see our portlet

Here is the sample code snippet of the liferay-portlet.xml

<liferay-portlet-app>
<portlet>
<portlet-name>StudentPage</portlet-name>
<icon>/icon.png</icon>
:
<control-panel-entry-category>portal</control-panel-entry-category>
<control-panel-entry-weight>100</control-panel-entry-weight>
:
</portlet>
</liferay-portlet-app>


As we can see that there are mainly two properties

I) "<control-panel-entry-category>" which controls under which section of the control panel our portlet should be visible.

Here we can specify one of the four values

i) my
ii) content
iii) portal
iv) server

In our case we have specified "portal" so our portlet "StudenPage" will be available under "portal" section.

II) "<control-panel-entry-weight>" and we need to set to see the custom portlet inside one of the sections of the control panel.

Here we need to specify the weight of the portlet. Higher the weight will show our portlet in lower portion.

In our case we have specified "100" means that across all the portlet under "portal" our portlet would come more on the bottom side.


2) Run and Verify

We are just a one step away to see our custom portlet inside control panel. Just build and deploy latest war file. Once we see that "StudentPage" (In our case) is available
for use just go over the control panel of the liferay, scroll down to "Portal" section and see your portlet would be available with other OOTB portlet.

FYI, liferay provides one more property inside same file called "<control-panel-entry-class>". This can be used if we want to specify custom logic that portlet
should be visible to only spefic set of roles. Then we can specify class name in this property. Basically custom class which we write should implement
"com.liferay.portlet.ControlPanelEntry" interface. "ControlPanelEntry" interface has the method "isVisible" which will be called where we can write our custom logic.

Reader may go through "com.liferay.portlet.BaseControlPanelEntry" class to checkout by default portlet would be visible to which all roles.

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Wednesday, 15 July 2015

How to display liferay portlet under custom category in add more option

Many a times it is the requirement that we want to see our custom portlet under specific category inside "Add More" option. In liferay it is possible to achieve the same by following simple steps.

Here are the three simple steps available to get it done:

1) Modify liferay-display.xml file to alter category details
2) Add an entry inside "Language.properties" for the new category
3) Run and Verify

Here are the steps in detailed:

1) Modify liferay-display.xml file to alter category details

<display>
        <category name="category.university">
                 <portlet id="studentPortlet" />
          </category>
</display>

Here we have taken an example of "University" which is the category name under which all our custom portlet related to "University" will be placed.

"category.university" is the name of the key which we will be placing inside "Language.properties"

2) Add an entry inside "Language.properties" for the new category

We need to create a "Language.properties" file which will maintain all the key and value pair.

In our case we need to add below line inside this file:

category.university=University

Here "category.university" is the key whose corresponding value i.e. "University" will be shown inside "Add More" option.

3) Run and Verify

Once above configuration is done we are almost done. Just need to build and redeploy our portlet. After we see message inside log file that our portlet is available for use we need to click on the "Add More" option and see the newly added category called "University" would be available. Under "University" you will see the portlet added under it. In our case its "studentPortlet".

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

Tuesday, 14 July 2015

How to use HttpSessionListener in Java EE

In dynamic web application user may store details in different scope. If data wants to be shared among more than one request at that time it can be stored inside "HttpSession". If we want to keep track that when HttpSession object gets created and destryoed then HttpSessionListener is the option one need to use.

HttpSession Lifecycle has below two events ,here are the main events of it:

1) session created
2) session destroyed

If we want to perform any action while session is created or destroyed then below three steps needs to be performed:

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "HttpSessionListener"
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 "HttpSessionListener" we need to add below
lines in it:

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

2) Add a class which implements "HttpSessionListener"

Here is the code snippet for the  quick reference:

public class MyHttpSessionListener implements HttpSessionListener {

    public MyHttpSessionListener() {
    }

    public void sessionCreated(HttpSessionEvent arg0) {
    System.out.println("Session Created");
    }

    public void sessionDestroyed(HttpSessionEvent arg0) {
    System.out.println("Session Destroyed");
    }
}

As we can see there are two methods "sessionCreated" and "sessionDestroyed" which will be called at the time of HttpSession object created and destroyed respectively.

3) Run and Verify

Lets create a dummy servlet called "SessionLifecyclTest" which has below "doGet" method which creates and invalidates the HttpSession object:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
session.invalidate();
}

when we run the Url : "http://localhost:8080/student/SessionLifeyCycleTest" and hit enter below lines we can see inside logs:

Session Created //Line #1
Session Destroyed //Line #2

where,

Line #1 is the result of 1st line of the "doGet" method (SessionLifecycleTest)
Line #2 is the result of the 2nd line of the "doGet" method (SessionLifecyclTest)

Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

How to use HttpSessionAttributeListener 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 in HttpSession then we can
use "HttpSessionAttributeListener". In short web application receives notification as and when any operation is done on the attribute of a HttpSession.

There is just a single listener which keeps track of the attribute being added, deleted, replaced by any of the Servlet.

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

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

Here are the steps to implement "HttpSessionAttributeListener"

1) Modify web.xml (deployment descriptor) file to add listener
2) Add a class which implements "HttpSessionAttributeListener"
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 "HttpSessionAttributeListener" we need to add below
lines in it:

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

Here we assume that we have created a class with the name "MyHttpSessionAttributeListener" which implements "HttpSessionAttributeListener".

2) Add a class which implements "HttpSessionAttributeListener"

Here is the code snippet for the  quick reference:

public class MyHttpSessionAttributeListener implements HttpSessionAttributeListener {

    public MyHttpSessionAttributeListener() {
    }

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

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

    public void attributeReplaced(HttpSessionBindingEvent arg0) {
        System.out.println("Attribute Replaced in session (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 Session scope.


3) Run and Verify

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

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(); // Line #1
session.setAttribute("name", "Peter"); // Line #2
session.setAttribute("name", "John"); // Line #3
session.removeAttribute("name"); // Line #4
 }

Now to verify our listener, we need to call our "StudentLogin" servlet in which we have done operation on the attribute of the "HttpSession".

In "StudentLogin",

Line #1 takes the HttpSession object from the HttpServletRequest object.
Line #2 sets the attribute in HttpSession scope.
Line #3 replaces the attribute from the HttpSession scope.
Line #4 removes the attribute from the HttpSession.

When "doGet" method of the "StudentLogin" 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 session (Name -> name, Value ->Peter)
Attribute Replaced in session (Name -> name, Value ->Peter)
Attribute Removed in session (Name -> name, Value ->John)


Cheers!
Henal Saraiya
(Lead Consultant)
CIGNEX Datamatics

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