Server Side Development: �Servlets
of 99
1
of 99
2
Server Side Development�Outline
of 99
3
Server Side Development�Tiered Architecture
Web Server
(Application Logic)
Database/ FileSystem
(Persistent Storage)
Application/Browser
(User Interface)
of 99
4
Server Side Development�Web Server
of 99
5
Server Side Development�Server Extensions
of 99
6
Server Side Development�Tomcat
HTTP
of 99
7
of 99
8
HTTP�Application Layer Protocol
of 99
9
HTTP�Application Layer Protocol, cont’d.
TCP/UDP with
Buffers and Variables
Controlled by
Application
Developer
Controlled by
Operating
System
HOST
Process
Process
Controlled by
Operating
System
Controlled by
Application
Developer
HOST
TCP/UDP with Buffers and Variables
Socket
Socket
Internet
(By convention get will not change data on server)
of 99
10
HTTP�HyperText Transfer Protocol
of 99
11
HTTP�GET and POST
of 99
12
HTTP�HTTP Headers
of 99
13
HTTP�Protocol
of 99
14
HTTP�Tracking State
of 99
15
HTTP�HTTP Status Codes
J2EE Architecture
of 99
16
of 99
17
J2EE Architecture�J2EE – Container Architecture
J2EE Component
Component Code
& Resources
J2EE Container
J2EE
Component
J2EE
Component
J2EE
Component
J2EE
Component
Component 2
of 99
18
Applet Container
Applet
Application Container
Application
JDBC
JAXP
JAAS
J
M
S
Client Tier
J2EE Server
J2ME App
Other Application or Server
J2EE Server
Enterprise Information System
Non-Java Sever
Database
3rd & Nth Tiers
Web Container
Connections
JDBC
JAXP
JavaMail/JAF
JTA
JAAS
JMS
Web Container
Connections
JDBC
JAXP
JavaMail/JAF
JTA
JAAS
JMS
JSPs
Servlets
EJBs
J2EE Server
Middle Tier
internet
internet
J2EE Architecture�J2EE – Container Architecture, cont’d.
Application Container
of 99
19
J2EE Architecture�Client Tier
Applet Container
Applet
Application Container
Application
JDBC
JAXP
JAAS
J
M
S
ClientApp (JAR file)
Main AppClass
Public static void main (String args[ ] )
Java Packages,
Classes, Libraries
Deployment Descriptor
to provide certain functionality to the components
in the application
of 99
20
J2EE Architecture�Middle Tier Container
of 99
21
J2EE Architecture�E-Commerce Scenario
WEB Container
WEB Container
OrderManager Application
Application Container
ClientApp
WEB Container
WEB Container
Shopping Cart Application
Process Servlet
Order
J2EE Server
EJB Container
WEB Container
Order EJB
Order Manager EJBApplication
Supplier Server
Order Manager
Servlet
StockOrder
(XML)
Database
Catalog Servlet
Cart Servlet
Static
Pages
of 99
22
J2EE Architecture�E-Commerce
of 99
23
J2EE Architecture�E-Auctions
Applet Container
PaymentApplet
Client Tier
Middle Tier
Database Tier
Sales & Auction Cluster
WEB Container
WEB Container
Payment
Application
WEB Container
WEB Container
Payment
Application
Payment Cluster
WEB Container
WEB Container
Sales/Auction
Application
WEB Container
WEB Container
Sales/Auction
Application
WEB Container
WEB Container
Sales/Auction
Application
Sales & Auction Database
Payment Database
Browser
of 99
24
J2EE Architecture�E-Auctions – Container Ideas
Auction Application
Registration
Deployment Descriptor
Java Package
Post
Search
Bid
Purchase
History
Payment
Offer
Static
Pages
Payment Application
Java Package
Static
Pages
Payment
Deployment Descriptor
Web Container
Application Container
ClientApp
of 99
25
J2EE Architecture�E-Auctions
Servlets
of 99
26
of 99
27
Servlets�Introduction
of 99
28
Servlet Container
Thread
Thread
Servlet
Create Thread Pool
Instantiate servlet
Call init ( ) method
Allocate request to thread
Allocate request to thread
Block all further requests Wait for active threads to end
Terminate thread pool
call destroy ( ) method
terminate servlet
Container shutdown
Call service ( ) method
Call service ( ) method
Perform Initialization
Perform Service
Perform cleanup
Servlet destroyed & garbage collected
Perform Service
Shutdown Initiated
HTTP Request 1
HTTP Request 2
HTTP Response 1
HTTP Response 2
Servlets�Servlet Lifecycle
of 99
29
Servlets�Servlet Communication
Servlets API
of 99
30
of 99
31
Servlets�Servlet API
of 99
32
Servlets�JAVA Servlets
of 99
33
Servlets�Javax.servlet Package
of 99
34
Exception
ServletException
UnavailableException
interface
Servlet
interface
ServletConfig
Serializable
GenericServlet
interface
FilterConfig
interface
ServletContext
interface
FilterChain
EventObject
ServletContextEvent
ServletContextAttributeEvent
interface
ServletRequest
ServletRequestWrapper
interface
RequestDispatcher
OutputStream
ServletOutputStream
InputStream
ServletInputStream
EventListener
interface
ServletContextListener
interface
ServletResponse
ServletResponseWrapper
interface
SingleThreadModel
EventListener
interface
ServletContextAttributeListener
Servlets�Class Diagram
of 99
35
Servlets�Interfaces
of 99
36
Servlets�Classes
of 99
37
Servlets�Generic Servlet Class
of 99
38
Servlets�javax.servlet.http
Interfaces
of 99
39
Servlets�Classes and Interfaces
Classes
of 99
40
GenericServlet Serializable HttpServlet
ServletRequest interface HttpServletRequest
ServletRequestWrapper HttpServletRequestWrapper
ServletRequestWrapper HttpServletRequestWrapper
ServletResponse interface HttpServletResponse
Object NoBodyResponse
Object HttpUtils
ServletOutputStream NoBodyOutStream
EventObject HttpSessionEvent
HttpSessionBindingEvent
Interface HttpSessionContext
Interface HttpSession
EventListener Interface HttpSessionListener
EventListener Interface HpptSessionAttributeListener
EventListener Interface HpptSessionActivationListener
EventListener Interface HpptSessionBindingListener
Servlets�Class Diagram
of 99
41
Servlets�HttpServlet Class
of 99
42
Servlets�HttpServletRequest Interface
of 99
43
Servlets�HttpServletRequest Interface, cont’d.
of 99
44
Servlets�Cookie Class
of 99
45
Servlets�Writing a Servlet
Example 1
of 99
46
package edu.albany.mis.goel.servlets;
import javax.servlet.http.*;
import java.io.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
// Get the parameter from the request
String username = request.getParameter("username");
// Send the response back to the user
try {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><body>");
writer.println("Thank you, " + username + ". You are now logged into the system.");
writer.println("</body></html>");
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
of 99
47
Example 1�Login Servlet
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Login</title>
</head>
<body>
<h1>Login</h1>
Please enter your username and password
<form action="servlet/edu.albany.mis.goel.servlets.Login" method="POST">
<p><input type="text" name="username" length="40">
<p><input type="password" name="password" length="40">
<p><input type="submit" value="Submit">
</form>
</body>
</html>
of 99
48
Example 1�Login.html
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Login Servlet</display-name>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>edu.albany.mis.goel.servlets.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
</web-app>
of 99
49
Example 1�web.xml
of 99
50
Example 1�Login Deployment
Example 2
of 99
51
package edu.albany.mis.goel.servlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Date;
/**
* Description:
* @author Andrew Harbourne-Thomas
* @version 1.0
*/
public class HttpRequestResponseServlet extends HttpServlet {
private static int cookiesCreated = 0;
of 99
52
Example 2�HttpRequestResponsServlet
/** Output a web page with HTTP request information and response data.
* @param request The object containing the client request
* @param response The object used to send the response back
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
StringBuffer httpRequestTable = getHttpRequestTable(request);
StringBuffer httpResponseTable = getHttpResponseTable(response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//HTML page
out.println("<html><head><title>RequestResponseServlet</title></head><body>");
out.println("<h1>Request Information</h1>" + httpRequestTable + "<hr>");
out.println("<h1>Response Information</h1>" + httpResponseTable);
out.println("</body></html>");
out.close();
}
of 99
53
Example 2�Servlet – doGet()
public class HTMLTable {
private StringBuffer head;
private StringBuffer rows;
private StringBuffer foot;
/** Initalises the StringBuffer Objects.
*/
public HTMLTable() {
head = new StringBuffer();
head.append("<table width=\"90%\" align=\"center\">");
head.append("<tr><th width=\"50%\" bgcolor=\"lightgrey\">Attribute</td>");
head.append("<th width=\"50%\" bgcolor=\"lightgrey\">Value</td></tr>");
rows = new StringBuffer();
foot = new StringBuffer();
foot.append("</table>");
}
of 99
54
Example 2�HTMLTable Class
/** Appends the attribute and value in a row to the HTML table StringBuffer.
* @param attribute The first column value.
* @param value The second column value.
*/
public void appendTitleRow(String attribute) {
rows.append("<tr><td colspan=2><b><u>").append(attribute);
rows.append("</u></b></td></tr>");
}
/** Appends the attribute and value in a row to the HTML table StringBuffer.
* @param attribute The first column value.
* @param value The second column value.
*/
public void appendRow(String attribute, String value) {
rows.append("<tr><td>").append(attribute);
rows.append("</td><td><code>").append(value).append("</code></td></tr>");
}
/** Appends the attribute and value in a row to the HTML table StringBuffer.
* @param attribute The first column value.
* @param value The second column value.
*/
public void appendRow(String attribute, int value) {
appendRow(attribute, new Integer(value).toString());
}
of 99
55
Example 2�HTMLTable Class, cont’d.
/** Appends the attribute and value in a row to the HTML table StringBuffer
* @param attribute The first column value.
* @param value The second column value.
*/
public void appendRow(String attribute, boolean value) {
appendRow(attribute, new Boolean(value).toString());
}
/** Overrides Object.toString method to present a String representation of the HTML table built up.
* @return value The second column value.
*/
public String toString() {
return head.append(rows).append(foot).toString();
}
/** Presents a StringBuffer representation of the HTML table built up.
* @return value The second column value.
*/
public StringBuffer toStringBuffer(){
return head.append(rows).append(foot);
}
}
of 99
56
Example 2�HTMLTable Class, cont’d.
of 99
57
/** Prepare a HTML table of information about the request made.
* @param request The object containing the client request
* @return String containing the table
*/
private StringBuffer getHttpRequestTable(HttpServletRequest request) {
HTMLTable table = new HTMLTable();
table.appendRow("HTTP Request Method", request.getMethod());
table.appendRow("Query String", request.getQueryString());
table.appendRow("Context Path", request.getContextPath());
table.appendRow("Servlet Path", request.getServletPath());
//additional info if required
/*
table.appendRow("Path Info", request.getPathInfo());
table.appendRow("Path Translated", request.getPathTranslated());
table.appendRow("Request URI", request.getRequestURI());
table.appendRow("Request URL", request.getRequestURL().toString());
*/
Example 2�Servlet - getHttpRequestTable
of 99
58
// Get cookies from the user request
Cookie[] ourCookies = request.getCookies();
if (ourCookies == null || ourCookies.length == 0) {
table.appendRow("Cookies", "NONE");
} else {
for (int i = 0; i < ourCookies.length; i++) {
String cookieName = ourCookies[i].getName();
String cookieValue = ourCookies[i].getValue();
table.appendRow("Cookie: <code>" + cookieName + "</code>", cookieValue);
}
}
Enumeration e = request.getHeaderNames();
while (e.hasMoreElements()) {
String headerName = (String)e.nextElement();
String headerValue = request.getHeader(headerName);
table.appendRow("Header: <code>" + headerName + "</code>", headerValue);
}
return table.toStringBuffer();
}
Example 2�Servlet – getHttpRequestTable, cont’d.
/** Prepare a HTML table of information about the response made.
* @param response Gives access to the response object
* @return String containing the table
*/
private StringBuffer getHttpResponseTable(HttpServletResponse response) {
HTMLTable table = new HTMLTable();
int cookieCount = cookiesCreated++;
String name = Integer.toString(cookieCount);
String value = new Date(System.currentTimeMillis()).toString();
Cookie cookie = new Cookie(name, value);
response.addCookie(cookie);
table.appendRow("Cookie Added:<code>" + name + "</code>", value);
return table.toStringBuffer();
}
}
of 99
59
Example 2�Servlet – getHttpRequestTable, cont’d.
Tracking State
of 99
60
of 99
61
Tracking State�Cookies
(0 – original Netscape version of Cookie
1 – cookies standardized via RFC 2109)
of 99
62
Tracking State�Cookie Attributes
package edu.albany.mis.goel.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.ServletException;
public class CookieServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
of 99
63
Tracking State�Cookie Servlet
Cookie[] cookies = request.getCookies();
Cookie token = null;
if(cookies != null) {
for(int i = 0; i < cookies.length; i++)
{
if(cookies[i].getName().equals("token")) {
// Found a token cookie
token = cookies[i];
break;
}
}
}
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
String reset = request.getParameter("reset");
System.out.println("token = " + token);
if (token == null || (reset != null && reset.equals("yes"))) {
Random rand = new Random();
long id = rand.nextLong();
writer.println("<p>Welcome. A new token " + id + " is now established</p>");
// Set the cookie
token = new Cookie("token", Long.toString(id));
token.setComment("Token to identify user");
token.setMaxAge(-1);
token.setPath("/cookie/track");
of 99
64
Tracking State�Cookies (Token)
response.addCookie(token);
} else {
writer.println("Welcome back. Your token is " + token.getValue() + ".</p>"); }
String requestURLSame = request.getRequestURL().toString();
String requestURLNew = request.getRequestURL() + "?reset=yes";
writer.println("<p>Click <a href=" + requestURLSame +
">here</a> again to continue browsing with the same identity.</p>");
writer.println("<p>Otherwise, click <a href=" + requestURLNew +
">here</a> again to start browsing with a new identity.</p>");
writer.println("</body></html>");
writer.close();
}
}
of 99
65
Tracking State�Cookies, cont’d.
package edu.albany.mis.goel.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.ServletException;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
Cookie token = null;
if(cookies != null) {
for(int i = 0; i < cookies.length; i++) {
if(cookies[i].getName().equals("token")) {
// Found a token cookie
token = cookies[i];
break;
}
}
}
of 99
66
Tracking State�Cookies
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
String reset = request.getParameter("reset");
System.out.println("token = " + token);
if (token == null || (reset != null && reset.equals("yes"))) {
Random rand = new Random();
long id = rand.nextLong();
writer.println("<p>Welcome. A new token " + id + " is now established</p>");
// Set the cookie
token = new Cookie("token", Long.toString(id));
token.setComment("Token to identify user");
token.setMaxAge(-1);
token.setPath("/cookie/track");
response.addCookie(token);
}
else {
writer.println("Welcome back. Your token is " + token.getValue() + ".</p>");
}
of 99
67
Tracking State�URL Encoding
package edu.albany.mis.goel.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class TokenServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// Get the token from the request
String tokenID = request.getParameter("tokenID");
// Prepare for response
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
}
of 99
68
Tracking State�URL Rewriting
if (tokenID == null) {
// Client did not sent any token
Random rand = new Random();
tokenID = Long.toString(rand.nextLong());
writer.println("<p>Welcome. A new token " + tokenID + " is now established</p>");
}
else {
// Client sent the token back
writer.println("<p>Welcome back. Your token is " + tokenID + ".</p>");
// Prepare links for sending requests back
String requestURLSame = request.getRequestURL().toString() + "?tokenID=" + tokenID;
String requestURLNew = request.getRequestURL().toString();
// Write the response and close
writer.println("<p>Click <a href=" + requestURLSame +
">here</a> again to continue browsing with the same identity.</p>");
writer.println("<p>Otherwise, click <a href=" + requestURLNew +
">here</a> again to start browsing with a new identity.</p>");
writer.println("</body></html>");
writer.close();
}
}
of 99
69
Tracking State�Hidden Form Fields
package edu.albany.mis.goel.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
public class HiddenFieldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
// Get the token from the request
String token = request.getParameter("token");
// Prepare for response
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("style=\"font-family:verdana;font-size:10pt\">");
if(token == null) {
// Client did not sent any token
Random rand = new Random();
token = Long.toString(rand.nextLong());
writer.println("<p>Welcome. A new token " + token + " is now established</p>");
}
of 99
70
Tracking State�Hidden Form Field
else {
// Client sent the token back
writer.println("<p>Welcome back. Your token is " + token + ".</p>");
// Prepare a URL for sending requests back
String requestURL = request.getRequestURL().toString();
// Write a form with a hidden field
writer.println("<p>");
writer.println("<form method='GET' action='" + requestURL + "'>");
writer.println("<input type='hidden' name='token' value='" + token + "'/>");
writer.println("<input type='submit' value='Click Here'/>");
writer.println("</form>");
writer.println(" to continue browsing with the same identity.</p>");
// Write another form without the hidden field
writer.println("<p>");
writer.println("<form method='GET' action='" + requestURL + "'>");
writer.println("<input type='submit' value='Click Here'/>");
writer.println("</form>");
writer.println(" to start browsing with a new identity.</p>");
writer.println("</body></html>");
writer.close();
}
}
}
of 99
71
Tracking State�HttpSession Interface
/** This is the main servlet of the application which reads the
* products from the product list and presents it to the user for
* selecting and addition to the shopping card. The data is read from
* an XML file and is added to a hashmap which is added to the
* ServletContext for future access.
* Steps:
* init()
* 1. Gets the servletcontext
* 2. Obtains the name of the product file from the context (init param)
* 3. Creates a DOM parser
* 4. Parses the product file and creates a document (xml data)
* 5. Adds the product information to a Hashmap called product
* 6. Adds the Hashmap to the context.
* doGetPost()
* 1. Reads the products from the Hashmap
* 2. Creates web page which contains standard header footer (dispatcher)
* 3. Adds products to the web page and links them to the cartServlet
*/
package edu.albany.mis.goel.store;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
// JAXP packages
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import org.w3c.dom.*;
of 99
72
Store�MainServlet
public class MainServlet extends HttpServlet {
public void init() throws ServletException {
// Load the products from XML file provided by init parameter
ServletContext context = getServletContext();
InputStream productsFile = context.getResourceAsStream((String) context.getInitParameter("productsFile"));
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = null;
try { db = dbf.newDocumentBuilder();
} catch (ParserConfigurationException pce) {
throw new ServletException (pce.getMessage());
}
Document doc = null;
try { doc = db.parse(productsFile);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} catch (SAXException se) {
throw new ServletException(se.getMessage()); }
NodeList productsList = doc.getElementsByTagName("product");
HashMap products = new HashMap();
Node product;
for (int ctr = 0; ctr < productsList.getLength(); ctr ++ ) {
product = productsList.item(ctr);
NamedNodeMap attribs = product.getAttributes();
Node attrib = attribs.getNamedItem("name");
String name = attrib.getNodeValue();
attrib = attribs.getNamedItem("price");
String price = attrib.getNodeValue();
Product p = new Product(ctr,name,price);
products.put(new Integer(ctr),p);
}
// Store products in the ServletContext
context.setAttribute("products",products);
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter();
// Include standard header
RequestDispatcher dispatcher = req.getRequestDispatcher("/header.html");
dispatcher.include(req,res);
HashMap products = (HashMap) getServletContext().getAttribute("products");
// List the products, clickable to add to cart
Iterator it = products.values().iterator();
out.println("<table>");
while (it.hasNext()) {
out.println("<tr>");
Product product = (Product) it.next();
out.print("<td><a href='Cart?add=true&id=" + product.getId() +"'>");
out.print(product.getName() + "</a></td><td>" + product.getPrice());
out.println("</td>);
out.println("</tr>");
}
out.println("</table>");
// Include standard footer
dispatcher = req.getRequestDispatcher("/footer.html");
dispatcher.include(req,res);
}
}
of 99
73
Store�MainServlet
package edu.albany.mis.goel.store;
import java.util.*;
public class Cart {
private HashMap items = new HashMap();
// Default Cart Constructor
public Cart() {
}
// Function to get items from the cart
public Iterator getItems() {
return items.values().iterator();
}
public void addItem(Product product) throws ItemAlreadyAddedException {
Integer id = new Integer(product.getId());
if (this.items.containsKey(id)) {
throw new ItemAlreadyAddedException();
}
this.items.put(id, product);
}
}
package edu.albany.mis.goel.store;
import javax.servlet.*;
public class ItemAlreadyAddedException extends ServletException {
}
of 99
74
Store�Cart and Product
package edu.albany.mis.goel.store;
public class Product {
private String name;
private String price;
private int id;
public Product(int id, String name, String price) {
this.price = price;
this.name = name;
this.id=id;
}
public String getPrice() {
return this.price;
}
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
}
package edu.albany.mis.goel.store;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CartServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Get the cart if it exists
HttpSession session = req.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
}
// Check to see if we are adding to the cart or we want to dispay the cart
String adding = req.getParameter("add");
PrintWriter out = res.getWriter();
// Add to it
if (adding.equalsIgnoreCase("true")) {
addToCart(req, cart, out);
}
// Display its contents
displayCart(cart, out);
}
of 99
75
Store�CartServlet
private void addToCart(HttpServletRequest req, Cart cart, PrintWriter out)
throws ItemAlreadyAddedException {
// Get the item to add from the request
// Get the products from the servletcontext
HashMap products = (HashMap) getServletContext().getAttribute("products");
// Find the one represented by the ID that we passed in
try {
Integer id = new Integer(Integer.parseInt(req.getParameter("id")));
Product p = (Product) products.get(id);
// Add it to the cart
cart.addItem(p);
// add the cart to the session
req.getSession().setAttribute("cart",cart);
out.println("<b>Succesfully added product to cart!</b><br>");
} catch (NumberFormatException nfe) {
out.println("<b>Can't add product</b><br>");
}
}
private void displayCart(Cart cart, PrintWriter out) {
Iterator items = cart.getItems();
out.println("<h1>Current Cart Contents:</h1>");
out.println("<table>");
while (items.hasNext()) {
out.println("<tr>");
Product p = (Product)items.next();
out.println("<td>"+p.getName()+"</td>"+"<td>"+p.getPrice() +"</td>");
out.println("<tr>");
}
out.println("</table>");
}
}
/** Checkout for the customer. This is also the place where the
* security check should be done to make sure that the customer is a
* registered customer. There are two ways of doing that. Currently
* security is not implemented
*
* 1. Declarative - Relies on the deployment
* 2. Programmatic - Internally codes the security
*
* Steps
* 1. Prints the contents of the shopping cart
* 2. Asks the user to confirm his/her selection
* 3. Sends the paget to the confirm page.
*/
package edu.albany.mis.goel.store;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.security.Principal;
public class CheckOutServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGetOrPost(req,res);
}
of 99
76
Tracking State�CheckoutServlet
private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Get the writer
PrintWriter out = res.getWriter();
// include the cart display, and ask to confirm check out.
System.out.println("Dispatching the request");
RequestDispatcher dispatcher = req.getRequestDispatcher("/Cart?add=false");
dispatcher.include(req,res);
out.println("<br>Please Click Confirm to check out");
out.println("<form action='confirmed.html'>" +
"<input type='submit' value='Confirm'></form>");
}
}
Application Deployment
of 99
77
AppDir/
index.html
main.jsp
images/
company.jpg
divider.jpg
admin/
admin.jsp
WEB-INF/
web.xml
classes/edu/albany/mis/goel/servlets/
ShoppingCart.class
Catalog.class
lib/
xereces.jar
xalan.jar
edu/albany/mis/goel/servlets/
ShoppingCart.java
Catalog.java
of 99
78
Application Deployment�Structure of Web Application
Exploded Directory Format
Web Application Archive (WAR) Format
of 99
79
Application Deployment�Deployment of Web Applications
of 99
80
Application Deployment�Deployment of Web Applications, cont’d.
of 99
81
Application Deployment�ServletContext
(located at http://java.sun.com/dtd/web-app-2-3.dtd)
of 99
82
Application Deployment�Deployment Descriptor
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
“http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
Contents of the file
<web-app>
of 99
83
Application Deployment�Deployment Descriptors - Header
<context-param>
<param-name>
adminEmail
</param-name>
<param-vlaue>
admin@wrox.com
</param-value>
</context-param>
e.g. String adminEmail = getServletContext().getInitParameter(“adminEmail”);
of 99
84
Application Deployment�Deployment Descriptors - Context
<servlet>
<servlet-name>storeservlet</servlet-name>
<servlet-class>edu.albany.mis.goel.servlets.storeservlet<servlet-class>
<init-param>
<param-name>version<param-name>
<param-value>0.1b<param-value>
<init-param>
</servlet>
e.g. String version = getServletConfig().getInitParameter(“version”);
of 99
85
Application Deployment�Deployment Descriptors - Servlets
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/home.html<url-pattern>
</servlet-mapping>
(i.e. http://localhost:8080/store/storeservlet)
e.g. <servlet-mapping>
<servlet-name>ValadatorServlet<servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
of 99
86
Application Deployment�Deployment Descriptors - Servlets
<error-page>
<exception-type> java.lang.ArithmeticExceception </exception-type> 🡨 Exception Type
<location>/error.html</location> 🡨 Resource to Show
</error-page>
<error-page>
<error-code>404</error-code> 🡨 Http Error Code
<location>/404.html</location> 🡨 Resource to Show
</error-page>
of 99
87
Application Deployment�Deployment Descriptors – Error Pages
<web-app>
<display-name> Music Store</display-name>
<description>Application for Music Rentals</description>
</web-app>
<welcome-file-list>
<welcome-file>index.html</welcome-file> 🡨 Welcome File URL
</welcome-file-list>
of 99
88
Application Deployment�Deployment Descriptors - Miscellaneous
<security-constraint>
<web-resource-collection>
<web-resource-name>CheckOutResource</web-resource-name>
<url-pattern>/CheckOutServlet/*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>storeuser</role-name> 🡨 Welcome File URL
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>Wrox Store Checkout</realm-name>
<form-login-config>
<form-login-page>/login.html</form-login-page>
<form-error-page>/error.html</form-error-page>
</form-login-config>
</login-config>
<tomcat-users>
<user name=“tomcat” password=“tomcat” roles=“tomcat” />
<user name=“role1” password=“tomcat” roles=“role1” />
</tomcat-users>
of 99
89
Application Deployment�Security Constraints
of 99
90
Application Deployment�ServletConfig Interface
of 99
91
Application Deployment�ServletContext Interface
of 99
92
Application Deployment�ServletContext Interface, cont’d.
Session Management
of 99
93
Session Management�Basics
of 99
94
Session Management�Creating and Using Sessions
of 99
95
Method | Description |
String getRequestedSessionID( ) | Gets the ID assigned by the server to the session |
Boolean isRequestSessionIdValid( ) | Returns true if the request contains a valid session ID |
Boolean isRequestSessionIdFromCookie( ) | Returns true if the session ID was sent as part of a cookie |
Boolean isRequestSessionIdFromURL( ) | Returns true if the session ID was sent through URL rewriting |
Session Management�What do you do with a session?
of 99
96
Forwarding and Including Requests
of 99
97
Forwarding and Including Requests�Obtaining RequestDispatcher
of 99
98
Forwarding and Including Requests�Using RequestDispatcher
of 99
99
Forwarding and Including Requests�Adding Parameters
of 99
100