Archive

Archive for August, 2013

Scripting Element JSP

August 25, 2013 Leave a comment

Pada JSP, kode java dapat ditulis pada JSP page menggunakan tag. Terdapat tiga jenis tag pada JSP yaitu :

  • sciptlet tag

Berikut ini syntax scriptlet tag :

<% //Java Code here %>

Pada tag ini berisi statement Java. Pada tag ini hanya dapat mendeklarasikan variable.

  • expression tag

Berikut ini syntax expression tag:

<%= expression %>

Pada tag ini berisi ekspresi yang dievaluasi, hasil akan diconvert ke String dan ditampilkan sesuai letaknya di JSP file . Ekspresi harus sesuai dengan spesifikasi Java.

  • declaration tag

Berikut ini syntax expression tag:

<%! //Java Code here %>

Tag ini dapat berupa deklarasi variable, method dan class. Berbeda dengan scriptlet tag yang hanya dapat berupa deklarasi variable.

Berikut ini contoh penggunaan tag tersebut :

<%--
    Document   : index
    Created on : Aug 25, 2013, 5:23:05 AM
    Author     : Kukuh Utama
--%>

<%@page import="java.util.Date"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
public class BadIdea {

  public BadIdea() {
  }
  private final int someValue = 42;
  public int getFoo() {
     return someValue;
  }
 
  public Date getDate(){
      Date today = new Date();
      return today;
 }  
 
}

int multipleFunction(int x ){
    return x*x;
}  
%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
          Today is : <%=new BadIdea().getDate()%>
          <br>
          <%
           int result = multipleFunction(100);
           BadIdea object = new BadIdea();
           out.println("SomeValue From BadIdea Class: " +object.someValue);
           out.println("<br>");
           out.println("Multiple Function Result : "+result);          
          %>
    </body>
</html>

Print screen dari contoh diatas :

Result

Result

Semoga bermanfaat.

Referensi : Dari berbagai sumber.

Advertisements

Filter Pada Servlet

August 18, 2013 Leave a comment

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.

Attribute Pada Servlet

August 16, 2013 Leave a comment

Attribute pada servlet memungkinkan data untuk disimpan dan digunakan antar servlet. Ada tiga scope untuk attribute yaitu

  • Request scope ( ServletRequest )
  • Session scope  ( HttpSession )
  • Context scope ( ServletContext )

Method yang digunakan yang digunakan untuk memanipulasi attribute sebagai berikut :

  • public void setAttribute(String name, Object object )
  • public Object getAttribute(String name)
  • public Enumeration getAttributeNames()
  • public void removeAttribue(String name)

Berikut ini contoh penggunaan Attribute untuk request dan session scope.

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 method="post" action="AttributeEx">
              <table>
                     <tr><td>Name</td> <td><input type="text" name="name"></td>  </tr>
                     <tr><td>Mobile</td> <td><input type="text" name="mobile"></td> </tr>
                     <tr><td>Address</td> <td><input type="text" name="address"></td> </tr>
                     <tr><td> <input type="submit" value="Submit"> </td> </tr>
              </table>
        </form>
    </body>
</html>

Nama file : AttributeEx.java ( servlet )

package Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AttributeEx extends HttpServlet {
    
      protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        String name=null;
        Enumeration attributes = request.getAttributeNames();
        try {
           
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ExServlet</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h5>Request Attribute</h5>");
            out.println("<table>");
            out.println("<tr>");
            out.println("<td>Name Attribute </td>");
            out.println("<td>Value Attribute </td>");
            out.println("</tr>");
                while(attributes.hasMoreElements()){
                name = (String) attributes.nextElement();
            out.println("<tr>");
            out.println("<td>"+name+"</td>");
            out.println("<td>"+request.getAttribute(name)+"</td>");
            out.println("</tr>");
            }
            out.println("</table>");
            out.println("<a href=\"ForwardServlet\">To Session Attribute </a>");
            out.println("</body>");
            out.println("</html>");
          } finally {            
              out.close();
          }
    }
      
      
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       String name ="";
       String address ="";
       int mobile = 0;
       
       name = request.getParameter("name");
       address = request.getParameter("address");
       mobile = Integer.parseInt(request.getParameter("mobile"));
       
       request.setAttribute("name", name);
       request.setAttribute("address", address);
       request.setAttribute("mobile", mobile);
       
       HttpSession mySession = request.getSession();
       
       mySession.setAttribute("name", name);
       mySession.setAttribute("address", address);
       mySession.setAttribute("mobile", mobile);
       System.out.println("Wonder Here");
       processRequest(request, response);
    }

}

Nama file : ForwardServlet.java ( servlet )

package Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
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 Kukuh Utama
 */
public class ForwardServlet 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();
        String name = null;
        HttpSession mySession = request.getSession();
        Enumeration attributes = mySession.getAttributeNames();
       
            out.println("<html>");
            out.println("<head>");
            out.println("<title></title>");            
            out.println("</head>");
            out.println("<body>");  
            out.println("<h5>Session Attribute</h5>");
            out.println("<table>");
            out.println("<tr>");
            out.println("<td>Name Attribute </td>");
            out.println("<td>Value Attribute </td>");
            out.println("</tr>");
            while(attributes.hasMoreElements()){
                name = (String) attributes.nextElement();
                if( name.equalsIgnoreCase("name") || name.equalsIgnoreCase("address") || name.equalsIgnoreCase("mobile")){
                out.println("<tr>");
                out.println("<td>"+name+"</td>");
                out.println("<td>"+mySession.getAttribute(name)+"</td>");
                out.println("</tr>");
                }
            }
            out.println("</table>");
            out.println("</body>");
            out.println("</html>");
      
    }

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

File : web.xml

.....

    <servlet>
        <servlet-name>AttributeEx</servlet-name>
        <servlet-class>Action.AttributeEx</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ForwardServlet</servlet-name>
        <servlet-class>Action.ForwardServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AttributeEx</servlet-name>
        <url-pattern>/AttributeEx</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ForwardServlet</servlet-name>
        <url-pattern>/ForwardServlet</url-pattern>
    </servlet-mapping>

.....

Halaman Index :

Index

Index

Halaman  Request Attribute Scope :

Attribute Request Scope

Attribute Request Scope

Halaman  Session Attribute Scope

Attribute Session Scope

Semoga bermanfaat.

Referensi : Dari berbagai sumber.

Session Tracking [ Part 2 ]

August 12, 2013 Leave a comment

HttpSession

HttpSession merupakan interface yang  menyediakan cara untuk melakukan tracking terhadap user. Web Container menggunakan interface ini untuk membuat session antara HTTP client dan HTTP server. Untuk memperoleh session object dapat menggunakan method getSession() dari interface HttpServletRequest.
HttpSession session = request.getSession();

Berikut ini method dari interface HttpSession yang sering digunakan :

  • public Object getAttribute(String name)
  • public Enumeration getAttributeNames()
  • public long getCreationTime()
  • public String getId()
  • public long getLastAccessedTime()
  • public int getMaxInactiveInterval()
  • public void invalidate()
  • public void removeAttribute(String name)
  • public void setAttribute(String name, Object value)
  • public void setMaxInactiveInterval(int interval)

Untuk lebih detail tentang HttpSession dapat dilihat disini .

Berikut ini contoh penggunaan HttpSession

File : Login.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 method="post" action="Login">
               <table>
                     <tr>
                         <td>User Name</td>
                         <td><input type="text" name="username"></td>
                     </tr>
                     <tr>
                         <td>Password</td>
                         <td><input type="password" name="password"> </td>
                     </tr>
                     <tr><td><input type="submit" value="Login"></td></tr>
               </table>
         </form>
    </body>
</html>

File : Login.java ( Servlet )

package Action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Login extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       String username="";
       String password="";
       
       username = request.getParameter("username");
       password = request.getParameter("password");
       
       HttpSession loginSession = request.getSession();
       Date createDateSession = new Date(loginSession.getCreationTime());
       Date lastAccess = new Date(loginSession.getLastAccessedTime());
       loginSession.setAttribute("username", username);
       loginSession.setAttribute("password", password);
       loginSession.setAttribute("createDate", createDateSession);
       loginSession.setAttribute("lastAccess", lastAccess);
       
       RequestDispatcher rd = request.getRequestDispatcher("/Home.jsp");
       
       rd.forward(request, response);
       
    }

}

File : Home.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>
        <% if( session.getAttribute("username") != null && session.getAttribute("password") != null ){ %>
        <h5>Welcome, <%out.println(session.getAttribute("username")); %> </h5>
        <h5>Session ID: <%out.println(session.getId()); %> </h5>
        <h5>Session was created on: <%out.println(session.getAttribute("createDate")); %> </h5>
        <h5>Last access: <%out.println(session.getAttribute("lastAccess")); %> </h5>
        <form action="Logout">
             <table>
                 <tr><td><input type="submit" value="Log Out"></td></tr>
             </table>
        </form>
        <%} else {
          out.println("<b>You have not login yet </b>");
          RequestDispatcher rd = request.getRequestDispatcher("Login.jsp");
          rd.include(request, response);
        }%>
    </body>
</html>

File : Logout.java ( Servlet )

package Action;

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

public class Logout extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       System.out.println("doGet");
       HttpSession loginSession = request.getSession();
       loginSession.invalidate();
       RequestDispatcher rd = request.getRequestDispatcher("/Login.jsp");
       rd.forward(request, response);
    }

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

File : web.xml

....

 <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>Action.Login</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Logout</servlet-name>
        <servlet-class>Action.Logout</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/Login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Logout</servlet-name>
        <url-pattern>/Logout</url-pattern>
    </servlet-mapping>

<session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>Login.jsp</welcome-file>
    </welcome-file-list>

....

Halaman Login:

Login

Login

Halaman Home:

Home

Home

Semoga bermanfaat.

Referensi : Dari berbagai sumber.