Listing 1: Class Boxer

package support;

import java.util.Collection;

/** This class supports a conversion between primitive types and wrapper objects (and
 vice-versa) that's needed when adding primitives to a collection

public class Boxer {

	// boxes int type into the Integer object
	// note that no wrapping or class casting is needed
	public static Integer box(int i) {
		Integer obj = i;
		return obj;

	// unboxes primitive type from the Integer object
	// note again that no wrapping is needed
	public static int unbox(Integer obj) {
		int i = (int)obj;
		return i;


	// adds int primitive directly to collection
	// with auto-wrapping
	public static void add(Collection col, int i) {

Listing 2: Class Generic

// Shows an example of using Java generics
package support;

import java.util.List;
import java.util.LinkedList;

public class Generic {
	// Return Generic List<Integer> object with one int eleemnt
	public static List<Integer> createGenericListWith(int g) {
		List<Integer> l = new LinkedList<Integer>();
		l.add(g); // Using autoboxing
		Integer i = l.iterator().next();
		return l;

Listing 3: Class ForLoop

package support;
import java.util.Collection;
import java.util.ArrayList;
 * Provides support for enhanced for loop

public class ForLoop {

	// convert the Collection of Integers to String collection
	public ArrayList<String> convertToString(Collection<Integer> c) {
		ArrayList<String> arr = new ArrayList<String>();
		for (Integer i : c) arr.add(i.toString());
		return arr;

Listing 4: Using printf

package support;
public class Printf {
	// print the number with decimal points
	public static void printWithDecimals(PrintWriter out, double q) {
		// Print the number with 3 decimal places.
		out.printf ("%5.3f %n", q);

Listing 5: Variable arguments

package support;
 * Using a method with variable arguments

public class Varargs {
	// method with variable number of arguments
	public static void format( out, String str, Object... args) {
		for(int i=0; i<args.length; i++) {
			out.println("Formatted" + (args[i]));

Listing 6: Static Imports

package support;
/** Demonstrates static import capability
import static java.lang.Math.*;
public class StaticImport {
	public static double pitimes(double d){
		return d * PI;
	public static double absoluteValue(double g) {
		return abs(g);

Listing 7: Sampleservlet class

package servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static support.Boxer.*;

A servlet can create a session, which means that visits to multiple pages within a site can
be tracked. The counter's value is stored in the session, so multiple visits to the page
can be counted. If the counter goes over five, it's cleared.

public class SampleServlet extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
	 throws ServletException, IOException {

	// Get the Session object from the request parameter (create it if necessary)

	boolean create = true;
	HttpSession session = req.getSession(create);

// Get the session data value (null value means counter has never been set)

Integer ival = (Integer)session.getAttribute ("sessiontest.counter");

	// convert the Integer object to an int primitive type
	int num = unbox(ival);

	// convert the int primitive type to an Integer and set it as a session attribute
	session.setAttribute ("sessiontest.counter", box(num));
	if (num > 5) {

	String cookie = req.getHeader("Cookie");

          // Write the output HTML page - just echo the counter's value

	     PrintWriter out = resp.getWriter();

	     SampleProgram.performLogic(out, num, cookie);

Listing 8: SampleProgram class

package servlet;

import static support.ForLoop.convertToString;
import static support.Generic.createGenericListWith;
import static support.Printf.printWithDecimals;
import static support.StaticImport.pitimes;
import static support.Varargs.format;

import java.util.ArrayList;
import java.util.List;

 * Sample program to be used by servlet
public class TestProgram {

	 * To be called from the command line if needed
	public static void main(String[] args) {

		if (args.length < 2) throw new RuntimeException("Usage: java servlet.SampleLogic
		 number string");
		int num = Integer.parseInt(args[0]);
		String cookie = args[1];
		PrintWriter out = new PrintWriter(System.out, true);
		performLogic(out, num, cookie);


	 * Performs all the necessary logic to display proper output
	public static void performLogic(PrintWriter out, int num, String cookie) {

	     List<Integer> list = createGenericListWith(num);
		 ArrayList<String> alist = convertToString(list);

	     out.println("<head><title>Session Tracking Test</title></head>");
	     out.println("<h1>Session Tracking Test</h1>");
	     out.print ("You have hit this page ");

	     // example of using printf function
	     printWithDecimals(out, num);
	     out.println(" times" + "<br>");

	     String fmt = "{1,number,$'#',##}";
	     out.println("Values are: ");

	     int[] intArr = new int[5];
	     for(int i=0;i<5;i++) intArr[i] = i;
	     format(out, fmt, intArr);
	     out.println("Array is: " + intArr + "<br>");
	     out.println("PI times is: " + pitimes(num) + "<br>");

	     out.println ("Your cookie (session id): " + cookie);

Listing 9: JUnit Test Program

package servlet;


import junit.framework.TestCase;

public class SampleProgramTest extends TestCase {

	public static void main(String[] args) {;

	protected void setUp() throws Exception {

	protected void tearDown() throws Exception {

	 * Test method for 'servlet.SampleProgram.main(String[])'
	public void testMain() {
		// TODO Auto-generated method stub
		SampleProgram.main(new String[]{"1", "abc"});
		assertEquals("1", "2");


	 * Test method for 'servlet.SampleProgram.performLogic(PrintWriter, int, String)'
	public void testPerformLogic() {
		// TODO Auto-generated method stub
		PrintWriter out = new PrintWriter(System.out, true);
		SampleProgram.performLogic(out, 1, "abc");

Listing 10: The servlet's deployment descriptor Web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
<Web-app id="WebApp">

		<description>Sample Servlet</description>



Listing 11: ANT deployment script build.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="MyJavaProject" default="create-war" basedir=".">

  <!-- Configure the directory where Tomcat 5.0 is -->
  <property name="local-tomcat" value="C:/Program Files/Apache Software
   Foundation/Tomcat 5.0"/>
	  <!-- Configure the directory into which the Web application is built -->
  <property name="build"    value="${basedir}/build"/>

  <!-- Configure the context path for this application -->
  <property name="path"     value="/myapp"/>

  <!-- Configure properties to access the Manager application -->
  <property name="url"      value="http://localhost:8080/manager/html"/>
  <property name="username" value="admin"/>
  <property name="password" value="admin"/>

  <!-- Configure the custom Ant tasks for the Manager application -->
  <taskdef name="deploy"    classname="org.apache.catalina.ant.DeployTask"/>
  <taskdef name="list"      classname="org.apache.catalina.ant.ListTask"/>
  <taskdef name="reload"    classname="org.apache.catalina.ant.ReloadTask"/>
  <taskdef name="resources" classname="org.apache.catalina.ant.ResourcesTask"/>
  <taskdef name="roles"     classname="org.apache.catalina.ant.RolesTask"/>
  <taskdef name="start"     classname="org.apache.catalina.ant.StartTask"/>
  <taskdef name="stop"      classname="org.apache.catalina.ant.StopTask"/>
  <taskdef name="undeploy"  classname="org.apache.catalina.ant.UndeployTask"/>

  <!-- Executable Targets -->
 <target name= "create-war">
    <property name= "war-base" value="${local-tomcat}/Webapps/myapp/"/>

  	<war destfile="${build}/myapp.war" Webxml="${basedir}/WEB-INF/Web.xml">
    	  <fileset dir="${basedir}/html"/>
		  <classes dir= "${basedir}/WEB-INF/classes">
		  		<exclude name="index.html"/>
		  		<exclude name="Web.xml"/>
		  		<exclude name="myapp.war"/>


  <target name="deploy" description="Install Web application"
    <deploy url="${url}" username="${username}" password="${password}"
            path="${path}" war="${build}${path}.war"/>

  <target name="reload" description="Reload Web application"
    <reload  url="${url}" username="${username}" password="${password}"

  <target name="undeploy" description="Remove Web application">
    <undeploy url="${url}" username="${username}" password="${password}"