Home > Java and Web > Filter Pada Servlet

Filter Pada Servlet

Filter adalah komponen yang terdapat pada spesifikasi servlet version 2.3 yang berfungsi untuk  men-intercept  request dari client sebelum mereka mengakses resource di server dan untuk memanipulasi response dari server sebelum dikirim kembali ke client. Filter API terdiri dari tiga interface yang terletak di javax.servlet package yaitu :

  • Filter Interface

Untuk membuat filter perlu untuk implement interface ini. Filter interface menyediakan tiga method life cycle untuk filter yang dibuat.

1. void destroy()

2. void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

3. void init(FilterConfig filterConfig)

Untuk detail Filter interface dapat dibaca disini.

  • FilterChain Inteface

Object dari FilterChain berfungsi untuk meng-execute filter atau resource yang lain. FilterChain interface hanya terdiri dari satu method yaitu :

1. void doFilter(ServletRequest request, ServletResponse response)

Untuk detail FilterChain interface dapat dibaca disini.

  • FilterConfig Interface

Object dari FilterConfig digunakan oleh web container untuk mengirimkan value pada saat inisialisasi filter. FilterConfig interface terdiri dari empat method yaitu :

1.String getFilterName()

2.String getInitParameter(String name)

3.Enumeration getInitParameterNames()

4.ServletContext getServletContext()

Untuk detail FilterConfig interface dapat dibaca disini.

Berikut ini contoh penggunaaan filter pada servlet dengan case filter menambahkan attribute waktu register dan IP address dari request:

Nama file : index.jsp

<%@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>
        <form action="Register" method="GET">
              <table>
                  <tr>
                       <td>Name</td>
                       <td><input type="text" name="name"></td>
                  </tr>
                  
                   <tr>
                       <td>Address</td>
                       <td><input type="text" name="address"></td>
                  </tr>
                   <tr>
                       <td>Mobile</td>
                       <td><input type="text" name="mobile"></td>
                  </tr>
                  
                  <tr>
                       <td>Password</td>
                       <td><input type="password" name="password"></td>
                  </tr>
                  <tr>
                      <td><input type="submit" value="Submit"></td>
                  </tr>
              </table>
        </form>
    </body>
</html>

Nama file : Register.java ( servlet )

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Kukuh Utama
 */
public class Register extends HttpServlet {
 
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            System.out.println("do Get");
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            try {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Filter Example</title>");            
                out.println("</head>");
                out.println("<body>");
                out.println("<h4>Parameter and Attribute Request</h4>");
                out.println("<table>");
                
                out.println("<tr>");
                out.println("<td>");
                out.println("Name");
                out.println("</td>");
                out.println("<td>");
                out.println(request.getParameter("name"));
                out.println("</td>");
                out.println("</tr>");
                
                out.println("<tr>");
                out.println("<td>");
                out.println("Address");
                out.println("</td>");
                out.println("<td>");
                out.println(request.getParameter("address"));
                out.println("</td>");
                out.println("</tr>");
                
                out.println("<tr>");
                out.println("<td>");
                out.println("Mobile");
                out.println("</td>");
                out.println("<td>");
                out.println(request.getParameter("mobile"));
                out.println("</td>");
                out.println("</tr>");
                
                out.println("<tr>");
                out.println("<td>");
                out.println("Password");
                out.println("</td>");
                out.println("<td>");
                out.println(request.getParameter("password"));
                out.println("</td>");
                out.println("</tr>");
                
                out.println("<tr>");
                out.println("<td>");
                out.println("IP Address");
                out.println("</td>");
                out.println("<td>");
                out.println(request.getAttribute("IPAddress"));
                out.println("</td>");
                out.println("</tr>");
                
                out.println("<tr>");
                out.println("<td>");
                out.println("Time Register");
                out.println("</td>");
                out.println("<td>");
                out.println(request.getAttribute("timeReg"));
                out.println("</td>");
                out.println("</tr>");
                
                out.println("</table>");
                out.println("</body>");
                out.println("</html>");
            } finally {            
                out.close();
            }           
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            System.out.println("do Post");
    }
}

Nama file : RegisterFilter.java ( filter )

import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author Kukuh Utama
 */
public class RegisterFilter implements Filter {
    
    private FilterConfig filterConfig = null;
    
    public RegisterFilter() {
        System.out.println("Construct Object");
    }    
    
    private void doBeforeProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
      
      System.out.println("do Before");
      request.setAttribute("timeReg", new Date());
      request.setAttribute("IPAddress", request.getRemoteAddr());
     
    }    
    
    private void doAfterProcessing(ServletRequest request, ServletResponse response)
            throws IOException, ServletException {
        
        System.out.println("do After");
        request.removeAttribute("timeReg");
        request.removeAttribute("IPAddress");
     
    }

 
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        doBeforeProcessing(request, response);
        
        System.out.println("Chain RegisterFilter Filter");
        chain.doFilter(request, response);
       
        doAfterProcessing(request, response);

    }

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

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

    public void destroy() {      
        System.out.println("Filter is destroyed");
        //add code to release any resource
    }

   
    public void init(FilterConfig filterConfig) {        
        this.filterConfig = filterConfig;
        System.out.println("Init.....");
        //Get init parameter
    }
 
}

Nama file : web.xml

.....

 <filter>
        <filter-name>RegisterFilter</filter-name>
        <filter-class>FilterPackage.RegisterFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>RegisterFilter</filter-name>
        <url-pattern>/Register</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>Register</servlet-name>
        <servlet-class>ServletPackage.Register</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Register</servlet-name>
        <url-pattern>/Register</url-pattern>
    </servlet-mapping>

.....

Halaman Index

index

index

Halaman Result

result

result

Semoga bermanfaat.

Referensi : Dari berbagai sumber.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: