0% found this document useful (0 votes)
15 views142 pages

JAVA JSP Servlet JDBC

The document provides an overview of Object-Oriented Programming using Java, focusing on Servlets, JSP, and JDBC. It details the HTTP protocol, servlet lifecycle, and the communication between servlets and clients, as well as the structure and functionality of Java servlets. Additionally, it covers the Servlet API, including interfaces and classes necessary for servlet development.

Uploaded by

xylem3009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views142 pages

JAVA JSP Servlet JDBC

The document provides an overview of Object-Oriented Programming using Java, focusing on Servlets, JSP, and JDBC. It details the HTTP protocol, servlet lifecycle, and the communication between servlets and clients, as well as the structure and functionality of Java servlets. Additionally, it covers the Servlet API, including interfaces and classes necessary for servlet development.

Uploaded by

xylem3009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 142

OBJECT ORIENTED

PROGRAMMING
USING JAVA
Servlets/JSP/JDBC
Requirements for JAVA
Install Java EE

Tomcat 5.5 – 8.0


HTTP

of 99 4
HTTP
Application Layer Protocol
• User applications implement this protocol
• Other protocols implemented by the OS.
• Different applications use different protocols
• Web Servers/Browsers use HTTP
• File Transfer Utilities use FTP
• Electronic Mail applications use SMTP
• Naming Servers use DNS
• Interacts with transport layer to send messages

of 99 5
HTTP
Application Layer Protocol, cont’d.
Socket Socket

TCP/UDP TCP/UDP
with with Buffers
Process Process
Buffers and and
Variables Variables
Internet

Controlled by Controlled by Controlled by Controlled by


Application Operating Operating Application
Developer System System Developer

HOST HOST

• Two parameter required for identifying the receiving process


• Host machine identifier - IP Address (localhost or ip-address)
• Host machine process identifier - Port (80 or 8080 for web server)

of 99 6
HTTP
HyperText Transfer Protocol
• Lightweight protocol for the web involving a single
request & response for communication
• Provides 8 methods
• Get: Used to request data from server
(By convention get will not change data on server)
• Post: Used to post data to the server
• Head: returns just the HTTP headers for a resource.
• Put: allows you to "put" (upload) a resource (file) on to a
webserver so that it be found under a specified URI.
• Delete: allows you to delete a resource (file).
• Connect:
• Options: To determine the type of requests server will handle
• Trace: Debugging

of 99 7
HTTP
GET and POST
• GET and POST allow information to be sent back to the web server
from a browser
• e.g. when you click on the “submit” button of a form the data in the
form is send back to the server, as "name=value" pairs.
• Choosing GET as the "method" will append all of the data to the URL
and it will show up in the URL bar of your browser.
• The amount of information you can send back using a GET is restricted
as URLs can only be 1024 characters.
• A POST sends the information through a socket back to the
webserver and it won't show up in the URL bar.
• This allows a lot more information to be sent to the server
• The data sent back is not restricted to textual data and it is possible to
send files and binary data such as serialized Java objects.

of 99 8
HTTP
HTTP Headers
• Contains information about client and the request
• Four categories of header information
• General Information: Date, caching information, warnings etc.
• Entity Information: Body of the request or response e.g. MIME type,
length etc.
• Request Information: Information about client e.g. cookies, types of
acceptable responses etc.
• Response Information: Information about server e.g. cookies,
authentication information etc.
• General & Entity information used for both client & server
• Request information included by client
• Response information included by server

of 99 9
HTTP
Protocol
• HTTP is a stateless protocol
• Request/Response occurs across a single network connection
• At the end of the exchange the connection is closed
• This is required to make the server more scalable
• Web Sites maintain persistent authentication so user does not
have to authenticate repeatedly
• While using HTTP persistent authentication is maintained using
a token exchange mechanism
• HTTP 1.1 has a special feature (keep-alive) which allows clients
to use same connection over multiple requests
• Not many servers support this
• Requests have to be in quick succession

of 99 10
HTTP
Tracking State
• Three types of tracking methods are used:
• Cookies: Line of text with ID on the users cookie file
• URL Session Tracking: An id is appended to all the links in
the website web pages.
• Hidden Form Elements: An ID is hidden in form elements
which are not visible to user
• Custom html page allows the state to be tracked

of 99 11
HTTP
HTTP Status Codes
• When a server responds to a request it provides a status code
• Web Container automatically handles setting of status codes
• Five categories of status codes
• Informational
• Success
• Redirection
• Client error
• Server error
• Common Status Codes
• 200 – Request was processed normally
• 401 – Unauthorized access
• 403 – Forbidden
• 404 – Requested resource not found on server
• 405 – Method Not allowed
• 500 – Internal server error

of 99 12
Server-side Java for the web

• a servlet is a Java program which outputs an html page; it is a


server-side technology

HTTP Request Server-side Request


Java Servlet
HTTP Response Response Header + Java Server Page
Html file

browser
web server
servlet container
(engine) - Tomcat
First java servlet (marked)
import java.io.*; // For Input output
import java.util.*;
import javax.servlet.*; // For basic servlet API support
import javax.servlet.http.*; //For Http servlet

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html"); // sets the type of content in output
PrintWriter out = response.getWriter(); //Invokes out stream
out.println("<html>"); // Output starts generating in form of HTML file.
out.println("<head>");
out.println("<title>First servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("It works...<hr>");
out.println("</body>");
out.println("</html>");
}
}
What is a java servlet ?
• a java servlet is a java class extending HTTPServlet class
• a java servlet class implements the doGet(), doPost() or
other equivalent HTTP method and (usually) prints at the
standard output an html file
• a java servlet class can contain any kind of java code the JDK
can compile
• a java servlet class needs to be compiled prior to using it; it
must use servlet-api.jar
Servlets

of 99 16
Servlets
Introduction
• Classes that dynamically process requests and construct
responses
• Dynamically generate html pages in response to requests
• May also send data in other forms like XML or serialized Java
objects
• Run in a servlet container and have access to services that the
container provides
• In an application processing of each request will normally be
done by a different servlet.
• e.g. search catalog, check out, confirm order etc.
• Client of the servlet can be any of the following
• Browser
• Applet
• Java Application

of 99 17
Servlets
Servlet Lifecycle
Servlet
Container

Create Thread Pool Thread


Thread

Instantiate servlet
Servlet
Call init ( ) method Perform
HTTP Initialization
Allocate request to thread Call service ( ) method
Request 1

HTTP
Allocate request to thread Call service ( ) method Perform Service
Request 2
Shutdown
Initiated
Block all further requests Wait
HTTP for active threads to end Perform Service
Response 1
Terminate thread pool

HTTP call destroy ( ) method


Perform
Response 2 cleanup
terminate servlet
Servlet destroyed
& garbage collected
Container shutdown

of 99 18
Servlets
Servlet Communication
• Servlet can communicate with four different entities
• Client during request/response cycle
• With servlet container to get context/config information
• With other resources on server e.g. servlets, EJBs
• With external resources like databases, legacy systems, and EIS
• Client communication can be in many forms
• In Http communication
• Request – Information parameters (as name value pairs)
• Response
• HTML (Browsers)
• WML (Mobile Devices)
• CSV (Spreadsheets)
• XML (Communicating with non-java systems)
• Serialized Objects

of 99 19
Servlets API

of 99 20
Servlets
Servlet API
• Contained in two packages
• javax.servlet
• javax.servlet.Http
• Contains 20 interfaces and 16 classes
• Prevalence of interfaces allows servlet implementation to
be customized to container

of 99 21
Servlets
JAVA Servlets
• Javax.servlet package can be extended for use with
any application layer protocol
• http is the most popularly used protocol
• Javax.servlet.http package is extension of the javax.servlet
package for http protocol
• The Servlet spec allows you to implement separate Java methods
implementing each HTTP method in your subclass of HttpServlet.
• Override the doGet() and/or doPost() method to provide normal
servlet functionality.
• Override doPut() or doDelete() if you want to implement these
methods.
• There's no need to override doOptions() or doTrace().
• The superclass handles the HEAD method all on its own.

of 99 22
Servlets
Javax.servlet Package
• Provides the contract between the servlet/web
application and the web container
• Used for creating protocol independent server
applications
• Servlet interface defines the core of the entire package
• Other interfaces provide additional services to the
developer
• Contains 12 interfaces
• 7 interfaces implemented by the package
• 5 interfaces implemented by the user

of 99 23
Servlets
Class Diagram
Exception EventListener
ServletException interface

EventObject ServletContextListener

ServletContextEvent
UnavailableException EventListener
interface
ServletContextAttributeEvent ServletContextAttributeListener
interface interface
Servlet ServletConfig
interface
interface
ServletResponse
ServletRequest

Serializable
GenericServlet ServletResponseWrapper
ServletRequestWrapper

interface interface interface OutputStream interface


FilterConfig ServletContext RequestDispatcher ServletOutputStream SingleThreadModel

interface InputStream
FilterChain ServletInputStream

of 99 24
Servlets
Interfaces
• Server implemented interfaces
• ServletConfig
• ServletContext
• ServletRequest
• ServletResponse
• RequestDispatcher
• FilterChain
• FilterConfig
• User implemented interfaces
• Servlet
• ServletContextListener
• ServletContextAttributeListener
• SingleThreadModel
• Filter

of 99 25
Servlets
Classes
• Servlet Classes
• GenericServlet // Protocol Independent
• ServletContextEvent
• ServletContextAttriubuteEvent
• ServletInputStream
• ServletOutputStream
• ServletRequestWrapper
• ServletResponseWrapper
• Exception Classes
• ServletException
• UnavailableException

of 99 26
Servlets
Generic Servlet Class
• GenericServlet is abstract class that implements servlet
interface
• Requires implementing the service() method
• Servlets normally extend from this class
• Methods
• LifeCycle Methods
• init()
• service()
• destroy()
• Environment Methods
• getServletContext()
• getInitParameter(…)
• getInitParameterNames()
• Utility Methods
• log(…)

of 99 27
Servlets
javax.servlet.http
• Javax.servlet package provides interfaces and classes to service
client requests in protocol independent manner.
• Javax.servlet.http package supports http-specific functions.
• Several of the classes are derived from the javax.servlet
packaage
• Some methods from the javax.servlet package are also used
• Contains
• 8 interfaces
• 7 classes

of 99 28
Servlets
Classes and Interfaces
Interfaces Classes
• HttpSession – Cookie
– HttpServlet
• HttpServletRequest
– HttpServletRequestWrapper
• HttpServletResponse – HttpServletResponseWrapper
• HttpSessionAttributeListener – HttpSessionBindingEvent
• HttpSessionActivationListener – HttpSessionEvent
• HttpSessionBindingListener – HttpUtils
• HttpSessionContext
• HttpSessionListener

of 99 29
Servlets
Class Diagram
GenericServlet EventObject
Serializable HttpSessionEvent
HttpServlet

ServletRequest interface HttpSessionBindingEvent


HttpServletRequest
Interface
HttpSessionContext
ServletRequestWrapper
Interface
HttpServletRequestWrapper
HttpSession

EventListener Interface
ServletResponse interface HttpSessionListener
HttpServletResponse

EventListener Interface
HpptSessionAttributeListener
Object ServletRequestWrapper
NoBodyResponse HttpServletRequestWrapper
EventListener Interface
HpptSessionActivationListener
Object ServletOutputStream
HttpUtils NoBodyOutStream
EventListener Interface
HpptSessionBindingListener

of 99 30
Servlets
HttpServlet Class
• Extends the Generic Servlet
• Inherits the init() and destroy methods()
• Overrides the service() method
• Service() method
• Signature: Protected void service(HttpServletRequest req,
HttpServletResponse res)
• Forwards the request to the appropriate method
• Developer should not normally override this method
• The developer needs to implement the methods
corresponding to the request
• doGet(), doPost(), doHead(), doPut()

of 99 31
Servlets
HttpServletRequest Interface
• Extends ServletRequest
• Inherited methods from ServletRequest
• getParameterNames()
• getParameter(String name)
• getParameterValues(String name)
• getServerName()
• getServerPort()
• getRequestDispatcher
• New methods defined
• getCookies()
• getHeader()
• getPathInfo()
• getContextPath()
• getQueryString()
of 99 32
Servlets
HttpServletRequest Interface, cont’d.
• Extends ServletResponse
• Inherited methods from ServletResponse
• getoutputStream()
• getWriter(String name)
• flushBuffer()
• setContentType()
• New methods
• encodeURL(String url)
• encodeRedirectURL(String url)
• setDateHeader()
• setStatus()
• ………
of 99 33
Servlets
Cookie Class
• Constructor
• Cookie (String name, String value)
• Methods
• public void setMaxAge(int expiry)
• public void setValue(String newValue)
• Can be added to the response by using
• void addCookie(Cookie cookie) of HttpServletResponse
• Can be obtained from the request by using
• Cookie[] getCookies() method of the HttpServletRequest

of 99 34
Servlets
Writing a Servlet
• Create a servletclass
• extend HttpServlet
• Implement the doGet() or doPost() method
• Both methods accept two parameters
• HttpServletRequest
• HttpServletResponse
• Obtain parameters from HttpServletRequest Interface
using
• getParameter(String name)
• Obtain the writer from the response object
• Process input data and generate output (in html form) and
write to the writer
• Close the writer

of 99 35
Example 1

of 99 36
Example 1- Login Servlet (Marked)
package edu.albany.mis.goel.servlets; // Needs when you create appropriate directory
import javax.servlet.http.*;
import java.io.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// Get the parameter from the request
String username = request.getParameter("username"); // takes parameter from username textbox
// 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 37
Example 1
Login.html
<!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 38
Example 1 (Marked)
web.xml
<?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> <!-- value inside highlighted tag must be same- ->
<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 39
Example 1
Login Deployment
• Compiling
• Makefile contains all the scripts for compiling and deployment of
the servlet
• Needs to be modified for any give application
• Commands
• make shutdown: shuts down the tomcat server
• make clean: cleans up the current setup for the application
• make all: compiles code, creates war file and deploys war file on
server
• make startup: starts the server again
• Running the servlet
• http://localhost:8080/login/login.html

of 99 40
Example 2

of 99 41
Example 2
HttpRequestResponsServlet
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 42
Example 2
Servlet – doGet()
/** 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 43
Example 2
HTMLTable Class
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 44
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 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 45
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 46
Example 2
Servlet - getHttpRequestTable
/** 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());
*/

of 99 47
Example 2
Servlet – getHttpRequestTable, cont’d.
// 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();
}

of 99 48
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 49
Tracking State

of 99 50
Tracking State
Cookies
• A Cookie is data (String) that the server passes to the
browser and the browser stores on the server
• Set of name value pairs
• Web servers place cookies on user machines with id
to track the users
• Two types of cookies
• Persistent cookies: Stored on hard drive in text format
• Non-persistent cookies: Stored in memory and goes away
after you reboot or turn off the machine

of 99 51
Tracking State
Cookie Attributes
• Attributes of a cookie
• Name: Name of a cookie
• Value: Value of the cookie
• Comment: Text explaining purpose of cookie
• Max-Age: Time in seconds after which the client should not send cookie
back to server
• Domain: Domain to which the cookie should be sent
• Path: The path to which the cookie should be sent
• Secure: Specifies if cookie should be sent via https
• Version: Cookie version
(0 – original Netscape version of Cookie
1 – cookies standardized via RFC 2109)

of 99 52
Tracking State
Cookie Servlet
package edu.albany.mis.goel.servlets; Cookie[] cookies = request.getCookies();
import java.io.IOException; Cookie token = null;
import java.io.PrintWriter; if(cookies != null) {
import java.util.Random; for(int i = 0; i < cookies.length; i++)
import javax.servlet.http.HttpServlet; {
import javax.servlet.http.HttpServletRequest; if(cookies[i].getName().equals("token"))
{
import javax.servlet.http.HttpServletResponse;
// Found a token cookie
import javax.servlet.http.Cookie;
token = cookies[i];
import javax.servlet.ServletException;
break;
public class CookieServlet extends HttpServlet
}
{
}
protected void doGet(HttpServletRequest
request,HttpServletResponse response) }
throws ServletException, IOException
{
of 99 53
Tracking State
Cookies (Token)
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 54
Tracking State
Cookies, cont’d.
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 55
Tracking State
Cookies
package edu.albany.mis.goel.servlets; response.setContentType("text/html");
import java.io.IOException; PrintWriter writer = response.getWriter();
import java.io.PrintWriter; writer.println("<html><head><title>Tokens</title></head><body ");
import java.util.Random; writer.println("style=\"font-family:verdana;font-size:10pt\">");
import javax.servlet.http.HttpServlet; String reset = request.getParameter("reset");
import javax.servlet.http.HttpServletRequest; System.out.println("token = " + token);
import javax.servlet.http.HttpServletResponse; if (token == null || (reset != null && reset.equals("yes"))) {
import javax.servlet.http.Cookie; Random rand = new Random();
import javax.servlet.ServletException; long id = rand.nextLong();
public class CookieServlet extends HttpServlet { writer.println("<p>Welcome. A new token " + id + " is now
established</p>");
protected void doGet(HttpServletRequest
request,HttpServletResponse response)
throws ServletException, IOException { // Set the cookie
Cookie[] cookies = request.getCookies(); token = new Cookie("token", Long.toString(id));
Cookie token = null; token.setComment("Token to identify user");
if(cookies != null) { token.setMaxAge(-1);
for(int i = 0; i < cookies.length; i++) { token.setPath("/cookie/track");
if(cookies[i].getName().equals("token")) { response.addCookie(token);
// Found a token cookie }
token = cookies[i]; else {
break; writer.println("Welcome back. Your token is " + token.getValue() +
".</p>");
}
}
}
}

of 99 56
Tracking State
URL Encoding
• http://
www.address.edu:1234/path/subdir/file.ext?query_string
• Service → http
• Host → www. Address. edu
• Port → 1234
• /path/subdur/file.ext → resource path on the server
• query_string → additional information that can be passed to resource
• Http allows name value pairs to be passed to the resource
• http:// www.test.edu/index.jsp?firstname=sanjay+lastname=goel
• The server can place the id of a customer along with the URL
• http://www.fake.com/ordering/id=928932888329938.823948
• This number can be obtained by guessing or looking over some
one’s shoulder
• Timeout for the sessions may be a few hours
• User can masquerade as the owner of the id and transact on the web

of 99 57
Tracking State
URL Rewriting
package edu.albany.mis.goel.servlets; if (tokenID == null) {
import java.io.IOException; // Client did not sent any token
import java.io.PrintWriter; Random rand = new Random();
import java.util.Random; tokenID = Long.toString(rand.nextLong());
import javax.servlet.http.HttpServlet; writer.println("<p>Welcome. A new token " + tokenID + " is now
established</p>");
import javax.servlet.http.HttpServletRequest;
}
import javax.servlet.http.HttpServletResponse;
else {
import javax.servlet.ServletException;
// Client sent the token back
public class TokenServlet extends HttpServlet {
writer.println("<p>Welcome back. Your token is " + tokenID + ".</p>");
protected void doGet(HttpServletRequest request,HttpServletResponse
response) // Prepare links for sending requests back
throws ServletException, IOException { String requestURLSame = request.getRequestURL().toString() +
"?tokenID=" + tokenID;
// Get the token from the request
String requestURLNew = request.getRequestURL().toString();
String tokenID = request.getParameter("tokenID");
// Write the response and close
// Prepare for response
writer.println("<p>Click <a href=" + requestURLSame +
response.setContentType("text/html");
">here</a> again to continue browsing with the same
PrintWriter writer = response.getWriter(); identity.</p>");
writer.println("<html><head><title>Tokens</title></head><body "); writer.println("<p>Otherwise, click <a href=" + requestURLNew +
writer.println("style=\"font-family:verdana;font-size:10pt\">"); ">here</a> again to start browsing with a new
} identity.</p>");
writer.println("</body></html>");
writer.close();
}
}

of 99 58
Tracking State
Hidden Form Fields
• HTML allows creation of hidden fields in the forms
• Developers use hidden fields to store information for
their reference
• ID can be stored as a hidden form field
• <Input Type=Hidden Name=“Search” Value=“key”>
• <Input Type=Hidden Name=“id” Value=“123429823”>

of 99 59
Tracking State
Hidden Form Field
package edu.albany.mis.goel.servlets; else {
import java.io.IOException; // Client sent the token back
import java.io.PrintWriter; writer.println("<p>Welcome back. Your token is " + token + ".</p>");
import java.util.Random; // Prepare a URL for sending requests back
import javax.servlet.http.HttpServlet;
String requestURL = request.getRequestURL().toString();
import javax.servlet.http.HttpServletRequest;
// Write a form with a hidden field
import javax.servlet.http.HttpServletResponse;
writer.println("<p>");
import javax.servlet.ServletException;
writer.println("<form method='GET' action='" + requestURL + "'>");
public class HiddenFieldServlet extends HttpServlet {
protected void doGet(HttpServletRequest writer.println("<input type='hidden' name='token' value='" + token + "'/>");
request,HttpServletResponse response) writer.println("<input type='submit' value='Click Here'/>");
throws ServletException, IOException { writer.println("</form>");
// Get the token from the request writer.println(" to continue browsing with the same identity.</p>");
String token = request.getParameter("token");
// Write another form without the hidden field
// Prepare for response
writer.println("<p>");
response.setContentType("text/html");
writer.println("<form method='GET' action='" + requestURL + "'>");
PrintWriter writer = response.getWriter();
writer.println("<input type='submit' value='Click Here'/>");
writer.println("<html><head><title>Tokens</title></head><body ");
writer.println("style=\"font-family:verdana;font-size:10pt\">"); writer.println("</form>");

if(token == null) { writer.println(" to start browsing with a new identity.</p>");


// Client did not sent any token writer.println("</body></html>");
Random rand = new Random(); writer.close();
token = Long.toString(rand.nextLong()); }
writer.println("<p>Welcome. A new token " + token + " is now }
established</p>");
}
}

of 99 60
Tracking State (Marked)
HttpSession Interface
• Provides methods to establish session between client and
server
• Session lasts for a specified time
• Allows binding of objects over multiple requests
• Important Methods
• getID()
• getAttribute(String name)
• getAttributeNames()
• setAttribute(String name, Object value)
• removeAttribute(String name)
• inValidate()

of 99 61
Store
MainServlet
/** This is the main servlet of the application which reads the public class MainServlet extends HttpServlet {
* products from the product list and presents it to the user for public void init() throws ServletException {
* selecting and addition to the shopping card. The data is read from // Load the products from XML file provided by init parameter

* an XML file and is added to a hashmap which is added to the ServletContext context = getServletContext();
InputStream productsFile = context.getResourceAsStream((String)
* ServletContext for future access. context.getInitParameter("productsFile"));
* Steps: DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
* init() DocumentBuilder db = null;
* 1. Gets the servletcontext try { db = dbf.newDocumentBuilder();
* 2. Obtains the name of the product file from the context (init param) } catch (ParserConfigurationException pce) {
* 3. Creates a DOM parser throw new ServletException (pce.getMessage());
* 4. Parses the product file and creates a document (xml data) }

* 5. Adds the product information to a Hashmap called product Document doc = null;
try { doc = db.parse(productsFile);
* 6. Adds the Hashmap to the context.
} catch (IOException ioe) {
* doGetPost()
throw new ServletException(ioe.getMessage());
* 1. Reads the products from the Hashmap
} catch (SAXException se) {
* 2. Creates web page which contains standard header footer (dispatcher)
throw new ServletException(se.getMessage()); }
* 3. Adds products to the web page and links them to the cartServlet NodeList productsList = doc.getElementsByTagName("product");
*/ HashMap products = new HashMap();
package edu.albany.mis.goel.store; Node product;
import java.io.*; for (int ctr = 0; ctr < productsList.getLength(); ctr ++ ) {
import java.util.*; product = productsList.item(ctr);
import javax.servlet.*; NamedNodeMap attribs = product.getAttributes();
import javax.servlet.http.*; Node attrib = attribs.getNamedItem("name");
String name = attrib.getNodeValue();

// JAXP packages attrib = attribs.getNamedItem("price");


String price = attrib.getNodeValue();
import javax.xml.parsers.*;
Product p = new Product(ctr,name,price);
import org.xml.sax.*;
products.put(new Integer(ctr),p);
import org.xml.sax.helpers.*;
}
import org.w3c.dom.*;
// Store products in the ServletContext
context.setAttribute("products",products);
}
of 99 62
Store
MainServlet
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 63
Store
Cart and Product
package edu.albany.mis.goel.store; package edu.albany.mis.goel.store;
import java.util.*; public class Product {
public class Cart { private String name;

private HashMap items = new HashMap(); private String price;

// Default Cart Constructor private int id;

public Cart() {
public Product(int id, String name, String price) {
}
this.price = price;
// Function to get items from the cart
this.name = name;
public Iterator getItems() {
this.id=id;
return items.values().iterator();
}
}
public void addItem(Product product) throws ItemAlreadyAddedException {
public String getPrice() {
Integer id = new Integer(product.getId());
return this.price;
if (this.items.containsKey(id)) {
}
throw new ItemAlreadyAddedException();
} public String getName() {
this.items.put(id, product); return this.name;
} }
}
public int getId() {
package edu.albany.mis.goel.store; return this.id;
import javax.servlet.*; }
public class ItemAlreadyAddedException extends ServletException {
} }

of 99 64
Store
CartServlet
package edu.albany.mis.goel.store; private void addToCart(HttpServletRequest req, Cart cart, PrintWriter out)
import java.io.*; throws ItemAlreadyAddedException {
import java.util.*; // Get the item to add from the request
import javax.servlet.*; // Get the products from the servletcontext
import javax.servlet.http.*;
HashMap products = (HashMap) getServletContext().getAttribute("products");
public class CartServlet extends HttpServlet {
// Find the one represented by the ID that we passed in
public void doPost(HttpServletRequest req, HttpServletResponse res)
try {
throws ServletException, IOException {
Integer id = new Integer(Integer.parseInt(req.getParameter("id")));
}
public void doGet(HttpServletRequest req, HttpServletResponse res) Product p = (Product) products.get(id);

throws ServletException, IOException { // Add it to the cart


doGetOrPost(req,res); cart.addItem(p);
} // add the cart to the session
private void doGetOrPost(HttpServletRequest req, HttpServletResponse res) req.getSession().setAttribute("cart",cart);
throws ServletException, IOException { out.println("<b>Succesfully added product to cart!</b><br>");
// Get the cart if it exists } catch (NumberFormatException nfe) {
HttpSession session = req.getSession(); out.println("<b>Can't add product</b><br>");
Cart cart = (Cart) session.getAttribute("cart"); }
if (cart == null) {
}
cart = new Cart();
private void displayCart(Cart cart, PrintWriter out) {
}
Iterator items = cart.getItems();
// Check to see if we are adding to the cart or we want to dispay the cart
out.println("<h1>Current Cart Contents:</h1>");
String adding = req.getParameter("add");
PrintWriter out = res.getWriter(); out.println("<table>");

// Add to it while (items.hasNext()) {


if (adding.equalsIgnoreCase("true")) { out.println("<tr>");
addToCart(req, cart, out); Product p = (Product)items.next();
} out.println("<td>"+p.getName()+"</td>"+"<td>"+p.getPrice() +"</td>");
// Display its contents out.println("<tr>");
displayCart(cart, out); }
} out.println("</table>");
}
}
of 99 65
Tracking State
CheckoutServlet
/** Checkout for the customer. This is also the place where the private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
* security check should be done to make sure that the customer is a throws ServletException, IOException {
* registered customer. There are two ways of doing that. Currently // Get the writer
* security is not implemented PrintWriter out = res.getWriter();
*
// include the cart display, and ask to confirm check out.
* 1. Declarative - Relies on the deployment
System.out.println("Dispatching the request");
* 2. Programmatic - Internally codes the security
RequestDispatcher dispatcher = req.getRequestDispatcher("/Cart?add=false");
*
dispatcher.include(req,res);
* Steps
* 1. Prints the contents of the shopping cart out.println("<br>Please Click Confirm to check out");

* 2. Asks the user to confirm his/her selection out.println("<form action='confirmed.html'>" +


* 3. Sends the paget to the confirm page. "<input type='submit' value='Confirm'></form>");
*/ }
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 66
Application Deployment

of 99 67
Application Deployment
Structure of Web Application
AppDir/
index.html • Public Resources that are
main.jsp downloaded directly to the client
images/ without processing
company.jpg – Lib files are standard libraries that
divider.jpg the code may need
admin/ – JSP files are an exception since they
admin.jsp are converted to servlets and not
downloaded directly
WEB-INF/
web.xml
classes/edu/albany/mis/goel/servlets/
• Files which the web container
ShoppingCart.class
processes but not client
Catalog.class
– Lib files are standard libraries that
lib/
the code may need
xereces.jar
xalan.jar
edu/albany/mis/goel/servlets/ • Source Files which are developed
ShoppingCart.java by the user
Catalog.java – Package directory reduces chances of
name conflicts

of 99 68
Application Deployment
Deployment of Web Applications
• Web applications are deployed in the web applications
directory of the web server
• In tomcat this directory is ${Tomcat_Home}/webapps
• Two separate ways of deploying web applications
Exploded Directory Format
• Development directory is copied to the application directory of the
web server
• Used primarily in development mode when changes are frequent
Web Application Archive (WAR) Format
• Archived version of development directory is copied to application
directory of web server
• Created using jar utility i.e. jar –cv0f SimpleWebApp.war .

of 99 69
Application Deployment
Deployment of Web Applications, cont’d.
• If web application is in a location different than the webapps
directory context is defined
• Location: ${Tomcat_Home}/conf/server.xml
• <context path=“/store” docBase=“/store.war”
reloadable=“true>
• Context declares a context to exist with a base URL path of /store
• The application can be accessed at http://localhost:8080/store/.
• docBase tells tomcat where to find the web application
• Relative path (/store.war) tells Tomcat that store.war is at the top level
of the webapps directory
• An absolute path can also be supplied I.e. c:/myapps/store.war
• Reloadable set to true indicates that if the class or lib files change the
application detects the change
of 99 70
Application Deployment
ServletContext
• Each application in a web container is associated with a context
• All web resources are associated with the context.
• Servlet context is rooted at a known path within web container. (e.g.
{Tomcat_Home}/webapps/store/home.html)
• Context for this application is /store
• User would access this as:
http://localhost:8080/store/home.html
• There is a special object called servlet context.
• A sandbox for the application (prevents name clashes and
efficient downloading of classes without having to set classpath)
• Allows servlets access container resources
• Primary use of servlet context is to share attributes between
servlets in an application.
• Context may be defined explicitly in a web server
• Configuration Directory in Tomcat: ${Tomcat_Home}/conf/server.xml
• <context path=“/examples” docBase=“examples” debug=“0” reloadable=“true”>

of 99 71
Application Deployment
Deployment Descriptor
• Conveys configuration information of a web application
• The primary elements of a deployment descriptor file
• Servlet definitions & mappings
• Servlet context initialization parameters
• Error pages
• Welcome pages
• File based security
• Rules for the deployment descriptor file
• Resides at the top level of the WEB-INF directory
• Must be a well formed XML file called web.xml
• Must conform to the dtd
(located at http://java.sun.com/dtd/web-app-2-3.dtd)

of 99 72
Application Deployment
Deployment Descriptors - Header
• Header denotes the version of XML
<?xml version="1.0" encoding="ISO-8859-1"?>
• Describes the the DTD for the application
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
“http://java.sun.com/dtd/web-app_2_3.dtd">
• Description of the application enclosed in web-app tags
<web-app>
Contents of the file

<web-app>

of 99 73
Application Deployment
Deployment Descriptors - Context
• Context parameters are parameters that are related to the
entire application.
• Any number of initialization parameters can be provided in the context
• One initialization parameter for web application is shown below:
<context-param>
<param-name>
adminEmail
</param-name>
<param-vlaue>
[email protected]
</param-value>
</context-param>

• ServletContext object is used to obtain context information


e.g. String adminEmail =
getServletContext().getInitParameter(“adminEmail”);
• The methods in ServletContext are abstract, their implementations
must be provided by the web container.
of 99 74
Application Deployment
Deployment Descriptors - Servlets
• Servlet Description, e.g.
<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>
• The above servlet is invoked by
http://localhost:8080/store/home.html (Here store is the context of
the application)
• The initialization parameters are used for the specific servlet
• They can be accessed using the ServletConfig object
e.g. String version = getServletConfig().getInitParameter(“version”);

of 99 75
Application Deployment
Deployment Descriptors - Servlets
• Servlet mappings map servlets to specific URL pattern
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/home.html<url-pattern>
</servlet-mapping>
• Allows web container to send requests to specific servlet
• Why is servlet mapping required?
• A logical way to specify servlets would be to use context/servletname
(i.e. http://localhost:8080/store/storeservlet)
• Allows multiple urls to be mapped to same servlet
• Allows implementation details to be hidden
• Servlets can be mapped to more than one URL thro the
use of wildcards in <url-pattern>
e.g. <servlet-mapping>
<servlet-name>ValadatorServlet<servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
• The previous example maps every URL encountered to the same servlet

of 99 76
Application Deployment
Deployment Descriptors – Error Pages
• Error pages allow the application to specify
pages to be shown when particular errors occur
• Used for Java Exceptions and Http Errors.
• The error page shown below is displayed when the
server encounters a java.lang.ArithmeticException.
<error-page>
<exception-type> java.lang.ArithmeticExceception </exception-type>  Exception Type
<location>/error.html</location>  Resource to Show
</error-page>

• The error page shown below is displayed when the


server encounters a an Http error
<error-page>
<error-code>404</error-code>  Http Error Code
<location>/404.html</location>  Resource to Show
</error-page>

of 99 77
Application Deployment
Deployment Descriptors - Miscellaneous
• Application Name & Description
<web-app>
<display-name> Music Store</display-name>
<description>Application for Music Rentals</description>
</web-app>

• Welcome Pages
<welcome-file-list>
<welcome-file>index.html</welcome-file>  Welcome File URL
</welcome-file-list>

of 99 78
Application Deployment
Security Constraints
• Define Security Constraint (resource collection & authorization
constraint)
<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>

• Define Login Configuration


<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>

• Define Users in Tomcat (Add users in ${Tomcat_Home}/conf/tomcat-


users.xml)
<tomcat-users>
<user name=“tomcat” password=“tomcat” roles=“tomcat” />
<user name=“role1” password=“tomcat” roles=“role1” />
</tomcat-users>
of 99 79
Application Deployment
ServletConfig Interface
• ServletConfig Object is used to pass initialization parameters to
a servlet
• Useful methods
• getServletName(): Returns name of servlet
• getServletContext(): Returns servletContext object
• getInitParameter(String name): returns value of the specified
parameter (null if not present)
• getInitParameterNames(): Gets names of all the parameters in the
initialization list.

of 99 80
Application Deployment
ServletContext Interface
• ServletContext is specific to a particular web application
running in a JVM
• Each web application in a container will have a single servlet context
associated with it.
• Allows you to maintain state across all servlets and clients in the
application
• Also acts a shared repository for common attributes to all servlets
• Allows servlets to share data with each other
• ServletContext Object also used for communication with host
server
• Allows servlet to get information about server on which it is running
• A typical use of this would be in a chat application

of 99 81
Application Deployment
ServletContext Interface, cont’d.
• Methods
• getContext(String uripath)
• getMimeType()
• getResourcePaths()
• getRequestDispatcher()
• getRealPath()
• getServerInfo()
• getInitParameter()
• getAttribute()
• setAttribute()
• ...

of 99 82
Session Management

of 99 83
Session Management
Basics
• HTTP is a stateless protocol. Each re.quest and
response stand alone
• Without session management, each time a client
makes a request to a server, it’s brand new user with
a brand new request from the server’s point of view.
• A session refers to the entire interaction between
between a client and a server from the time of the
client’s first request, which generally begins the
session, to the time the session is terminated.

of 99 84
Session Management
Creating and Using Sessions
• Two methods of the HttpServletRequest object are
used to create a session:
• HttpSession getSession( );
• HttpSession getSession(boolean);
• Other methods for dealing with sessions:
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 Returns true if the session ID was sent
isRequestSessionIdFromCookie( ) as part of a cookie
Boolean isRequestSessionIdFromURL( ) Returns true if the session ID was sent
through URL rewriting
of 99 85
Session Management
What do you do with a session?
• Sessions are useful for persisting information about a
client and a client’s interactions with an application.
• To do that, the HttpSession interface defines a
number of mehods:
• setAttribute(String, Object)
• getAttribute(String)

of 99 86
Forwarding and Including
Requests

of 99 87
Forwarding and Including Requests
Obtaining RequestDispatcher
• From ServletRequest
• RequestDispatcher getRequestDispatcher(String path)
• The path argument can be a relative path or absolute path
• If the path is absolute relative to application context it starts with a “/”
e.g. /Login
• If the path if relative it is interpreted relative to the current web
component location, e.g. if web component is /store then case would
be considered /store/case
• From ServletContext
• ServletContext getServletContext()
• RequestDispatcher getNamedDispatcher(String name)
• RequestDispatcher getRequestDispatcher(String path)
• The path argument should always start with a / and is interpreted
relative to the application context

of 99 88
Forwarding and Including Requests
Using RequestDispatcher
• Forwarding Request
• void forward(ServletRequest request, ServletResponse
response) throws ServletException, java.io.IOException
• Calling servlet should not write any data to the response
stream before calling this method
• If response data is sent to the stream before calling forward
an error is thrown
• Including Resource
• void include(ServletRequest req, ServletResponse res)
throws ServletException, java.io.Exception
• You can safely write to the ResponseStream before calling
the include function.

of 99 89
Forwarding and Including Requests
Adding Parameters
• Parameters are added for use in the forwarded
request
• Several methods defined in ServletRequest Interface
• Object getAttrubute(String name)
• Enumeration getAttributeNames()
• void setAttribute(String name, Object o)
• void removeAttribute(String name)
• The calling servlet can set the attributes
• The receiving servlet will use getAttribute(String)
method to retrieve the values

of 99 90
Apache Tomcat
• the most well known servlet/jsp container
• is a web server + implementation of Java Servlet and JSP
(Java Server Pages) APIs
• is developed by Apache Software Foundation
• available at http://tomcat.apache.org/ under Apache
Software License
Installing Tomcat
1. Download the binary zip distribution (e.g. apache-
tomcat-6.0.20.zip) in a local folder (we will use c:\temp
in the rest of the guide)
2. Set the environment variables
JAVA_HOME=path_to_JDK_installation_folder
CATALINA_HOME=path_to_tomcat_installation_folder
either as Windows system variables or in the files
startup.bat and shutdown.bat from the bin directory
Ex. place the following lines in the beginning of startup.bat and
shutdown.bat:
set JAVA_HOME=c:\progra~1\java\jdk1.6.0
set CATALINA_HOME=c:\temp\apache-tomcat-6.0.20
Starting/shutting down Tomcat
• start Tomcat from a cmd prompter (window):
c:\temp\apache-tomcat-6.0.20\bin\startup.bat
• verify startup by pointing a browser to the url
http://localhost:8080
• shutting down Tomcat from a cmd prompter (window):
c:\temp\apache-tomcat-6.0.20\bin\shutdown.bat
Tomcat standard folders
• bin – contains executable files for controlling the server (start,
shut down etc.)
• conf – contains configuration files; most important server.xml
for configuring the server and web.xml a general
configuration file for web applications
• lib – libraries (jars) used by tomcat and deployed web
applications
• logs – log files
• temp – temporary files
• webapps – contains the web applications deployed
• work – contains files created by tomcat during running (e.g. it
crates a servlet from each jsp file)
Format of a web application
• web applications are stored in the webapps folder, either as a
folder or as a .war archive
• a web application (either a folder or a .war archive) must
contain the following files:
• WEB-INF folder
• WEB-INF\web.xml: a configuration file
• optionally the WEB-INF folder can contain the following
subfolders:
• classes: which contain servlets
• lib: which contains jars used by the web application
• html, jsp and resource files can be placed anywhere in the
web application home folder
• servlets must be placed in the folder or subfolders of WEB-
INF\classes
A very simple web.xml example
<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd version="2.5">

</web-app>
Configuring servlets
• for JSPs (Java Server Pages) no additional configuration needs to
be done
• for java servlets additional lines must be placed in the web.xml
file:
<servlet>
<servlet-name>ServletsName</servlet-name>
<servlet-
class>The_Class_Name_of_the_Servlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> ServletsName </servlet-name>
<url-pattern>/URL_of_the_servlet</url-pattern>
</servlet-mapping>
First JSP file
<html>
<body>
<%
out.println(“First JSP… It works<br/>");
%>
</body>
</html>
What is JSP?

Why yes, there is!

• Server-side scripting language developed by Sun Microsystems to create


dynamic/interactive web content
• Scripting done by Java code embedded within static HMTL using XML-like JSP tags
and ‘scriptlets’
• Allows for seamless integration of static HTML with server-side Java
What is JSP?

• An extension to the Servlet API:


• Provides an abstraction above the level of the Servlet
• Provides usage of the same core features and services
• Allows integration with existing Java classes and JavaBeans
Advantages

• JSP programming is easy!


(For anyone familiar with HTML and Java)
• No need to explicitly compile
• Can be deployed on virtually any platform; only requires Apache web
server and Tomcat
• Allows separation of dynamic and static content
Process
Scope
Synchronization
• Default – Servlets instantiated only once
• Multithreaded to serve multiple instances
• Shared class variables, concurrence problems
• <%@ page is ThreadSafe = “false” %>
• Slow round robin service
Syntax
• Expressions
Expression is evaluated and placed in output
<%= expression %>
<%= new java.util.Date( ) %>

• Scriptlets
Code is inserted in service method.
<% code %>
Syntax
• Declarations
Code is inserted in body of servlet class, outside of service method.
<%! code %>
<%! private int accessCount = 0; %>

• Directives
Messages that enable the programs to set the overall structure of the resulting
servlet.
<%@ settings %>
Syntax
• Page Directives
Directions to the servlet engine about general setup.
<%@ page att="val" %>
<%@ page import ="java.util.*" %>

• Include Directives
A file is inserted when the JSP page is translated.
<%@ include file=“Relative url" %>
Syntax
• Actions
Predefined tasks that are processed by the JSP container at request time.

<jsp:include> Action
Includes a file at the time the page is requested.
<jsp: include page="banner.html" flush = "true" />
Standard Actions
Action Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes, the
referenced resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page. This
action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the form of a
browser-specific object or embed HTML element. In the case of a
Java applet, this action enables the downloading and installation of the
Java Plug-in, if it is not already installed on the client computer.
<jsp:param> Used with the include, forward and plugin actions to specify
additional name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies the
scope of the bean and assigns it an ID that scripting components can use
to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of
this action is automatic matching of request parameters to bean properties
of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the result
to a string for output in the response.
Fig. 25.5 JSP standard actions.

109
Servlet code in JAVA
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class HelloWorld
*/
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
private String message;
/**
* @see HttpServlet#HttpServlet()
*/
Servlet code in JAVA
public HelloWorld() {
super();
message = "Hello World";
// TODO Auto-generated constructor stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}
}
JDBC code in JAVA (Marked)
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10.ResultSet rs=stmt.executeQuery("select * from emp");
11.while(rs.next())
12.System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13.con.close();
14.}catch(Exception e){ System.out.println(e);}
15.}
16.}
Web service in JAVA
package Test;

import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Endpoint;

@WebService
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
public class TestService {

@WebMethod
public String sayHello(String msg){
return "Hello "+msg;
}

public static void main(String[] args){


Endpoint.publish("http://localhost:8888/testWS", new TestService());
}
}
3-tier architecture

1.) 3-Tier Architecture separates the application


into 3 components as given below:-
Presentation Layer (UI)
Business Access Layer
Data Access Layer
3-tier architecture
2.) 3-Tier Architecture is a Linear Architecture.
image
3.) In 3-tier Architecture, user interacts with Presentation Layer.It
is a User Interface layer which can interact to any user in
application.
4.) In 3-tier Architecture, Business Access Layer is Responsible for
all communication between Presentation layer and Data Access
Layer.Here Business Access Layer is a mediator between
Presentation layer and Data Access Layer.
3-tier architecture
5.) In 3-tier Architecture,All Data will be stored on Data Access
Layer Only.

6.) In 3-tier Architecture, Bidirectional communication is possible


(with Business layer) within layers (presentation and Data access).
3-tier architecture
MVC architecture
1.) MVC Architecture separates the application into three
components as given below:-
Model
View
Controller
MVC architecture
3.) In MVC Architecture , user interacts with View component.
4.) MVC Architecture uses 3-Tier Architecture concepts .
5.) In MVC Architecture, Controller component is responsible for
communication between view and model. Ex. If user (View) want to
update your database values then it(request) first pass to
the Controller component, after that controller pass the request
to model component if required.
6.) 3-Tier Architecture and MVC Architecture used together. MVC
doesn't replace 3-tier architecture.
MVC architecture
MVC architecture
• The MVC architectural style is nonhierarchical (triangular):
• View subsystem sends updates to the Controller subsystem
• Controller subsystem updates the Model subsystem
• View subsystem is updated directly from the Model subsystem
• The 3-tier architectural style is hierarchical (linear):
• The presentation layer never communicates directly with the data layer
(opaque architecture)
• All communication must pass through the middleware layer
SOA architecture
• Service-Oriented Architecture is implemented with web services, which
makes the “functional building blocks accessible over standard internet
protocols.”
• Use Service-Oriented Architecture to create reusable code
• With Service-Oriented Architecture, a standard form of communication is
put in place, allowing the various systems and platforms to function
independent of each other.
• Use Service-Oriented Architecture for scalability.
• With Service-Oriented Architecture, it’s possible to reduce costs while still
“maintaining a desired level of output.”
Appendix – I

JSP
<jsp:include> Action
• <jsp:include> action
• Enables dynamic content to be included in a JSP at request time
• More flexible than include directive (included at translation time)
• Requires more overhead when page contents change frequently
• <jsp:include page = "toc.html" flush = "true" />
• page is the resource to include
• flush must be true to say to flush buffer after including

124
1 <!-- Fig. 25.7: banner.html -->
2 <!-- banner to include in another document -->
3 <div style = "width: 580px">
4 <p>
5 Java(TM), C, C++, Visual Basic(R),
6 Object Technology, and <br /> Internet and
7 World Wide Web Programming Training&nbsp;<br />
8 On-Site Seminars Delivered Worldwide
9 </p>
10
11 <p>
12 <a href = "mailto:[email protected]">[email protected]</a>
13 <br />978.461.5880<br />12 Clock Tower Place, Suite 200,
14 Maynard, MA 01754
15 </p>
16 </div>

125
1 <!-- Fig. 25.8: toc.html -->

2 <!-- contents to include in another document -->

4 <p><a href = "http://www.deitel.com/books/index.html">

5 Publications/BookStore

6 </a></p>

8 <p><a href = "http://www.deitel.com/whatsnew.html">

9 What's New

10 </a></p>

11

12 <p><a href = "http://www.deitel.com/books/downloads.html">

13 Downloads/Resources

14 </a></p>

15

16 <p><a href = "http://www.deitel.com/faq/index.html">

17 FAQ (Frequently Asked Questions)

18 </a></p>

19

20 <p><a href = "http://www.deitel.com/intro.html">

21 Who we are

22 </a></p>

23

126
24 <p><a href = "http://www.deitel.com/index.html">

25 Home Page

26 </a></p>

27

28 <p>Send questions or comments about this site to

29 <a href = "mailto:[email protected]">

30 [email protected]

31 </a><br />

32 Copyright 1995-2003 by Deitel &amp; Associates, Inc.

33 All Rights Reserved.

34 </p>

127
1 <!-- Fig. 25.9: clock2.jsp -->

2 <!-- date and time to include in another document -->

4 <table>

5 <tr>

6 <td style = "background-color: black;">

7 <p class = "big" style = "color: cyan; font-size: 3em;

8 font-weight: bold;">

10 <%-- script to determine client local and --%>

11 <%-- format date accordingly --%>

12 <%

13 // get client locale


Use Locale
14 java.util.Locale locale = request.getLocale(); to format
16
15

// get DateFormat for client's Locale


Date with
17 java.text.DateFormat dateFormat = specified
18 java.text.DateFormat.getDateTimeInstance( DateForma
20
19 java.text.DateFormat.LONG,

java.text.DateFormat.LONG, locale );
t
21

22 %> <%-- end script --%>

23

24 <%-- output date --%>

25 <%= dateFormat.format( new java.util.Date() ) %>

26 </p>

27 </td>

28 </tr>

29 </table>

128
1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

5 <!-- Fig. 25.10: include.jsp -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Using jsp:include</title>

11

12 <style type = "text/css">

13 body {

14 font-family: tahoma, helvetica, arial, sans-serif;

15 }

16

17 table, tr, td {

18 font-size: .9em;

19 border: 3px groove;

20 padding: 5px;

21 background-color: #dddddd;

22 }

23 </style>

24 </head>

25

129
26 <body>

27 <table>

28 <tr>

29 <td style = "width: 160px; text-align: center">

30 <img src = "images/logotiny.png"

31 width = "140" height = "93"

32 alt = "Deitel & Associates, Inc. Logo" />

33 </td>

34

35 <td>

36

37 <%-- include banner.html in this JSP --%>

38 <jsp:include page = "banner.html"

39 flush = "true" />


Use JSP action to
40 include
41 </td> banner.html
42 </tr>

43

44 <tr>

45 <td style = "width: 160px"> Use JSP action to


46
include
47 <%-- include toc.html in this JSP --%>

48 <jsp:include page = "toc.html" flush = "true" />


toc.html
49

50 </td>

51

130
52 <td style = "vertical-align: top">

53

54 <%-- include clock2.jsp in this JSP --%>

55 <jsp:include page = "clock2.jsp" Use JSP action to


56 flush = "true" /> include
57
clock2.jsp
58 </td>

59 </tr>

60 </table>

61 </body>

62 </html>

131
include.jsp

132
<jsp:forward> Action
• <jsp:forward> action
• Enables JSP to forward request to different resources
• Can forward requests only to resources in same context
• Original JSP terminates
• <jsp:param> action
• Specifies name/value pairs of information
• Name/Value pairs are passed to other actions

133
1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

5 <!-- Fig. 25.11: forward1.jsp -->

7 <html xmlns = "http://www.w3.org/1999/xhtml">

9 <head>

10 <title>Forward request to another JSP</title>

11 </head>

12

13 <body>

14 <% // begin scriptlet

15

16 String name = request.getParameter( "firstName" );

17

18 if ( name != null ) {

19

20 %> <%-- end scriptlet to insert fixed template data --%>

21

22 <jsp:forward page = "forward2.jsp">

23 <jsp:param name = "date"


Forward request
24 value = "<%= new java.util.Date() %>" /> to
25 </jsp:forward> forward2.js
26
p

134
27 <% // continue scriptlet

28

29 } // end if

30 else {

31

32 %> <%-- end scriptlet to insert fixed template data --%>

33

34 <form action = "forward1.jsp" method = "get">

35 <p>Type your first name and press Submit</p>

36

37 <p><input type = "text" name = "firstName" />

38 <input type = "submit" value = "Submit" />

39 </p>

40 </form>

41

42 <% // continue scriptlet

43

44 } // end else

45

46 %> <%-- end scriptlet --%>

47 </body>

48

49 </html> <!-- end XHTML document -->

135
1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

5 <!-- forward2.jsp -->

7 <html xmlns = "http://www.w3.org/1999/xhtml"v

9 <head>

10 <title>Processing a forwarded request</title>

11

12 <style type = "text/css">

13 .big {

14 font-family: tahoma, helvetica, arial, sans-serif;

15 font-weight: bold;

16 font-size: 2em;

17 }

18 </style>

19 </head>
Receive request
20 from
21 <body> forward1.jsp,
<p class = "big">
22
then get
23 Hello <%= request.getParameter( "firstName" ) %>, <br />

24 Your request was received <br /> and forwarded at


firstName
25 </p> parameter from
26
request

136
27 <table style = "border: 6px outset;">

28 <tr>

29 <td style = "background-color: black;">

30 <p class = "big" style = "color: cyan;">

31 <%= request.getParameter( "date" ) %> Get date


32 </p> parameter from
33 </td>

34 </tr>
request
35 </table>

36 </body>

37

38 </html>

137
<jsp:useBean> Action
• <jsp:useBean> action
• Enables JSP to manipulate Java object
• Creates Java object or locates an existing object for use in JSP
• <jsp:getProperty name = "rotator" property = "link“
/> same as
• <%= rotator.getLink() %>

138
1 // Fig. 25.14: Rotator.java

2 // A JavaBean that rotates advertisements.

3 package com.deitel.jhtp5.jsp;

5 public class Rotator {

6 private String images[] = { "images/advjHTP1.jpg",

7 "images/cppHTP4.jpg", "images/iw3HTP2.jpg",

8 "images/jwsFEP1.jpg", "images/vbnetHTP2.jpg" };

10 private String links[] = {

11 "http://www.amazon.com/exec/obidos/ASIN/0130895601/" +

12 "deitelassociatin",

13 "http://www.amazon.com/exec/obidos/ASIN/0130384747/" +

14 "deitelassociatin",

15 "http://www.amazon.com/exec/obidos/ASIN/0130308978/" +

16 "deitelassociatin",

17 "http://www.amazon.com/exec/obidos/ASIN/0130461342/" +

18 "deitelassociatin",

19 "http://www.amazon.com/exec/obidos/ASIN/0130293636/" +

20 "deitelassociatin" };

21

22 private int selectedIndex = 0;

23

139
24 // returns image file name for current ad

25 public String getImage() Return image file


26 {
name for book cover
27 return images[ selectedIndex ];

28 }
image
29

30 // returns the URL for ad's corresponding Web site

31 public String getLink() Return hyperlink to


{
32
book at
33 return links[ selectedIndex ];

34 } Amazon.com
35

36 // update selectedIndex so next calls to getImage and

37 // getLink return a different advertisement


Update Rotator so
38 public void nextAd()

39 {
subsequent calls to
40 selectedIndex = ( selectedIndex + 1 ) % images.length; getImage and
41 } getLink return
42 }
information for
different
advertisements

140
1 <?xml version = "1.0"?>

2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

5 <!-- Fig. 25.15: adrotator.jsp -->

8
<jsp:useBean id = "rotator" scope = "application"

class = "com.deitel.jhtp5.jsp.Rotator" />


Use jsp:useBean
9
action to obtain
10 <html xmlns = "http://www.w3.org/1999/xhtml"> reference to
11
Rotator object
12 <head>

13 <title>AdRotator Example</title>

14

15 <style type = "text/css">

16 .big { font-family: helvetica, arial, sans-serif;

17 font-weight: bold;

18 font-size: 2em }

19 </style>

20

21 <%-- update advertisement --%>

22 <% rotator.nextAd(); %>

23 </head>
Invoke
24 Rotator’s
nextAd method

141
25 <body>

26 <p class = "big">AdRotator Example</p>

27

28 <p> Define hyperlink


29 <a href = "<jsp:getProperty name = "rotator" to Amazon.com
30 property = "link" />">
site
31

32 <img src = "<jsp:getProperty name = "rotator"

33 property = "image" />" alt = "advertisement" />

34 </a>

35 </p>

36 </body>

37 </html>

142

You might also like