WHAT'S NEW?
Loading...

Membuat Servlet Filter dan Servlet Listener Part 2

Assalamu'alaikum ..
Mari kita lanjutkan ngulik java, sebelumnya di part 1 kita sudah membahas tentang servlet filternya bisa dilihat di Servlet Filter Login.
postingan kali ini saya akan mengangkat tema ServletContext dan ContextListener ..

ServletContext adalah suatu interface yang digunakan untuk berkomunikasi dengan servlet container. Dalam sebuah aplikasi web hanya terdapat satu ServletContext saja, dan seluruh komponen aplikasi web dapat saling menggunakannya.

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.

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

 view servlet context

Lalu buatlah sebuah servlet baru dengan nama ServletContextClass, jangan lupa untuk menceklis "Add Information to Deployment descriptor (web.xml)" kemudian rubah file ServletContextClass.java menjadi seperti code dibawah ini :
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 fitri
 */
public class ServletContextClass extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST
     * 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("");
            out.println("");
            out.println("");
            out.println("Servlet ServletContextClass");            
            out.println("");
            out.println("");
            out.println("

Servlet ServletContextClass at " + request.getContextPath() + "

"); out.println(""); out.println(""); } } // /** * Handles the HTTP GET 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 POST 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(" Atribut " + attrName + " , nilainya = " + ctx.getAttribute(attrName)); } out.print (" getServletContextName() : " + ctx.getServletContextName()); out.print(" " + ctx.getInitParameter("bhs1")); Enumeration temp2 = ctx.getInitParameterNames(); while (temp.hasMoreElements()) { String paramName = (String) temp2.nextElement(); out.print(" Atribut " + paramName + " , nilainya = " + ctx.getAttribute(paramName)); } out.print(" getServerInfo() :" + ctx.getServerInfo()); out.print(" 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"; } }

Setelah selesai, kita akan lanjutkan membuat ContextListener dengan nama ServletContextListenerClass.
add new di dalam package sebelumnya, pilih Web Application Listener. beri nama ServletContextListenerClass, jangan dulu klik Finish! pada kolom interface to implement, centang context listener. Lalu klik finish dan ubah code yang ada menjadi seperti dibawah 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 fitri
 */



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 dijalankan. Sedangkan ketika servlet-context akan dishutdown maka fungsi contextDestroyed akan dijalankan. Selanjutnya kita buat file seperti ServletContextClass beri nama ServletContextAttributeListenerClass dan pada kolom Interfaces to Implement centang Context Attribute Listener lalu Finish. ubah code file tersebut seperti di bawah 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 fitri
 */


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.

Selanjutnya buat file ServerListener dengan nama ServletRequestListenerClass, pada kolom
Interfaces to Implement pilih Request Listener:
kemudian ubah kode seperti dibawah 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 fitri
 */
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.
    }
}

Selanjutnya buat file ServerListener dengan nama HttpSessionListenerClass, pada kolom Interfaces to Implement pilih HTTP Session Listener:
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 fitri
 */
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.
    }
}
Selanjutnya buat file ServerListener dengan nama HttpSessionAttributeListenerClass, pada kolom Interfaces to Implement pilih HTTP Session Attribute Listener
kemudian ubah code seperti dibawah :

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 fitri
 */
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 sebuah listener. Konfigurasinya kita lakukan di file web.xml, seperti ini:

    
        bhs1
        Java
    
    
        bhs2
        C++
    
    
        bhs3
        C
    
    
        bhs4
        VB.Net
    
    
        bhs5
        JSP
    
    
        ServletContextListener
        ServletContextListenerClass
    
    
        ServletContextAttributeListener
        ServletContextAttributeListenerClass
    
    
        RequestListener
        ServletRequestListenerClass
    
    
        HttpSessionListener
        HttpSessionListenerClass
    
    
        RequestAttributeListener
        HttpSessionAttributeListener
    
    
        RequestAttributeListener
        ServletRequestAttributeListener
    
    
        ServletContext
        ServletContext
    
    
        ServletContextClass
        ServletContextClass
    
    
        ServletContext
        /ServletContext
    
    
        ServletContextClass
        /ServletContextClass
    
    
        
            30
        
    

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

Wassalamualaikum wr. wb


Coming soon : Membuat Servlet Filter dan Servlet Listener Part 3

0 komentar:

Posting Komentar