Kali ini saya akan kembali membahas tentang materi kuliah yang saya dapatkan di kampus. Dan materi yang saya dapat beberapa minggu yang lalu adalah : Java Servlet Filter
Singkatnya, filter adalah sebuah komponen yang dapat menangani request atau response yang harus atau tidak harus dilakukan/diterima oleh client. Secara normal, filter digunakan untuk membungkus dan memanipulasi request, response, atau nilai header sebelum dan setelah eksekusi target.
Baiklah, eksekusi!
Harap diingat : Siapkan software seperti Netbeans dan JDK (Java Development Kit) untuk membuat aplikasi ini. Dalam pengerjaannya, saya menggunakan Netbeans 7.1.
Selanjutnya, masuk ke index.html dan ubahlah script menjadi seperti ini :
PART 2 : LoginServlet.java
Singkatnya, filter adalah sebuah komponen yang dapat menangani request atau response yang harus atau tidak harus dilakukan/diterima oleh client. Secara normal, filter digunakan untuk membungkus dan memanipulasi request, response, atau nilai header sebelum dan setelah eksekusi target.
Baiklah, eksekusi!
Harap diingat : Siapkan software seperti Netbeans dan JDK (Java Development Kit) untuk membuat aplikasi ini. Dalam pengerjaannya, saya menggunakan Netbeans 7.1.
PART 1 : Membuat Project dan Mengubah halaman index.html
Beginilah langkah membuat project baru :
- Buka Netbeans yang telah diinstal.
- Pilih menu "File" , lalu klik "New Project" untuk membuat project baru.
- Setelah itu, akan muncul aplikasi jenis apa yang akan kita buat.
- Pilih "Java Web" -> "Web Application", lalu klik "Next" untuk melanjutkan.
Berilah nama project tersebut "filterlogin". Jika sudah, maka struktur project filenya akan seperti gambar di bawah ini
Selanjutnya, masuk ke index.html dan ubahlah script menjadi seperti ini :
PART 2 : LoginServlet.java
Bagian kedua adalah mengubah isi file "LoginServlet.java". LoginServlet.java berfungsi sebagai script yang menjalankan segala hal tentang login. Ubahlah scriptnya menjadi 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.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author uplink 05
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "fujana";
private final String password = "00513112107";
/**
* 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("<html>");
out.println("<head>");
out.println("<title>Servlet LoginServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LoginServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} 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);
}
/**
* 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);
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if (userID.equals(user) && password.equals(pwd)) {
HttpSession session = request.getSession();
session.setAttribute("user", "Pankaj");
//setting session to expiry in 30 mins 88
session.setMaxInactiveInterval(30 * 60);
Cookie userName = new Cookie("user", user);
userName.setMaxAge(30 * 60);
response.addCookie(userName);
response.sendRedirect("LoginSuccess.jsp");
} else {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out = response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
PART 3 : LoginSuccess.jsp
Bagian ketiga adalah mengubah isi file "LoginSuccess.jsp". LoginSuccess.jsp berfungsi sebagai script yang menjalankan ketika user berhasil login. Ubah scriptnya menjadi seperti ini :
<%--
Document : LoginSuccess
Created on : 14-Jan-2015, 21:04:02
Author : uplink 05
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
//allow access only if session exists
String user = (String) session.getAttribute("user");
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("user")) {
userName = cookie.getValue();
}
if (cookie.getName().equals("JSESSIONID")) {
sessionID = cookie.getValue();
}
}
}
%>
<h3>Hi <%=userName%>, Login successful. Your Session ID=<%=sessionID%></h3>
<br>
User=<%=user%>
<br>
<a href="CheckoutPage.jsp">Checkout Page</a>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
PART 4 : LogoutServlet.jsp
Bagian keempat adalah mengubah isi file "LogoutServlet.jsp". LogoutServlet.jsp berfungsi sebagai script yang menjalankan ketika usermelakukan logout. Ubah scriptnya menjadi 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.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author mcs
*/
public class LogoutServlet 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("<html>");
out.println("<head>");
out.println("<title>Servlet LogoutServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LogoutServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} 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);
}
/**
* 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);
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("JSESSIONID")) {
System.out.println("JSESSIONID=" + cookie.getValue());
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User=" + session.getAttribute("user"));
if (session != null) {
session.invalidate();
}
response.sendRedirect("index.html");
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
* 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.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author mcs
*/
public class LogoutServlet 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("<html>");
out.println("<head>");
out.println("<title>Servlet LogoutServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet LogoutServlet at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
} 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);
}
/**
* 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);
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("JSESSIONID")) {
System.out.println("JSESSIONID=" + cookie.getValue());
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User=" + session.getAttribute("user"));
if (session != null) {
session.invalidate();
}
response.sendRedirect("index.html");
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
PART 5 : RequestLoggingFilter.java
Bagian kelima adalah mengubah isi file "RequestLoggingFilter.java". RequestLoggingFilter.java berfungsi sebagai script yang menjalankan ketika user melakukan logout. Ubah scriptnya 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.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class RequestLoggingFilter implements Filter {
private static final boolean debug = true;
// The filter configuration object we are associated with. If
// this value is null, this filter instance is not currently
// configured.
private FilterConfig filterConfig = null;
//private ServletContext context;
public RequestLoggingFilter() {
}
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("RequestLoggingFilter:DoBeforeProcessing");
}
HttpServletRequest req = (HttpServletRequest) request;
Enumeration<String> params = req.getParameterNames();
while (params.hasMoreElements()) {
String name = params.nextElement();
String value = request.getParameter(name);
log(req.getRemoteAddr() + "::Request Params::{" + name + "=" + value + "}");
}
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
log(req.getRemoteAddr() + "::Cookie::{" + cookie.getName() + "," + cookie.getValue() + "}");
}
}
// Write code here to process the request and/or response before
// the rest of the filter chain is invoked.
// For example, a logging filter might log items on the request object,
// such as the parameters.
/*
for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
String values[] = request.getParameterValues(name);
int n = values.length;
StringBuffer buf = new StringBuffer();
buf.append(name);
buf.append("=");
for(int i=0; i < n; i++) {
buf.append(values[i]);
if (i < n-1)
buf.append(",");
}
log(buf.toString());
}
*/
}
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("RequestLoggingFilter:DoAfterProcessing");
}
// Write code here to process the request and/or response after
// the rest of the filter chain is invoked.
// For example, a logging filter might log the attributes on the
// request object after the request has been processed.
/*
for (Enumeration en = request.getAttributeNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
Object value = request.getAttribute(name);
log("attribute: " + name + "=" + value.toString());
}
*/
// For example, a filter might append something to the response.
/*
PrintWriter respOut = new PrintWriter(response.getWriter());
respOut.println("<P><B>This has been appended by an intrusive filter.</B>");
*/
}
/**
*
* @param request The servlet request we are processing
* @param response The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (debug) {
log("RequestLoggingFilter:doFilter()");
}
doBeforeProcessing(request, response);
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch (Throwable t) {
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
// If there was a problem, we want to rethrow it if it is
// a known type, otherwise log it.
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
/**
* Return the filter configuration object for this filter.
*/
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
/**
* Set the filter configuration object for this filter.
*
* @param filterConfig The filter configuration object
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* Destroy method for this filter
*/
public void destroy() {
}
/**
* Init method for this filter
*/
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (debug) {
log("RequestLoggingFilter:Initializing filter");
}
}
}
/**
* Return a String representation of this object.
*/
@Override
public String toString() {
if (filterConfig == null) {
return ("RequestLoggingFilter()");
}
StringBuffer sb = new StringBuffer("RequestLoggingFilter(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private void sendProcessingError(Throwable t, ServletResponse response) {
String stackTrace = getStackTrace(t);
if (stackTrace != null && !stackTrace.equals("")) {
try {
response.setContentType("text/html");
PrintStream ps = new PrintStream(response.getOutputStream());
PrintWriter pw = new PrintWriter(ps);
pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n");
// PENDING! Localize this for next official release
pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
pw.print(stackTrace);
pw.print("</pre></body>\n</html>"); //NOI18N
pw.close();
ps.close();
response.getOutputStream().close();
} catch (Exception ex) {
}
} else {
try {
PrintStream ps = new PrintStream(response.getOutputStream());
t.printStackTrace(ps);
ps.close();
response.getOutputStream().close();
} catch (Exception ex) {
}
}
}
public static String getStackTrace(Throwable t) {
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex) {
}
return stackTrace;
}
public void log(String msg) {
filterConfig.getServletContext().log(msg);
}
}
PART 6 : AuthenticationFilter.java
Bagian keenam adalah mengubah isi file "AuthenticationFilter.java". AuthenticationFilter.java berfungsi sebagai script yang menjalankan ketika user melakukan logout. Ubah scriptnya 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.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author uplink 05
*/
public class AuthenticationFilter extends HttpServlet {
private static final boolean debug = true;
// The filter configuration object we are associated with. If
// this value is null, this filter instance is not currently
// configured.
private FilterConfig filterConfig = null;
public AuthenticationFilter() {
}
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("AuthenticationFilter:DoBeforeProcessing");
}
// Write code here to process the request and/or response before
// the rest of the filter chain is invoked.
// For example, a logging filter might log items on the request object,
// such as the parameters.
/*
for (Enumeration en = request.getParameterNames();
en.hasMoreElements(); ) {
String name = (String)en.nextElement();
String values[] = request.getParameterValues(name);
int n = values.length;
StringBuffer buf = new StringBuffer();
buf.append(name);
buf.append("=");
for(int i=0; i < n; i++) {
buf.append(values[i]);
if (i < n-1)
buf.append(",");
}
log(buf.toString());
}
*/
}
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (debug) {
log("AuthenticationFilter:DoAfterProcessing");
}
// Write code here to process the request and/or response after
// the rest of the filter chain is invoked.
// For example, a logging filter might log the attributes on the
// request object after the request has been processed.
/*
for (Enumeration en = request.getAttributeNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
Object value = request.getAttribute(name);
log("attribute: " + name + "=" + value.toString());
}
*/
// For example, a filter might append something to the response.
/*
PrintWriter respOut = new PrintWriter(response.getWriter());
respOut.println("<P><B>This has been appended by an intrusive filter.</B>");
*/
}
/**
* 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
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (debug) {
log("AuthenticationFilter:doFilter()");
}
doBeforeProcessing(request, response);
Throwable problem = null;
try {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
log("Requested Resource::" + uri);
HttpSession session = req.getSession(false);
if (session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet"))) {
log("Unauthorized access request");
res.sendRedirect("index.html");
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
} catch (Throwable t) {
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
// If there was a problem, we want to rethrow it if it is
// a known type, otherwise log it.
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
/**
* Return the filter configuration object for this filter.
*/
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
/**
* Set the filter configuration object for this filter.
*
* @param filterConfig The filter configuration object
*/
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
/**
* Destroy method for this filter
*/
public void destroy() {
}
/**
* Init method for this filter
*/
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (debug) {
log("AuthenticationFilter:Initializing filter");
}
}
}
/**
* Return a String representation of this object.
*/
@Override
public String toString() {
if (filterConfig == null) {
return ("AuthenticationFilter()");
}
StringBuffer sb = new StringBuffer("AuthenticationFilter(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private void sendProcessingError(Throwable t, ServletResponse response) {
String stackTrace = getStackTrace(t);
if (stackTrace != null && !stackTrace.equals("")) {
try {
response.setContentType("text/html");
PrintStream ps = new PrintStream(response.getOutputStream());
PrintWriter pw = new PrintWriter(ps);
pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n");
//NOI18N
// PENDING! Localize this for next official release
pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
pw.print(stackTrace);
pw.print("</pre></body>\n</html>");
//NOI18N
pw.close();
ps.close();
response.getOutputStream().close();
} catch (Exception ex) {
}
} else {
try {
PrintStream ps = new PrintStream(response.getOutputStream());
t.printStackTrace(ps);
ps.close();
response.getOutputStream().close();
} catch (Exception ex) {
}
}
}
public static String getStackTrace(Throwable t) {
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex) {
}
return stackTrace;
}
public void log(String msg) {
filterConfig.getServletContext().log(msg);
}
}
PART 7 : Checkout.jsp
Bagian ketujuh adalah mengubah isi file "Checkout.jsp". Checkout.jsp berfungsi sebagai script yang menjalankan ketika user melakukan logout. Ubah scriptnya menjadi seperti ini :
<%--
Document : CheckoutPage
Created on : 14-Jan-2015, 21:12:10
Author : uplink 05
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("user")) {
userName = cookie.getValue();
}
}
}
%>
<h3>Hi <%=userName%>, do the checkout.</h3>
<br>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
PART 8 : web.xml
Bagian terakhir ! ubah isi file "web.xml". web.xml berfungsi sebagai script yang menjalankan ketika user melakukan logout. Ubah scriptnya menjadi seperti ini :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<filter>
<filter-name>RequestLoggingFilter</filter-name>
<filter-class>RequestLoggingFilter</filter-class>
</filter>
<filter>
<filter-name>AuthenticationFilter</filter-name>
<filter-class>AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestLoggingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>AuthenticationFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>