Servlet Context dan Listener DB di Java

Melanjutkan dari project artikel sebelumnya gan, kali ini saya kan membuat listener file dengan menggunakan db, mari langsung kita ke projectnya gan, sebelumnya saya disini menggunakan editor netbeans v 7.3.

Sama seperti project sebelumnya, buat project baru, beri nama ServletListenerDB
Setelah itu, klik kanan di source package, buat file web application listener,
berinama AppContextAttributeListener.java, jangan lupa centang Context Attribute Listener,
lalu edit scriptnya seperti ini : 


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

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

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

@Override
public void attributeAdded(ServletContextAttributeEvent event) {
System.out.println("ServletContext attribute added :: {" + event.getName()+", "+ event.getValue()+"}");
}

@Override
public void attributeRemoved(ServletContextAttributeEvent event) {
System.out.println("ServletContext attribute replaced :: {" + event.getName()+", "+ event.getValue()+"}");
}

@Override
public void attributeReplaced(ServletContextAttributeEvent event) {
System.out.println("ServletContext attribute removed :: {" + event.getName()+", "+ event.getValue()+"}");
}
}

Setelah itu buat file web application listener, beri nama AppContextListener.java, jangan lupa centang Context Listener, lalu masukan script berikut  ini :

/*
* 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 AppContextListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
String url = ctx.getInitParameter("DBURL");
String u = ctx.getInitParameter("DBUSER");
String p = ctx.getInitParameter("DBPWD");

DBConnectionManager dbManager = new DBConnectionManager(url, u, p);
ctx.setAttribute("DBManager", dbManager);
System.out.println("Database connection initialized for Application");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();

DBConnectionManager dbManager = (DBConnectionManager) ctx.getAttribute("DBManager");
dbManager.closeConnection();
System.out.println("Database connection closed for Application");

}
}

Setelah itu buat file web application listener, beri nama MyServletRequestListener.java, jangan lupa centang Request Listener, lalu masukan script seperti ini : 

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

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

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

@Override
public void requestDestroyed(ServletRequestEvent sre) {
ServletRequest servletRequest = sre.getServletRequest();
System.out.println("ServletRequest destroyed. Remote IP = " + servletRequest.getRemoteAddr());
}

@Override
public void requestInitialized(ServletRequestEvent sre) {
ServletRequest servletRequest = sre.getServletRequest();
System.out.println("ServletRequest initialized. Remote IP = " + servletRequest.getRemoteAddr());
}
}

Setelah itu buat file web application listener, beri nama MySessionListener.java, centang Http Session Listener, lalu edit seperti ini : 

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

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 MySessionListener implements HttpSessionListener {

@Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("Session Created :: ID="+ se.getSession().getId());
}

@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Session Destroyed:: ID="+ se.getSession().getId());
}
}

Lalu, buat file servlet, beri nama MyServlet.java, lalu edit seperti ini :

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

import java.io.IOException;
import java.io.PrintWriter;
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 MyServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
/**
* 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 MyServlet</title>");
out.println("");
out.println("");
out.println("<h1>
Servlet MyServlet 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);

ServletContext ctx = request.getServletContext();
ctx.setAttribute("User", "Maulana");
String user = (String) ctx.getAttribute("user");
ctx.removeAttribute("User");

HttpSession session = request.getSession();
session.invalidate();

PrintWriter out = response.getWriter();
out.write("H1 " + user);
}

/**
* 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>
}

Terakhir gan buat file baru, beri nama DBConnectionManager.java, lalu masukan scriptnya seperti ini : 

import java.sql.Connection;

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

/**
*
* @author M Rizki Fahrizal
*/
public class DBConnectionManager {
private String dbURL;
private String user;
private String password;
private Connection con;

public DBConnectionManager(String url, String u, String p){
this.dbURL = url;
this.user = u;
this.password = p;
}

public Connection getConnection(){
return this.con;
}

public void closeConnection(){

}
}

selesai juga gan akhirnya 😀 silahkan tinggal kalian coba run, apabila ada yang ingin ditanyakan silahkan untuk meninggalkan di komentar, thank you udah mampir ke blog ane gan.

Leave a Reply

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