Thursday, August 5, 2010

JSP TAGS Tutorial

This article explains about the various tags available in JSP with suitable examples. In JSP tags can be divided into 4 different types. These are:


1. Directives
Directives are used to import packages, define error handling pages or the session information of the JSPpage.

2. Declarations
Declarations tags are used for defining the functions and variables to be used in the JSP.

3. Scriplets
Using scriplets tags we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine.

4. Expressions
We can use this expressions tags to output any data on the generated page. These data are automatically converted to string and printed on the output stream.


Now we will examine each tags in details with examples. JSP DIRECTIVES

Syntax of JSPdirectives is:

<%@directive attribute="value" %>

Where directive may be:

1. page: page is used to provide the information about it.
Example: <%@page language="java" %>

2. include: include is used to include a file in the JSPpage.
Example: <%@ include file="/header.jsp" %>

3. taglib: taglib is used to use the custom tags in the JSPpages (custom tags allows us to defined our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>


and attribute may be:

1. language="java"
This tells the server that the page is using the java language. Current JSP specification supports only java language.
Example: <%@page language="java" %>

2. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages.
Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %>

3. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this value is true.
Example: <%@page language="java" session="true" %>

4. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>

5. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %>

Wednesday, August 4, 2010

Java Servlet Example / Sample code to read and create session objects

package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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;

/**
 * Servlet implementation class SessionExample
 */

public class SessionExample extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException {
  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<body bgcolor=\"white\">");
  out.println("<head>");

  String title = "Session Example";
  out.println("<title>" + title + "</title>");
  out.println("</head>");
  out.println("<body>");


  out.println("<h3>" + title + "</h3>");

  HttpSession session = request.getSession(true);
  out.println("Session Id: " + session.getId());
  out.println("<br>");
  out.println("Created On: ");
  out.println(new Date(session.getCreationTime()) + "<br>");
  out.println("Last Accessed On: ");
  out.println(new Date(session.getLastAccessedTime()));

  String dataName = request.getParameter("dataname");
  String dataValue = request.getParameter("datavalue");
  if (dataName != null && dataValue != null) {
   session.setAttribute(dataName, dataValue);
  }

  out.println("<P>");
  out.println( "Session Data: <br>");
  Enumeration<?> names = session.getAttributeNames();
  while (names.hasMoreElements()) {
   String name = (String) names.nextElement();
   String value = session.getAttribute(name).toString();
   out.println(name+ " = "
     + value + "<br>");
  }

  out.println("<P>");
  out.print("<form action=\"");
  out.print(response.encodeURL("SessionExample"));
  out.print("\" ");
  out.println("method=POST>");
  out.println("Name of Session Attribute: ");
  out.println("<input type=text size=20 name=dataname>");
  out.println("<br>");
  out.println("Value of Session Attribute: ");
  out.println("<input type=text size=20 name=datavalue>");
  out.println("<br>");
  out.println("<input type=submit>");
  out.println("</form>");

  out.println("<P>GET based form:<br>");
  out.print("<form action=\"");
  out.print(response.encodeURL("SessionExample"));
  out.print("\" ");
  out.println("method=GET>");
  out.println("Name of Session Attribute: ");
  out.println("<input type=text size=20 name=dataname>");
  out.println("<br>");
  out.println("Value of Session Attribute: ");
  out.println("<input type=text size=20 name=datavalue>");
  out.println("<br>");
  out.println("<input type=submit>");
  out.println("</form>");

  out.print("<p><a href=\"");
  out.print(response
    .encodeURL("SessionExample?dataname=urlEncodedSessionName&datavalue=urlEncodedSessionValue"));
  out.println("\" >URL encoded </a>");

  out.println("</body>");
  out.println("</html>");

  out.println("</body>");
  out.println("</html>");
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws IOException, ServletException {
  doGet(request, response);
 }

}

Java Servlet Example / Sample Code to set and read Cookies and display cookies in browser

Following Sample Code / Example will ask user to input cookies name and value form browser and then as response list of shows all the cookies set.

package test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<body bgcolor=\"white\">");
  out.println("<head>");

  String title = "Cookie Example";
  out.println("<title>" + title + "</title>");
  out.println("</head>");
  out.println("<body>");
  // set a cookie
  
  String name = request.getParameter("cookieName");
  if (name != null && name.length() > 0) {
   String value = request.getParameter("cookieValue");
   Cookie c = new Cookie(name, value);
   response.addCookie(c);
  }

  // print out cookies
  out.print("List of cookies:");
  Cookie[] cookies = request.getCookies();
  for (int i = 0; i < cookies.length; i++) {
   Cookie c = cookies[i];
   String cookieName = c.getName();
   String value = c.getValue();
   out.println("<br/>");
   out.println(cookieName + " = " + value);
  }


  out.println("<P>");
  out.println("Create a cookie to send to your browser" + "<br>");
  out.print("<form action=\"");
  out.println("CookieExample\" method=POST>");
  out.print("Cookie Name:  ");
  out.println("<input type=text length=20 name=cookieName><br>");
  out.print("Cookie Value  ");
  out.println("<input type=text length=20 name=cookieValue><br>");
  out.println("<input type=submit></form>");

  out.println("</body>");
  out.println("</html>");

 }

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  doGet(request, response);

 }

}

Java Servlet Example / Sample code to reqd Request Parameters using HttpServletRequest from doGet, doPost or do* methods

Following example / sample code for Java Servlet takes First Name and Last Name form the browser as request and reads request parameters and displays back to browser using HttpServletResponse.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestParamExample extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Request Parameters Example</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3>Request Parameters Example</h3>");
        out.println("Parameters in this request:<br>");
        if (firstName != null || lastName != null) {
            out.println("First Name:");
            out.println(" = " + HTMLFilter.filter(firstName) + "<br>");
            out.println("Last Name:");
            out.println(" = " + HTMLFilter.filter(lastName));
        } else {
            out.println("No Parameters, Please enter some");
        }
        out.println("<P>");
        out.print("<form action=\"");
        out.print("RequestParamExample\" ");
        out.println("method=POST>");
        out.println("First Name:");
        out.println("<input type=text size=20 name=firstname>");
        out.println("<br>");
        out.println("Last Name:");
        out.println("<input type=text size=20 name=lastname>");
        out.println("<br>");
        out.println("<input type=submit>");
        out.println("</form>");
        out.println("</body>");
        out.println("</html>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse res)
    throws IOException, ServletException
    {
        doGet(request, response);
    }
}

Java Servlet Sample Code / Example to read Request Header

This sample code extracts all headers form the request and sends back to response.

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestHeaderExample extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Enumeration e = request.getHeaderNames();
        while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            String value = request.getHeader(name);
            out.println(name + " = " + value);
        }
    }
}

Java Servlet Example / Sample code to read Request Information using HttpServletRequest from doGet, doPost or do* methods

Following Servlet sample code will demonstrate you how to extract request information within doGet, doPost or any other Sevlet methods. In the following example RequestInfo Servlet extends HttpSevlet and overrides its doGet and doPost methods, all the do* methods has 2 arguments (1) HttpServletRequest and (2) HttpServletResponse. We can extract request method, protocol, path, remote address from HttpServletRequest object as shown in the bellow example.

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class RequestInfo extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body>");
        out.println("<head>");
        out.println("<title>Request Information Example</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3>Request Information Example</h3>");
        out.println("Method: " + request.getMethod());
        out.println("Request URI: " + request.getRequestURI());
        out.println("Protocol: " + request.getProtocol());
        out.println("PathInfo: " + request.getPathInfo());
        out.println("Remote Address: " + request.getRemoteAddr());
        out.println("</body>");
        out.println("</html>");
    }


    /**
     * We are going to perform the same operations for POST requests
     * as for GET methods, so this method just sends the request to
     * the doGet method.
     */

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        doGet(request, response);
    }
}

Tuesday, August 3, 2010

Welcome

Welcome to JSP Servlet Guide