Servlet Listener di Java

Sekarang saya akan membahas tentang pembuatan servlet listener di java, project ini merupakan lanjutan dari project yang saya posting kemarin hehe, namun berbeda materi, langsung saja berikut ini cara pembuatannya.

langkah pertama buat project baru, lalu beri nama project MyServletListener 


buka file index.jsp, lalu masukan code sebagai berikut

<%-- 
Document : index
Created on : 18 Jan 15, 15:25:10
Author : M Rizki Fahrizal
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<title>JSP Page</title>



<a href="https://www.blogger.com/getServletContext.do">View Servlet Context</a>
 

Setelah itu klik kanan di source package, buat file web application listener, beri nama HttpSessionAttributeListener.java, centang Http Session Attribute Listener, lalu edit filenya dan masukan code seperti ini : 
/*

 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionBindingEvent;

/**
* Web application lifecycle listener.
*
*
*/
@WebListener()
public class HttpSessionAttributeListener implements javax.servlet.http.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 ditambahkan");
}
}

@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");
}
}

@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");
}
}
}

Setelah itu masih sama, buat file web application listener, beri nama HttpSessionListenerClass.java, jangan lupa centang Http Session Listener

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

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

/**
* Web application lifecycle listener.
*
* @author M Rizki Fahrizal
*/
@WebListener()
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");
}
}

@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");
}
}
}

Sekarang buat file web application listener, beri nama ServletContextAttributeListenerClass.java, jangan lupa centang Context Attribute Listener, lalu masukan script seperti berikut :  
/*

 * To change this template, choose Tools | Templates
* and open the template in the editor.
*/

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

/**
* Web application lifecycle listener.
*
* @author M Rizki Fahrizal
*/
@WebListener()
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");
}
}

@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");
}
}

@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");
}
}
}

Setelah itu, buat file servlet, beri nama ServletContextClass.java, lalu masukan script berikut : 

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

import com.sun.jmx.snmp.Enumerated;
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 M Rizki Fahrizal
*/
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");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("");
out.println("");
out.println("");
out.println("<title>Servlet ServletContextClass</title>");
out.println("");
out.println("");
out.println("<h1>
Servlet ServletContextClass at " + request.getContextPath() + "</h1>
");
out.println("");
out.println("");
} finally {
out.close();
}
}

// <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
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);

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("
Attribut " + attrName +", nilainya = "+ ctx.getAttribute(attrName));
}

out.print("

getServletContextName() : "+ctx.getServletContextName());

out.print("
" + ctx.getInitParameter("bhs1"));
Enumeration temp2 = ctx.getInitParameterNames();
while(temp2.hasMoreElements()){
String paramName = (String) temp2.nextElement();
out.print("
Attribut " +paramName+", nilainya = "+ ctx.getInitParameter(paramName));

}

out.print("
getServerInfo() : "+ ctx.getServerInfo());
out.print("
getRealPath() : "+ ctx.getRealPath(""));
ctx.log("Hello Word");

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);

}

/**
* 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
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}

Jika sudah, buat file web application listener, beri nama ServletContextListenerClass.java, jangan lupa centang Context Listenernya, lalu masukan kode berikut :

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

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

/**
* Web application lifecycle listener.
*
* @author M Rizki Fahrizal
*/
@WebListener()
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");
}
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
if(ctx != null){
ctx.log("Context : " + ctx.getServletContextName()+"sudah dihancurkan");
}
}
}

Terakhir gan, buat file web appication listener, beri nama ServletRequestListener.java, jangan lupa centang Request Listener, lalu masukan script sebagai berikut : 

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

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

/**
* Web application lifecycle listener.
*
* @author M Rizki Fahrizal
*/
@WebListener()
public class ServletRequestListenerClass implements ServletRequestListener {

@Override
public void requestDestroyed(ServletRequestEvent sre) {
ServletContext ctx = sre.getServletContext();
if(ctx != null){
ctx.log("Context "+ ctx.getServletContextName() + ", "
+ "attribute "+sre.getServletRequest()+ "sudah dihancurkan");
}
}

@Override
public void requestInitialized(ServletRequestEvent sre) {
ServletContext ctx = sre.getServletContext();
if(ctx != null){
ctx.log("Context "+ ctx.getServletContextName() + ", "
+ "attribute "+sre.getServletRequest()+ "sudah diinisialisasi");
}
}
}

Terakhir gan seriusan, ubah file web.xml di folder webinf, edit scriptnya seperti berikut : 

<web-app version="3.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.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>ServletContextAttributeListener</listener-class>
</listener>
<listener>
<description>RequestListener</description>
<listener-class>ServletRequestListenerClass</listener-class>
</listener>
<listener>
<description>HttpSessionListener</description>
<listener-class>HttpSessionListenerClass</listener-class>
</listener>
<listener>
<description>RequestAttributeListener</description>
<listener-class>HttpSessionAttributeListenerClass</listener-class>
</listener>
<listener>
<description>RequestAttributeListener</description>
<listener-class>ServletRequestAttributeListener</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>

Sudah selesai gan, silahkan coba agan run dan buktikan hasilnya B| thankyou udah mampir ke blog ane gan dan jangan lupa kalo ada yang ingin ditanyakan tinggalkan jejak.

Leave a Reply

Your email address will not be published. Required fields are marked *