JSP - Java Server Pages

In this example we will build AddressBook - a small web application that stores names and phone numbers.

The class Person.java represents the person object. It has setter and getter methods for accessing persons name and phone number.

package si.matjaz.addressbook;

public class Person {

private String name;

private String phoneNumber;

public Person(String name, String phoneNumber) {
this.name = name;
this.phoneNumber = phoneNumber;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getPhoneNumber() {
return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}

}

The class AddressBookServlet extends the HttpServlet and implements the doPost() method. This method handles all user requests (ie. every button pressed)
Addresses are stored in a http session as an attribute. First time when the page is opened, no button is pressed yet and the list of addresses is filled with some default values.
Every address in the page has 'Remove' button which removes the i-th entry.
The 'Add' button does nothing but redirects the request to the page new.jsp.
The 'Save' button extracts the parameters from the http request (name and phone), fills the addressesList and stores the list back in the http session.

package si.matjaz.addressbook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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 AddressBookServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

HttpSession session = req.getSession(true);
List<Person> addressList = (List<Person>) session.getAttribute("addresses");

String buttonPressed = req.getParameter("button");

if (buttonPressed == null) {

if (addressList == null) {
addressList = new ArrayList<Person>();
}
addressList.add(new Person("George", "123-456"));
addressList.add(new Person("John", "555-444"));
session.setAttribute("addresses", addressList);
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/");
rd.forward(req, resp);

} else if (buttonPressed.equals("add")) {

ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/new.jsp");
rd.forward(req, resp);

} else if (buttonPressed.equals("remove")) {

String pos = req.getParameter("position");
addressList.remove((new Integer(pos)).intValue());
session.setAttribute("addresses", addressList);
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/");
rd.forward(req, resp);

} else if (buttonPressed.equals("save")) {

Person aPerson = new Person(req.getParameter("name"), req.getParameter("phone"));
if (addressList == null) {
addressList = new ArrayList<Person>();
}
addressList.add(aPerson);
session.setAttribute("addresses", addressList);
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/");
rd.forward(req, resp);
}

}

}

This is the index.jsp page which is opened first when the AddressBook is opened.

<%@page language="java" contentType="text/html" %>
<%@page session="true" import="java.util.*, si.matjaz.addressbook.Person" %>
<html>
<head>
<title>AddressBook</title>
</head>
<body>
<h1>My Address Book</h1>
<hr/>

<table border="1" cellpadding="2">
<tr>
<td>NAME</td>
<td>PHONE</td>
<td></td>
</tr>
<%
List<Person> addresslist = (List<Person>) session.getValue("addresses");
if (addresslist != null) {
for (int i = 0; i < addresslist.size(); i++) {
Person aPerson = (Person) addresslist.get(i);
%>
<tr>
<td><%=aPerson.getName()%></td>
<td><%=aPerson.getPhoneNumber()%></td>
<td><form name="removeButtonForm" action="book" method="post">
<input type="hidden" name="position" value="<%=i%>" />
<input type="hidden" name="button" value="remove" />
<input type="submit" value="Remove" /></form></td>

</tr>
<%
} // for
} else {
response.sendRedirect("/AddressBook/book");
}
%>
</table>

<form name="addButtonForm" action="book" method="post">
<input type="hidden" name="button" value="add"/>
<input type="submit" value="Add..."/>
</form>
</body>
</html>

This is the new.jsp page which contains the form for inserting new persons name and phone number.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add new person</title>
</head>
<body>
<h1>Add new person</h1>
<hr/>
<form name="addPersonForm" action="book" method="post">
Name: <input type="text" name="name" size="15" />
Phone: <input type="text" name="phone" size="20" />
<input type="hidden" name="button" value="save"/>
<input type="submit" value="Add"/>
</form>
</body>
</html>

Deployment descriptor

web.xml describes how the AddressBook should be deployed on web server. <welcome-file> defines that index.jsp page should be opened first. Servlet mapping defines that all http requests whose url ends with /book should be handled by the AddressBookServlet servlet and servlet-class specifies exactly which class implements the servlet functionality.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>AddressBook</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>AddressBookServlet</servlet-name>
<servlet-class>si.matjaz.addressbook.AddressBookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddressBookServlet</servlet-name>
<url-pattern>/book</url-pattern>
</servlet-mapping>
</web-app>

The address book can be reached at

http://localhost:8080/AddressBook/

Happy browsing...