ServletContext dan Listener di Java

Assalamualaikum Warohmatullah,
Selamat sore, 
Kali ini saya akan berbagi mengenai ServletContext dan Listener di Java.

Sebelumnya saya akan menjelaskan mengenai ServletContext. Apa itu ServletContext?
ServletContext adalah suatu interface yang digunakan untuk berkomunikasi dengan servletcontainer. Dalam sebuah aplikasi web hanya terdapat satu ServletContext saja, dan seluruh komponen aplikasi web dapat saling menggunakannya. Berikut ini adalah daftar method yang sering digunakan yang berada di interface ServletContext:
  • setAttribute (String name, Object object) Berfungsi untuk membuat suatu attribute dengan nama dan object tertentu.
  • getAttribute(String  name) Berfungsi  untuk  mengembalikan  nilai  dari  suatu  attribu tetertentu.
  • getAttributeNames() Berfungsi untuk mengembalikan nama2 semua attribute yang ada dalam ServletContext.
  • removeAttribute(String name). Berfungsi untuk mengahapus suatu attribute tertentu.
  • getServletContextName() Berfungsi untuk mengambil nilai yang berada di dalam elemen yang berada di file web.xml.
  • getInitParameter(String  name) Berfungsi  untuk  mengambil  nilai  paramater  yang  sudah diinisaliasikan di file web.xml.
  • getInitParameterNames() Berfungsi untuk mengambil semua nama parameter yang ada.
  • getServerInfo() Berfungsi  untuk  mengambil  nama  dan  versi dari  servlet-container. Formatnya adalah servername/versionnumber.
  • getRealPath(String path) Berfungsi untuk mengambil real path dari suatu aplikasi web. Real path disini maksudnya letak direktori file2 aplikasi web tersebut.
  • log(String  log) Berfungsi  untuk menulis  suatu  pesan/log. 
Log  yang  kita  buat  ini  bisa dilihat di Apache Tomcat xxx.Log (Jika menggunakan netbeans, terletak di bagian output). Sedangkan  ContextListener  berfungsi  seperti listener  di  java  yaitu mendeteksi  suatu event  dan memberikan  respons terhadap event tersebut.  Di  dalam  servlet, jika kita mendeklarasikan  sebuah  listener pada objek tertentu,  maka  servlet-container akan menghasilkan event yang sesuai pada saat terjadi perubahan dalam objek tersebut. Berikut ini adalah beberapa interface listener bisa digunakan di servlet:

  • ServletContextListener
  • ServletContextAttributeListener
  • ServletRequestListener
  • ServletRequestAttributeListener
  • HttpSessionListener
  • HttpSessionAttributeListener

Sekarang langsung saja buat sebuah project java web baru dengan nama MyServletListener menggunakan IDE kalian (saya menggunakan netbeans), lalu tambahkan code berikut di file index.jsp/ index.html

<a href="getServletContext.do">view servlet context</a>

Lalu  buatlah  sebuah servlet  baru  dengan  nama ServletContextClass,  perhatikan gambar berikut ini :


Jangan lupa untuk men –ceklis Add Information to Deployment descriptor



Kemudian rubah file ServletContextClass.java menjadi seperti ini:

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Siti Sadiah
 */
public class ServletContextClass extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ServletContextClass</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ServletContextClass at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException{
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        ServletContext ctx = getServletContext();
        
        ctx.setAttribute("name", "Eresha Wikrama");
        out.print(ctx.getAttribute("name"));
        
        Enumeration temp = ctx.getAttributeNames();
        while (temp.hasMoreElements()) {
            String attrName = (String) temp.nextElement();
            out.print("<br>Atribut " + attrName + " , nilainya = " + ctx.getAttribute(attrName));
        }
        
        out.print ("<br><br>getServletContextName() : " + ctx.getServletContextName());
        
        out.print("<br>" + ctx.getInitParameter("bhs1"));
        Enumeration temp2 = ctx.getInitParameterNames();
        while (temp.hasMoreElements()) {
           String paramName = (String) temp2.nextElement();
           out.print("<br>Atribut " + paramName + " , nilainya = " + ctx.getAttribute(paramName));
        }
        
        out.print("<br>getServerInfo() :" + ctx.getServerInfo());
        out.print("<br>getRealPath() :" + ctx.getRealPath(""));
        ctx.log("Hello World");
        
            ctx.setAttribute("name", "Eresha Wikrama Bogor, Teknik Informatika");
            ctx.setAttribute("name", null);
            
            request.setAttribute("word", "never say give up in this world");
            request.setAttribute("word", "do your best and let God do the rest");
            request.setAttribute("word", null);
            
            HttpSession session = request.getSession();
            session.setAttribute("userSession", "EreshaWikramaSession");
            session.setAttribute("userSession", "Mari Belajar Java");
            session.setAttribute("userSession", null);
        }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws  ServletException, IOException{
            processRequest(request, response);
            }
    
    @Override
    public String getServletInfo(){
        return "Short Description";
    }
 }

Kemudian buat sebuah 6 buah class untuk mengimplementasikan setiap interface listener di atas. Sebenarnya buat 1 class juga bisa untuk mengimplementasikan keenam interface tersebut. Namun ada baiknya dipisah saja per interface, supaya lebih mudah dicerna.

ServletContextListener


Selanjutnya seperti gambar di bawah ini :


Klik next, kemudian :


Klik finish. Kemudian ubah kode pada file ServletContexListenerClass.Java menjadi seperti ini :

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Web application lifecycle listener.
 *
 * @author Siti Sadiah
 */

public class ServletContextListenerClass implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext ctx = sce.getServletContext();
        if (ctx != null){
            ctx.log("Context : " + ctx.getServletContextName() + " sudah diinisialisasi");
            
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext ctx = sce.getServletContext();
        if (ctx != null){
            ctx.log("Context : " + ctx.getServletContextName() + " sudah dihancurkan");
            
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

Ketika proses inisialisasi dari aplikasi kita telah dimulai, maka fungsi ContextInitialized akan di jalankan. Sedangkan ketika servlet-context akan dishutdown maka fungsi contextDestroyed akan dijalankan.

ServletContextAttributeListener
Selanjutnya buat file ServerListener dengan nama ServletContextAttributeListenerClass, pada bagian Interfaces to Implement, pilih Context Attribute Listener


Kemudian ubah kode file class tersebut menjadi seperti ini :

import javax.servlet.ServletContext;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Web application lifecycle listener.
 *
 * @author Siti Sadiah
 */


public class ServletContextAttributeListenerClass implements ServletContextAttributeListener {

    @Override
    public void attributeAdded(ServletContextAttributeEvent event) {
        ServletContext ctx = event.getServletContext();
        if (ctx != null)
        {
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "attribute " + event.getName() + " dengan nilai : " + event.getValue() + " Sudah ditambahkan"
            );
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void attributeRemoved(ServletContextAttributeEvent event) {
        ServletContext ctx = event.getServletContext();
        if (ctx != null)
        {
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "attribute " + event.getName() + " dengan nilai : " + event.getValue() + " Sudah dihapus"
            );
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void attributeReplaced(ServletContextAttributeEvent event) {
        ServletContext ctx = event.getServletContext();
        if (ctx != null)
        {
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "attribute " + event.getName() + " dengan nilai : " + event.getValue() + " Sudah diubah"
            );
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

Ketika ada suatu attribute baru yang ditambahkan ke dalam servlet-context maka fungsi attributeAdded akan dijalankan, ketika suatu attribute dihapus maka fungsi attributeRemoved dijalankan, dan ketika suatu attribute diubah nilainya maka fungsi attributeReplaced dijalankan


Kemudian ubah code file class tersebut menjadi seperti ini :

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Web application lifecycle listener.
 *
 * @author Siti Sadiah
 */
public class ServletRequestListenerClass implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        ServletContext ctx = sre.getServletContext();
        if(ctx != null)
        {
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "request " + sre.getServletRequest() + " sudah  dihancurkan");
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        ServletContext ctx = sre.getServletContext();
        if(ctx != null)
        {
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "request " + sre.getServletRequest() + " sudah  diinisialisasi");
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

ServletRequstAttributeListener
Selanjutnya buat file ServletListener dengan nama ServletRequestAttributeListenerClass, pada kolom Interface to Implement pilih Request Attribute Listener:


Kemudian ubah kode file tersebut seperti dibawah ini :

import javax.servlet.ServletRequestAttributeEvent;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Web application lifecycle listener.
 *
 * @author Siti Sadiah
 */
public class ServletRequestAttributeListener implements 
        javax.servlet.ServletRequestAttributeListener{
  
    @Override
    public void attributeAdded(ServletRequestAttributeEvent event) {
        System.out.println("Attribute ditambahkan : " + event.getName() + " = "
                    + event.getValue());
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent event) {
        System.out.println("Attribute dihapus : " + event.getName() + " = "
                    + event.getValue());
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent event) {
        System.out.println("Attribute diganti : " + event.getName() + " = "
                    + event.getValue());
    }
}

HttpSessionListener
Selanjutnya buat file ServerListener dengan nama HttpSessionListenerClass, pada Interface to Implement pilih HTTP Session Listener


Kemudian, ubah kode tersebut seperti di bawah ini :

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Web application lifecycle listener.
 *
 * @author Siti Sadiah
 */
public class HttpSessionListenerClass implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        if(ctx != null){
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "session " + se.getSession().getId() + " sudah dibuat"
            );
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        if(ctx != null){
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "session " + se.getSession().getId() + " sudah dihancurkan"
            );
        }
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

HttpSessionAttributeListener
Selanjutnya buat file ServerListener dengan HttpSessionAttributeListenerClass, pada kolom Interfaces to Implement pilih Http Session Attribute Listener :


Kemudian ubah kode seperti di bawah ini :

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Web application lifecycle listener.
 *
 * @author Siti Sadiah
 */
public class HttpSessionAttributeListenerClass implements HttpSessionAttributeListener {

    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        ServletContext ctx = event.getSession().getServletContext();
        if (ctx != null){
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "session attribute " + event.getName() + " dengan nilai : "
                    + event.getValue() + " sudah ditambahakan"
            );
        }
//        /throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        ServletContext ctx = event.getSession().getServletContext();
        if (ctx != null){
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "session attribute " + event.getName() + " dengan nilai : "
                    + event.getValue() + " sudah dihapus"
            );
        }
//        /throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {
        ServletContext ctx = event.getSession().getServletContext();
        if (ctx != null){
            ctx.log("Context " + ctx.getServletContextName() + ", "
                    + "session attribute " + event.getName() + " dengan nilai : "
                    + event.getValue() + " sudah diubah"
            );
        }
//        /throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

Sekarang daftarkan class ServletContextClass sebagai sebuah servlet dan keenam class di atas sebagai sebuat listener. Konfigurasinya kita lakukan di file web.xml, seperti ini :

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>bhs1</param-name>
        <param-value>Java</param-value>
    </context-param>
    <context-param>
        <param-name>bhs2</param-name>
        <param-value>C++</param-value>
    </context-param>
    <context-param>
        <param-name>bhs3</param-name>
        <param-value>C</param-value>
    </context-param>
    <context-param>
        <param-name>bhs4</param-name>
        <param-value>VB.Net</param-value>
    </context-param>
    <context-param>
        <param-name>bhs5</param-name>
        <param-value>JSP</param-value>
    </context-param>
    <listener>
        <description>ServletContextListener</description>
        <listener-class>ServletContextListenerClass</listener-class>
    </listener>
    <listener>
        <description>ServletContextAttributeListener</description>
        <listener-class>ServletContextAttributeListenerClass</listener-class>
    </listener>
    <listener>
        <description>RequestListener</description>
        <listener-class>ServletRequestListenerClass</listener-class>
    </listener>
    <listener>
        <description>RequestAttributeListener</description>
        <listener-class>HttpSessionAttributeListenerClass</listener-class>
    </listener>
    <listener>
        <description>RequestAttributeListener</description>
        <listener-class>HttpSessionAttributeListenerClass</listener-class>
    </listener>
    <servlet>
        <servlet-name>ServletContext</servlet-name>
        <servlet-class>ServletContext</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ServletContextClass</servlet-name>
        <servlet-class>ServletContextClass</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletContext</servlet-name>
        <url-pattern>/ServletContext</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ServletContextClass</servlet-name>
        <url-pattern>/ServletContextClass</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Dalam prakteknya, listener ServletContextListener sering digunakan untuk melakukan proses connect dan disconnect dari database server. Sedangkan listener HttpSessionListener sering digunakan untuk mencatat aktivitas di database. Misalnya kapan user login dan kapan user logout dari aplikasi kita.

Alhamdulillah ServletContext dan Listener java sudah selesai dibuat, silahkan untuk melakukan running aplikasi dengan mengklik kanan pada aplikasi dan pilih run. Semoga berhasil :D
Terima kasih









Share on Google Plus

About Unknown

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 komentar:

Posting Komentar