Servlet Filter di Java

Hallo sudah lama saya ga post lagi gan, ok kali ini saya akan memposting cara servlet filter di java, servlet filter ini merupakan salah satu tugas mata kuliah saya, ok langsung saja Berikut ini penggunaan Filter di Java Servlet menggunakan netbeans.
Buat lah sebuah web application dengan nama filterLogin. Adapun struktur aplikasinya sebagai berikut :



Setelah struktur project kalian seperti diatas maka sekarang kita masukan script di index.html, berikut isi scriptnya.

index.html

<title>Filter Login</title>

<form action="LoginServlet" method="post">
Username: <input name="user" type="text">


Password: <input name="pwd" type="password">


<input type="submit" value="Login">
</form>

Selanjutnya buka CheckoutPage.jsp  lalu masukan script berikut ini.

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

<title>JSP Page</title>

<%
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>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout">
</form>

lanjut gan buka file LoginSuccess.jsp  lalu masukan scriptnya seperti dibawah: 

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

<title>JSP Page</title>

<%
//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>
<%=userName%>, Login successful. Your Session ID=<%=sessionID%></h3>
User=<%=user%>


<a href="https://www.blogger.com/CheckoutPage.jsp">Checkout Page</a>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout">
</form>

Selanjutnya pilih file AuthenticationFilter.java, lalu isikan script berikut.

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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthenticationFilter implements Filter {
private static final boolean DEBUG = true;
private FilterConfig filterConfig = null;

public AuthenticationFilter(){}

private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
if (DEBUG) {
log("AuthenticationFilter:doBeforeProcessing");
}
}

private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (DEBUG) {
log("AuthenticationFilter:doAfterProcessing");
}
}

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 {
chain.doFilter(request, response);
}

} catch (Throwable t){
problem = t;
t.printStackTrace();
}

doAfterProcessing(request, response);

if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}

public FilterConfig getFilterConfig(){
return (this.filterConfig);
}

public void setFilterConfig(FilterConfig filterConfig){
this.filterConfig = filterConfig;
}

public void destroy(){

}

public void init(FilterConfig filterConfig){
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (DEBUG) {
log("AuthenticationFilter:Initializing filter");
}
}
}

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("nn<title>Error</title>nnn");
pw.print("<h1>
The resource did not process correctly</h1>
n<pre>n");
pw.print(stackTrace);
pw.print("</pre>
n<\html>"); // N0I18N
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);
}
}

lanjut gan ketikan script berikut di LoginServlet.java

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;

public class LoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;
private final String userID = "admin";
private final String password = "123";
/**
* 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("");
out.println("");
out.println("");
out.println("<title>Servlet LoginServlet</title>");
out.println("");
out.println("");
out.println("<h1>
Servlet LoginServlet at " + request.getContextPath() + "</h1>
");
out.println("");
out.println("");
}
}

// <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
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("<span style="color: red;">Either user name or password is wrong.</span>");
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>

}

Selanjutnya masuk ke file LogoutServlet.java dan masukan code sebagai berikut : 

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

/**
*
*
*/
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");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("");
out.println("");
out.println("");
out.println("<title>Servlet LogoutServlet</title>");
out.println("");
out.println("");
out.println("<h1>
Servlet LogoutServlet at " + request.getContextPath() + "</h1>
");
out.println("");
out.println("");
}
}

// <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);
response.setContentType("text/html");
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>

}

Masuk ke file RequestLoggingFilter.java dan ketikan script berikut : 

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.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;
private FilterConfig filterConfig = null;

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

private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
if (DEBUG) {
log("RequestLoggingFilter:doAfterProcessing");
}
}

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){
problem = t;
t.printStackTrace();
}

doAfterProcessing(request, response);

if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}



public FilterConfig getFilterConfig(){
return (this.filterConfig);
}

public void setFilterConfig(FilterConfig filterConfig)
{
this.filterConfig = filterConfig;
}

public void destroy(){}

public void init(FilterConfig filterConfig){
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (DEBUG) {
log("RequestLoggingFilter:Initializing filter");
}
}
}

@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("nn<title>Error</title>nnn");
pw.print("<h1>
The resource did not process correctly</h1>
n<pre>n");
pw.print(stackTrace);
pw.print("</pre>
n");
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);
}
}

</string>

Sekian gan pembuatan servlet filter dengan java semoga membantu dan bermanfaat, thank you udah berkunjung ke blog ane.

Leave a Reply

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