You are on page 1of 182

2 Days Workshop

“Developing Java Web App


Using Servlet & JSP”
Introduction To
Java Web Application
Web Components & Container
Browser Web Container EJB Container

Applet HTTP/ JSP Servlet RMI EJB


HTTPS

J2SE

RMI/IIOP
JavaMail

RMI/IIOP
JavaMail

JDBC
JDBC
JMS
JNDI

JTA

JNDI

JMS

JTA
App Client JAF
Container JAF
App HTTP/ J2SE
Client HTTPS
RMI
RMI/IIOP

JDBC
JNDI
JMS

J2SE J2SE

Database
4
Web Components & Container
● Web components are in the form of either Servlet
or JSP (JSP is converted into Servlet)
● Web components run in a Web container
– Tomcat/Jetty are popular web containers
– All J2EE compliant app servers (GlassFish,
WebSphere, WebLogic, JBoss) provide web
containers
● Web container provides system services to Web
components
– Request dispatching, security, and life cycle
management
5
Web Application & Components
● Web Application is a deployable package
– Web components (Servlets and JSP's)
– Static resource files such as images
– Helper classes
– Libraries
– Deployment descriptor (web.xml file)
● Web Application can be represented as
– A hierarchy of directories and files (unpacked form) or
– *.WAR file reflecting the same hierarchy (packed form)

6
Technologies Used
In Web Application

7
Web Request Handling

8
Java Web Application Technologies

9
Web Application
Development and
Deployment Steps

10
Web Application Development
and Deployment Steps
1.Write (and compile) the Web component code
(Servlet or JSP) and helper classes referenced
by the web component code
2.Create any static resources (for example,
images, HTML pages, CSS files)
3.Create deployment descriptor (web.xml)
4.Build the Web application (*.war file or
deployment-ready directory)
5.Deploy the web application into a Web
container
● Web clients are now ready to access them via URL 11
1. Write and compile the Web
component code
● Create development tree structure
● Write either servlet code or JSP pages
along with related helper code
● Create build.xml for Ant-based build (and
other application development life-cycle
management) process
● IDE (i.e. NetBeans, Eclipse) or Maven
handle all these chores
12
Development Tree Structure
● Keep Web application source separate from
compiled files
– facilitate iterative development
● Root directory
– build.xml: Ant build file
– src: Java source of servlets and JavaBeans
components
– web: JSP pages and HTML pages, images

13
Example: hello2 Tree Structure
(before “ant build” command)
● Hello2
– src/servlets
● GreetingServlet.java

● ResponseServlet.java

– web
● WEB-INF

– web.xml
● duke.waving.gif

– build.xml
14
2. Create any static resources
● HTML pages
– Custom pages
– Login pages
– Error pages
● Image files that are used by HTML pages or
JSP pages
– Example: duke.waving.gif

15
3. Create deployment
descriptor (web.xml)
● Deployment descriptor contains
deployment time runtime instructions to
the Web container
– URL that the client uses to access the web
component
● Every web application has to have it

16
4. Build the Web application
● Either *.WAR file or unpacked form of *.WAR
file
● Build process is made of
– create build directory (if it is not present) and its
subdirectories
– compile Java code into build/WEB-INF/classes
directory
● Java classes reside under ./WEB-INF/classes
directory
– copy web.xml file into build/WEB-INF directory
– copy image files into build directory
17
Example: hello2 Tree Structure

● Hello1
– src
– web
– build.xml
– build
● WEB-INF

– classes
● GreetingServlet.class

● ResponseServlet.class

– web.xml
● duke.waving.gif
18
5. Deploy Web application
● Deploy the application over deployment
platform such as GlassFish or Tomcat
● 3 ways to deploy to GlassFish
– NetBeans
– GlassFish admin console
– Command line tool (asadmin of GlassFish)
asadmin deploy --port 4848 --host localhost –passwordfile
"c:\j2eetutorial\examples\common\admin-password.txt" --user admin
hello2.war (asant deploy-war)

19
6. Perform Client Access to
Web Application
● From a browser, go to URL of the Web
application

20
http://localhost:8080/hello1/greeting

21
Running Web Application

22
Web Application
Archive (*.WAR)

23
Web Application
● Web application can be deployed in two
different forms
– a *.war file or
– an unpacked directory laid out in the same
format as a *.war file (build directory)
● Use *.war file when you have to deploy on
a remote machine

24
What is *.WAR file?
● Ready to deploy'able package over web
container
● Similar to *.jar file
● Contains things to be deployed
– Web components (servlets or JSP's)
– Server-side utility classes
– Static Web presentation content (HTML, image,
etc)
● Reflects contents in build directory
25
Document Root & Context
● Document Root of the Web application
– Top-level directory of WAR
– Contains JSP pages, client-side classes and
archives, and static Web resources are stored
– Also contains WEB-INF directory
● A context is a name that gets mapped to
the document root of a Web application
– /hello1 is context for hello1 example
– Distinguishes a Web application in a single Web
container
– Has to be specified as part of client URL 26
Directory Structure of
*.WAR file

27
Directory Structure of
*.WAR file

28
How to Create *.WAR file?
● 3 different ways
– Use IDE (NetBeans, Eclipse)
– Use Maven
– Use ant tool after putting proper build
instruction in build.xml file
● “asant create-war” (under J2EE 1.4

tutorial)
– Use “jar cvf <filename>.war .” command
under build directory

29
Example: Creating hello2.war via
“asant create-war” command
C:\j2eetutorial14\examples\web\hello2>asant create-war
Buildfile: build.xml
...
create-war:
[echo] Creating the WAR....
[delete] Deleting:
C:\j2eetutorial14\examples\web\hello2\assemble\war\hello2.war
[delete] Deleting directory
C:\j2eetutorial14\examples\web\hello2\assemble\war\WEB-INF
[copy] Copying 1 file to
C:\j2eetutorial14\examples\web\hello2\assemble\war\WEB-INF
[copy] Copying 2 files to
C:\j2eetutorial14\examples\web\hello2\assemble\war\WEB-INF\classes
[war] Building war:
C:\j2eetutorial14\examples\web\hello2\assemble\war\hello2.war
[copy] Copying 1 file to C:\j2eetutorial14\examples\web\hello2 30
Example: Creating hello2.war via
jar command
C:\j2eetutorial14\examples\web\hello2\build>jar cvf hello2.war .
added manifest
adding: duke.waving.gif(in = 1305) (out= 1295)(deflated 0%)
adding: servlets/(in = 0) (out= 0)(stored 0%)
adding: servlets/GreetingServlet.class(in = 1680) (out= 887)(deflated 47%)
adding: servlets/ResponseServlet.class(in = 1090) (out= 572)(deflated 47%)

C:\j2eetutorial14\examples\web\hello2\build>jar xvf hello2.war


created: META-INF/
extracted: META-INF/MANIFEST.MF
extracted: duke.waving.gif
created: servlets/
extracted: servlets/GreetingServlet.class
extracted: servlets/ResponseServlet.class

31
WEB-INF Directory
● Subdirectory of Document root
● Contains
– web.xml : Web application deployment descriptor
– JSP tag library descriptor files
– Classes : A directory that contains server-side
classes: servlets, utility classes, and JavaBeans
components
– lib : A directory that contains JAR archives of
libraries (tag libraries and any utility libraries
called by server-side classes)
32
HTTP request URL & Web
component URL (alias) & Context
● Request URL: User specified access point of
a web resource
– http://[host]:[port]/[request path]?[query string]
– [request path] is made of context and web component's
URL
– http://localhost:8080/hello1/greeting?username=Monica
● Context: Name of the root document of a web
application – Identifies a particular application
on that server
– /hello1 is context 33
Configuring
Web Application via
web.xml

34
Configuring Web Application
● Configuration information is specified in
web.xml (Web Applications Deployment
Descriptor)

35
Web Applications Deployment
Descriptor (web.xml)
● Prolog
● Alias Paths
● Context and Initialization Parameters
● Event Listeners
● Filter Mappings
● Error Mappings
● Reference to Environment Entries, Resource
environment entries, or Resources

36
Web Applications Deployment
Descriptor (web.xml)
● Case sensitive
● Order sensitive (in the following order)
– icon, display-name, description, distributable
– context-param, filter, filter-mapping
– listener, servet, servlet-mapping, session-config
– mime-mapping, welcome-file-list
– error-page, taglib, resource-env-ref, resource-ref
– security-constraint, login-config, security-role
– env-entry, ejb-ref, ejb-local-ref
37
Prolog (of web.xml)
● Every XML document needs a prolog
<?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">

38
Alias Paths (of web.xml)
● When a request is received by Servlet container,
it must determine which Web component in a
which web application should handle the request.
It does so by mapping the URL path contained in
the request to a Web component
● A URL path contains the context root and alias
path
– http://<host>:8080/context_root/alias_path
● Alias Path can be in the form of either
– /alias-string (for servlet) or
– /*.jsp (for JSP)
39
Alias Paths (of web.xml)
<servlet>
<servlet-name>greeting</servlet-name>
<display-name>greeting</display-name>
<description>no description</description>
<servlet-class>GreetingServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>response</servlet-name>
<display-name>response</display-name>
<description>no description</description>
<servlet-class>ResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>greeting</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>response</servlet-name>
<url-pattern>/response</url-pattern>
</servlet-mapping> 40
Context and Initialization
Parameters (of web.xml)
● Represents application context
● Can be shared among Web components in a WAR file
<web-app>
...
<context-param>
<param-name>
javax.servlet.jsp.jstl.fmt.localizationContext
</param-name>
<param-value>messages.BookstoreMessages</param-value>
</context-param>
...
</web-app>

41
Event Listeners (of web.xml)
● Receives servlet life-cycle events

<listener>
<listener-class>listeners.ContextListener</listener-class>
</listener>

42
Filter Mappings (of web.xml)
● Specify which filters are applied to a
request, and in what order

<filter>
<filter-name>OrderFilter<filter-name>
<filter-class>filters.OrderFilter<filter-class>
</filter>
<filter-mapping>
<filter-name>OrderFilter</filter-name>
<url-pattern>/receipt</url-pattern>
</filter-mapping>

43
Error Mappings (of web.xml)
● Maps status code retURLed in an HTTP
response to a Java programming language
exception retURLed by any Web
component and a Web resource

<error-page>
<exception-type>exception.OrderException</exception-type>
<location>/errorpage.html</location>
</error-page>

44
References (of web.xml)
● Need when web components make
references to environment entries,
resource environment entries, or resources
such as databases
● Example: declare a reference to the data
source
<resource-ref>
<res-ref-name>jdbc/BookDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
45
Example web.xml of hello2
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>hello2</display-name>
<servlet>
<display-name>GreetingServlet</display-name>
<servlet-name>GreetingServlet</servlet-name>
<servlet-class>servlets.GreetingServlet</servlet-class>
</servlet>
<servlet>
<display-name>ResponseServlet</display-name>
<servlet-name>ResponseServlet</servlet-name>
<servlet-class>servlets.ResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GreetingServlet</servlet-name>
<url-pattern>/greeting</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ResponseServlet</servlet-name>
<url-pattern>/response</url-pattern>
</servlet-mapping>
</web-app> 46
Java Servlet
Part I
What is Servlet?

4
What is Servlet?
● Java™ objects which are based on
Servlet framework and APIs
● Extend the functionality of a HTTP
server for creating dynamic contents
● Mapped to URLs and managed by
container with a simple architecture
● Available and running on all major
web servers and app servers
● Platform and server independent
5
Static vs. Dynamic Contents
● Static contents
– Typically static HTML page
– Same display for everyone
● Dynamic contents
– Contents is dynamically generated based on
conditions
– Conditions could be
● User identity
● Time of the day
● User entered values through forms and selections
– Examples
● ETrade webpage customized just for you, my Yahoo 6
First Servlet Code

Public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response){

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>Hello World!</title>");

}
...
}

7
CGI versus Servlet
CGI Servlet
 Written in C, C++,  Written in Java
Visual Basic and Perl  Powerful, reliable, and
 Difficult to maintain, efficient
non-scalable, non-  Improves scalability,
manageable reusability (component
 Prone to security based)
problems of  Leverages built-in
programming language security of Java
 Resource intensive programming language
and inefficient  Platform independent and
 Platform and portable
application-specific

8
Servlet vs. CGI

Request
RequestCGI1
CGI1 Child
Childfor
for CGI1
CGI1
Request CGI
CGI
RequestCGI2
CGI2 Based Child
Based Childfor
for CGI2
CGI2
Webserver
Webserver
Request
RequestCGI1
CGI1 Child
Childfor
for CGI1
CGI1

Request
RequestServlet1
Servlet1 Servlet
Servlet Based
Based Webserver
Webserver
Request Servlet1
RequestServlet2
Servlet2 Servlet1
JVM
JVM
Request Servlet1 Servlet2
Servlet2

9
Advantages of Servlet over CGI
● No CGI limitations
● Abundant third-party tools and Web
servers supporting Servlet
● Access to entire family of Java APIs
● Reliable, better performance and scalability
● Platform and server independent
● Secure
● Most servers allow automatic reloading of
Servlet's by administrative action
10
Servlet in a
Big Picture of Java EE
Application

11
Where are Servlet and JSP?

Web Tier EJB Tier

12
Servlet Request &
Response Model

13
Servlet Request and Response
Model
Servlet Container
Request

Browser
HTTP Request
Servlet
Response

Web Response
Server

14
What does Servlet Do?

1.Receives client request (mostly in the form of


HTTP request)
2.Extract some information from the request
3.Do perform business logic processing
(possibly by accessing database, invoking
EJBs, web services etc)
4.Create and send response to client (mostly in
the form of HTTP response) or forward the
request to another servlet or JSP page

15
Requests and Responses
● What is a request?
– Information that is sent from client to a server
● Who made the request

● What user-entered data is sent

● Which HTTP headers are sent

● What is a response?
– Information that is sent to client from a server
● Text(html, plain) or binary(image) data

● HTTP headers, cookies, etc

16
HTTP

● HTTP request contains


– header
– a HTTP method
● Get: Input form data is passed as part of URL
● Post: Input form data is passed within message body
● Put
– request data

17
HTTP GET and POST
● The most common HTTP methods
● HTTP GET requests:
– User entered information is appended to the URL in a
query string
– Can only send limited amount of data as query param's
● .../servlet/ViewCourse?FirstName=Sang&LastName=Shin
● HTTP POST requests:
– User entered information is sent as data (not appended
to URL)
– Can send any amount of data

18
First Servlet Again
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

Public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First Servlet</title>");
out.println("<big>Hello Code Camp!</big>");

}
}

19
Interfaces & Classes
of Servlet

20
Servlet Interfaces & Classes
Servlet

GenericServlet HttpSession

You will work with


mostly with HttpServlet HttpServlet

ServletRequest ServletResponse

HttpServletRequest HttpServletResponse

21
Servlet Life-Cycle

22
Servlet Life-Cycle
Is Servlet Loaded?

Http
request
Load Invoke
No

Http
response Yes
Run
Servlet
Servlet Container

Client Server

23
HttpServlet Life Cycle Methods
service( )

init( ) destroy( )
Ready
Init parameters

You will work


mostly with
doGet() & doPost()
doGet( ) doPost( )
Request parameters 24
Servlet Life Cycle Methods
● Invoked by container
– Container controls life cycle of a servlet
● Defined in
– javax.servlet.GenericServlet class or
● init()

● destroy()

● service() - this is an abstract method

– javax.servlet.http.HttpServlet class
● service() - implementation

● doGet(), doPost(), doXxx()


25
Servlet Life Cycle Methods
● init()
– Invoked once when the servlet is first instantiated
– Perform any set-up in this method
● Read init parameters
● Setting up a database connection
● destroy()
– Invoked before servlet instance is removed
– Perform any clean-up
● Closing a previously created database connection
26
Example: init() reading
Configuration parameters
public void init(ServletConfig config) throws
ServletException {
super.init(config);
String driver = getInitParameter("driver");
String fURL = getInitParameter("url");
try {
openDBConnection(driver, fURL);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e){
e.printStackTrace();
}
}
27
Setting Init Parameters in web.xml

<web-app>
<servlet>
<servlet-name>chart</servlet-name>
<servlet-class>ChartServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>
COM.cloudscape.core.RmiJdbcDriver
</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>
jdbc:cloudscape:rmi:CloudscapeDB
</param-value>
</init-param>
</servlet>
...
</web-app>
28
Servlet Life Cycle Methods
● service() javax.servlet.GenericServlet class
– Abstract method
● service() in javax.servlet.http.HttpServlet class
– Concrete method (implementation)
– Dispatches to doGet(), doPost(), etc
– Do not override this service() method!
● doGet(), doPost(), doXxx() in
javax.servlet.http.HttpServlet
– Handles HTTP GET, POST, etc. requests
– Override these methods in your servlet to provide
desired behavior
29
service() & doGet()/doPost()
● service() methods take generic
requests and responses:
– service(ServletRequest request,
ServletResponse response)
● doGet() or doPost() take HTTP
requests and responses:
– doGet(HttpServletRequest request,
HttpServletResponse response)
– doPost(HttpServletRequest request,
HttpServletResponse response)
30
Service() Method
GenericServlet
Server subclass
Subclass of
GenericServlet class
Request

Service( )

Response

Key: Implemented by subclass 31


doGet() and doPost() Methods
Server HttpServlet subclass

doGet( )
Request

Service( )

Response doPost( )

Key: Implemented by subclass


32
Typical Things You Do in doGet() &
doPost()
● Extract client-sent information (HTTP
parameter) from HTTP request
● Set (Save) and get (read) attributes to/from
Scope objects
● Perform some business logic or access
database
● Optionally forward the request to other Web
components (Servlet or JSP)
● Populate HTTP response message and send it
to client 33
Example: Simple doGet()
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

Public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Just send back a simple HTTP response


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<title>First Servlet</title>");
out.println("<big>Hello J2EE Programmers! </big>");
}
} 34
Example: Sophisticated doGet()
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Read session-scope attribute “messages”


HttpSession session = request.getSession(true);
ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");

// Set headers and buffer size before accessing the Writer


response.setContentType("text/html");
response.setBufferSize(8192);
PrintWriter out = response.getWriter();

// Then write the response (Populate the header part of the response)
out.println("<html>" +
"<head><title>" + messages.getString("TitleBookDescription") +
"</title></head>");

// Get the dispatcher; it gets the banner to the user


RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/banner");

if (dispatcher != null)
dispatcher.include(request, response);
35
Example: Sophisticated doGet()
// Get request parameter (Get the identifier of the book to display)
String bookId = request.getParameter("bookId");
if (bookId != null) {

// and the information about the book (Perform business logic)


try {
BookDetails bd = bookDB.getBookDetails(bookId);
Currency c = (Currency)session.getAttribute("currency");
if (c == null) {
c = new Currency();
c.setLocale(request.getLocale());
session.setAttribute("currency", c);
}
c.setAmount(bd.getPrice());

// Print out the information obtained


out.println("...");
} catch (BookNotFoundException ex) {
response.resetBuffer();
throw new ServletException(ex);
}

}
out.println("</body></html>");
out.close();
}
36
Steps of Populating HTTP
Response
● Fill Response headers
● Set some properties of the response
– Buffer size
● Get an output stream object from the
response
● Write body content to the output stream

37
Example: Simple Response
Public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Fill response headers


response.setContentType("text/html");
// Set buffer size
response.setBufferSize(8192);
// Get an output stream object from the response
PrintWriter out = response.getWriter();
// Write body content to output stream
out.println("<title>First Servlet</title>");
out.println("<big>Hello J2EE Programmers! </big>");
}
}
38
Servlet Request
(HttpServletRequest)

39
What is Servlet Request?
● Contains data passed from client to servlet
● All servlet requests implement ServletRequest
interface which defines methods for accessing
– Client sent parameters
– Object-valued attributes
– Locales
– Client and server
– Input stream
– Protocol information
– Content type
– If request is made over secure channel (HTTPS) or not
40
Requests
data,
client, server, header
servlet itself
Request Servlet 1

Servlet 2

Response Servlet 3

Web Server 41
Getting Client Sent Parameters
● A request can come with any number of
parameters
● Parameters are sent from HTML forms:
– GET: as a query string, appended to a URL
– POST: as encoded POST data, not appeared in the
URL
● getParameter("parameterName")
– Returns the value of parameterName
– Returns null if no such parameter is present
– Works identically for GET and POST requests
42
A Sample FORM using GET
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Collecting Three Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Please Enter Your Information</H1>

<FORM ACTION="/sample/servlet/ThreeParams">
First Name: <INPUT TYPE="TEXT" NAME="param1"><BR>
Last Name: <INPUT TYPE="TEXT" NAME="param2"><BR>
Class Name: <INPUT TYPE="TEXT" NAME="param3"><BR>
<CENTER>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>

</BODY>
</HTML>

43
A Sample FORM using GET

44
A FORM Based Servlet: Get
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Simple servlet that reads three parameters from the html form */
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Your Information";
out.println("<HTML>" +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<UL>\n" +
" <LI><B>First Name in Response</B>: "
+ request.getParameter("param1") + "\n" +
" <LI><B>Last Name in Response</B>: "
+ request.getParameter("param2") + "\n" +
" <LI><B>NickName in Response</B>: "
+ request.getParameter("param3") + "\n" +
"</UL>\n" +
"</BODY></HTML>");
}
}
45
A Sample FORM using POST
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>A Sample FORM using POST</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">A Sample FORM using POST</H1>
<FORM ACTION="/sample/servlet/ShowParameters" METHOD="POST">
Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR>
Quantity: <INPUT TYPE="TEXT" NAME="quantity"><BR>
Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR>
First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR>
<TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
Credit Card Number:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
<CENTER>
<INPUT TYPE="SUBMIT" VALUE="Submit Order">
</CENTER>
</FORM>
</BODY>
</HTML>
46
A Sample FORM using POST

47
A Form Based Servlet: POST
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ShowParameters extends HttpServlet {


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

48
Who Set Object/value Attributes

● Request attributes can be set in two ways


– Servlet container itself might set attributes to make
available custom information about a request
● example: javax.servlet.request.X509Certificate attribute
for HTTPS
– Servlet set application-specific attribute
● void setAttribute(java.lang.String name,
java.lang.Object o)

49
Getting Locale Information
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

HttpSession session = request.getSession();


ResourceBundle messages =
(ResourceBundle)session.getAttribute("messages");

if (messages == null) {
Locale locale=request.getLocale();
messages = ResourceBundle.getBundle(
"messages.BookstoreMessages", locale);
session.setAttribute("messages", messages);
}

50
Getting Client Information
● Servlet can get client information from the
request
– String request.getRemoteAddr()
● Get client's IP address
– String request.getRemoteHost()
● Get client's host name

51
Getting Server Information
● Servlet can get server's information:
– String request.getServerName()
● e.g. "www.sun.com"
– int request.getServerPort()
● e.g. Port number "8080"

52
Getting Misc. Information
● Input stream
– ServletInputStream getInputStream()
– java.io.BufferedReader getReader()
● Protocol
– java.lang.String getProtocol()
● Content type
– java.lang.String getContentType()
● Is secure or not (if it is HTTPS or not)
– boolean isSecure()
53
Cookie Method (in
HTTPServletRequest)
● Cookie[] getCookies()
– Returns an array containing all of the Cookie objects
the client sent with this request

54
HTTP Request URL

55
HTTP Request URL
● Contains the following parts
– http://[host]:[port]/[request path]?[query string]

56
HTTP Request URL: [request path]
● http://[host]:[port]/[request path]?[query string]
● [request path] is made of
– Context: /<context of web app>
– Servlet name: /<component alias>
– Path information: the rest of it
● Examples
– http://localhost:8080/hello1/greeting
– http://localhost:8080/hello1/greeting.jsp
– http://daydreamer/catalog/lawn/xyz.jsp

57
HTTP Request URL: [query string]
● http://[host]:[port]/[request path]?[query string]
● [query string] are composed of a set of parameters
and values that are user entered
● Two ways query strings are generated
– A query string can explicitly appear in a web page
● <a href="/bookstore1/catalog?Add=101">Add To Cart</a>
● String bookId = request.getParameter("Add");
– A query string is appended to a URL when a form
with a GET HTTP method is submitted
● http://localhost/hello1/greeting?username=Monica
● String userName=request.getParameter(“username”)
58
Context, Path, Query, Parameter
Methods
● String getContextPath()
● String getQueryString()
● String getPathInfo()
● String getPathTranslated()

59
HTTP Request Headers

60
HTTP Request Headers
● HTTP requests include headers which
provide extra information about the
request
● Example of HTTP 1.1 Request:
GET /search? keywords= servlets+ jsp HTTP/ 1.1
Accept: image/ gif, image/ jpg, */*
Accept-Encoding: gzip
Connection: Keep- Alive
Cookie: userID= id456578
Host: www.sun.com
Referer: http:/www.jpassion.com/codecamp.html
User-Agent: Mozilla/ 4.7 [en] (Win98; U)
61
HTTP Request Headers
● Accept
– Indicates MIME types browser can handle.
● Accept-Encoding
– Indicates encoding (e. g., gzip or compress)
browser can handle
● Etc.

62
HTTP Header Methods
● String getHeader(java.lang.String name)
– value of the specified request header as String
● java.util.Enumeration getHeaders(java.lang.String
name)
– values of the specified request header
● java.util.Enumeration getHeaderNames()
– names of request headers
● int getIntHeader(java.lang.String name)
– value of the specified request header as an int

63
Showing Request Headers
//Shows all the request headers sent on this particular request.
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Servlet Example: Showing Request Headers";
out.println("<HTML>" + ...
"<B>Request Method: </B>" +
request.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" +
request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" +
request.getProtocol() + "<BR><BR>\n" +
...
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
...
}
}

64
Request Headers Sample

65
Java Servlet
Part II
Servlet Response
(HttpServletResponse)

3
What is Servlet Response?
● Contains data passed from servlet to client
● All servlet responses implement
ServletResponse interface
– Retrieve an output stream
– Indicate content type
– Indicate whether to buffer output
– Set localization information
● HttpServletResponse extends ServletResponse
– HTTP response status code
– Cookies

4
Responses

Request Servlet 1

Response Structure: Servlet 2


status code , headers
and body.

Response Servlet 3

Web Server
5
Response Structure

Status Code

Response Headers

Response Body

6
Status Code in
Http Response
7
HTTP Response Status Codes
● Why do we need HTTP response status
code?
– Forward client to another page
– Indicates resource is missing
– Instruct browser to use cached copy

8
Methods for Setting HTTP
Response Status Codes
● public void setStatus(int statusCode)
– Status codes are defined in HttpServletResponse
– Status codes are numeric fall into five general
categories:
● 100-199 Informational
● 200-299 Successful
● 300-399 Redirection
● 400-499 Incomplete
● 500-599 Server Error
– Default status code is 200 (OK) 9
Example of HTTP Response
Status
HTTP/ 1.1 200 OK
Content-Type: text/ html
<! DOCTYPE ...>
<HTML
...
</ HTML>

10
Common Status Codes
● 200 (SC_OK)
– Success and document follows
– Default for servlets
● 204 (SC_No_CONTENT)
– Success but no response body
– Browser should keep displaying previous
document
● 301 (SC_MOVED_PERMANENTLY)
– The document moved permanently (indicated
in Location header)
– Browsers go to new location automatically
11
Common Status Codes
● 302 (SC_MOVED_TEMPORARILY)
– Redirect
– Servlets should use sendRedirect, not
setStatus, when setting this header
● 401 (SC_UNAUTHORIZED)
– Browser tried to access password- protected
page without proper Authorization header
● 404 (SC_NOT_FOUND)
– No such page

12
Methods for Sending Error

● Error status codes (400-599) can be


used in sendError methods.
● public void sendError(int code)
– The server may give the error special
treatment
● public void sendError(int code, String
message)
– Wraps message inside small HTML
document
13
setStatus() & sendError()
try {
returnAFile(fileName, out)
}
catch (FileNotFoundException e){
response.setStatus(response.SC_NOT_FOUND);
out.println("Response body");
}

has same effect as

try {
returnAFile(fileName, out)
}
catch (FileNotFoundException e){
response.sendError(response.SC_NOT_FOUND);
}
14
Header in
Http Response
16
Why HTTP Response Headers?
● Give forwarding location
● Specify cookies
● Supply the page modification date
● Instruct the browser to reload the page
after a designated interval
● Give the file size so that persistent HTTP
connections can be used
● Designate the type of document being
generated
● etc.
17
Methods for Setting Arbitrary
Response Headers
● public void setHeader( String headerName, String
headerValue)
– Sets an arbitrary header.
● public void setDateHeader( String name, long millisecs)
– Converts milliseconds since 1970 to a date string in
GMT format
● public void setIntHeader( String name, int headerValue)
– Prevents need to convert int to String before calling
setHeader
● addHeader, addDateHeader, addIntHeader
– Adds new occurrence of header instead of replacing.
18
Methods for setting Common
Response Headers
● setContentType
– Sets the Content- Type header. Servlets almost
always use this.
● setContentLength
– Sets the Content- Length header. Used for
persistent HTTP connections.
● addCookie
– Adds a value to the Set- Cookie header.
● sendRedirect
– Sets the Location header and changes status
code. 19
Common HTTP 1.1 Response
Headers
● Location
– Specifies a document's new location.
– Use sendRedirect() method instead of setting
this directly
● Refresh
– Specifies a delay before the browser
automatically reloads a page
● Set-Cookie
– The cookies that browser should remember
– Don’t set this header directly
– Use addCookie(Cookie cookie) method instead.20
Common HTTP 1.1 Response
Headers (cont.)
● Cache-Control (1.1) and Pragma (1.0)
– A no-cache value prevents browsers from
caching page. Send both headers or check
HTTP version.
● Content- Encoding
– The way document is encoded. Browser
reverses this encoding before handling
document.
● Content- Length
– The number of bytes in the response. Used for
persistent HTTP connections.
21
Common HTTP 1.1 Response
Headers (cont.)
● Content-Type
– The MIME type of the document being returned.
– Use setContentType() method to set this
header.
● Last-Modified
– The time document was last changed

22
Refresh Sample Code

public class DateRefresh extends HttpServlet {


public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
res.setHeader("Refresh", "5");
out.println(new Date().toString());
}
}

23
Body in
Http Response
24
Writing a Response Body
● A servlet almost always returns a response body
● Response body could either be a PrintWriter or a
ServletOutputStream
● PrintWriter
– Obtained via response.getWriter()
– For character-based output
● ServletOutputStream
– Using response.getOutputStream()
– For binary (image) data

25
Scope Objects

26
Scope Objects

● Enables sharing information among collaborating


web components via attributes maintained in
Scope objects
– Attributes are name/object pairs
● Attributes maintained in the Scope objects are
accessed with
– getAttribute() & setAttribute()
● 4 Scope objects are defined
– Web context, session, request, page

27
Four Scope Objects: Accessibility
● Web context (ServletConext)
– Accessible from Web components within a Web
context
● Session
– Accessible from Web components handling a request
that belongs to the session
● Request
– Accessible from Web components handling the
request
● Page
– Accessible from JSP page that creates the object
28
Four Scope Objects: Class
● Web context
– javax.servlet.ServletContext
● Session
– javax.servlet.http.HttpSession
● Request
– javax.servlet.http.HttpServletRequest
● Page
– javax.servlet.jsp.PageContext

29
Web Context
(ServletContext)
30
What is ServletContext For?
● Used by servets to
– Set and get context-wide (application-wide)
object-valued attributes
– Get request dispatcher
● To forward to or include web component
– Access Web context-wide initialization
parameters set in the web.xml file
– Access Web resources associated with the
Web context
– Log
– Access other misc. information
31
Scope of ServletContext
● Context-wide scope
– Shared by all servlets and JSP pages within a
"web application"
● Why it is called “web application scope”
● All servlets in BookStore web application share
same ServletContext object
– There is one ServletContext object per "web
application"

32
ServletContext:
Web Application Scope

Client 1

ServletContext
server

application

Client 2

33
How to Access ServletContext
Object?
● Within your servlet code, call
getServletContext()

● The ServletContext is contained in


ServletConfig object, which the Web server
provides to a servlet when the servlet is
initialized
– init (ServletConfig servletConfig) in Servlet
interface
34
Example: Getting Attribute Value
from ServletContext
public class CatalogServlet extends HttpServlet {
private BookDB bookDB;
public void init() throws ServletException {
// Get context-wide attribute value from
// ServletContext object
bookDB = (BookDB)getServletContext().
getAttribute("bookDB");
if (bookDB == null) throw new
UnavailableException("Couldn't get database.");
}
}

35
Session
(HttpSession)
We will talk more on
HTTPSession
later in “Session Tracking” 36
Why HttpSession?
● Need a mechanism to maintain client state
across a series of requests from a same user (or
originating from the same browser) over some
period of time
– Example: Online shopping cart
● Yet, HTTP is stateless
● HttpSession maintains client state
– Used by Servlets to set and get the values of
session scope attributes

37
How to Get HttpSession?
● via getSession() method of a Request
object (HttpServletRequest)

38
Example: HttpSession
public class CashierServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

// Get the user's session and shopping cart


HttpSession session = request.getSession();
ShoppingCart cart =
(ShoppingCart)session.getAttribute("cart");
...
// Determine the total price of the user's books
double total = cart.getTotal();

39
Init Parameters

41
Setting Context Init Parameters
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" ...>
<context-param>
<param-name>city</param-name>
<param-value>Seoul</param-value>
</context-param>
<context-param>
<param-name>age</param-name>
<param-value>22</param-value>
</context-param>
<servlet>
<display-name>GreetingServlet</display-name>
<servlet-name>GreetingServlet</servlet-name>
<servlet-class>servlets.GreetingServlet</servlet-
class>
</servlet>

42
Reading Context Init Parameters
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();

// then write the data of the response


String username = request.getParameter("username");

if ((username != null) && (username.length() > 0)) {


out.println("<h2>Hello, " + username + "!</h2>");
out.println("<h2>You live in " +
getServletContext().getInitParameter("city") + "!</h2>");
out.println("<h2>Your age is " +
getServletContext().getInitParameter("age") + "!</h2>");
}

43
Setting Servlet Init Parameters
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" ...>
<servlet>
<display-name>GreetingServlet</display-name>
<servlet-name>GreetingServlet</servlet-name>
<servlet-class>servlets.GreetingServlet</servlet-class>
<init-param>
<param-name>greeting1</param-name>
<param-value>hello</param-value>
</init-param>
</servlet>
<servlet>
<display-name>GreetingServlet2</display-name>
<servlet-name>GreetingServlet2</servlet-name>
<servlet-class>servlets.GreetingServlet2</servlet-class>
<init-param>
<param-name>greeting2</param-name>
<param-value>goodbye</param-value>
</init-param>
</servlet>
44
Reading Servlet Init Parameters
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();

// then write the data of the response


String username = request.getParameter("username");

if ((username != null) && (username.length() > 0)) {


out.println("<h2>Hello, " + username + "!</h2>");
out.println("<h2>You live in " +
getServletContext().getInitParameter("city") + "!</h2>");
out.println("<h2>Your age is " +
getServletContext().getInitParameter("age") + "!</h2>");
out.println("<h2>Your greeting message is " +
getInitParameter("greeting3") + "!</h2>");

}
45
Handling Errors

47
Handling Errors
● Web container generates default error page
● You can specify custom default page to be
displayed instead
● Steps to handle errors
– Create appropriate error html pages for error
conditions
– Modify the web.xml accordingly

48
Example: Setting Error Pages in
web.xml
<error-page>
<exception-type>
exception.BookNotFoundException
</exception-type>
<location>/errorpage1.html</location>
</error-page>
<error-page>
<exception-type>
exception.BooksNotFoundException
</exception-type>
<location>/errorpage2.html</location>
</error-page>
<error-page>
<exception-type>exception.OrderException</exception-type>
<location>/errorpage3.html</location>
</error-page> 49
RequestDispatcher

51
Example: Getting and Using
RequestDispatcher Object
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

HttpSession session = request.getSession(true);


ResourceBundle messages = (ResourceBundle)session.getAttribute("messages");

// set headers and buffer size before accessing the Writer


response.setContentType("text/html");
response.setBufferSize(8192);
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title>" + messages.getString("TitleBookDescription") +
"</title></head>");

// Get the dispatcher; it gets the banner to the user


RequestDispatcher dispatcher =
session.getServletContext().getRequestDispatcher("/banner");

if (dispatcher != null)
dispatcher.include(request, response);
...
52
Logging
54
Example: Logging
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

...
getServletContext().log(“Life is good!”);
...
getServletContext().log(“Life is bad!”, someException);

55
Java Server Pages
(JSP)
Agenda
● What is JSP?
● JSP vs Servlet
● JSP/Servlet in big picture of Java EE
● JSP architecture
● Life-cycle of a JSP page
● Steps for building JSP-based web application

2
What is JSP?

3
What is JSP page?
● A text-based document capable of
returning dynamic content to a client
browser
– It looks and feels like a HTML page
● Contains both static and dynamic content
– Static content: via HTML, XML
– Dynamic content: via programming code (not
recommended), and JavaBeans, custom tags

4
Why JSP Technology?
● Enables separation of business logic from
presentation
– Presentation is in the form of HTML or XML/XSLT
– Business logic is implemented as Java Beans or
custom tags
– Better maintainability, reusability (than just using
servlets only)
● Extensible via custom tags
● Builds on Servlet technology
– A JSP gets compiled into Servlet before
deployment

5
JSP Sample Code
<html>
Hello World!
<br>
<jsp:useBean id="clock"
class=“calendar.JspCalendar” />
Today is
<ul>
<li>Day of month: <%= clock.getDayOfMonth() %>
<li>Year: <%= clock.getYear() %>
</ul>
</html>

6
Static vs. Dynamic Contents
● Static contents
– Typically static HTML page
– Same display for everyone
● Dynamic contents
– Contents is dynamically generated based on conditions
– Conditions could be
● User identity
● Time of the day
● User entered values through forms and selections
– Examples
● Etrade webpage customized just for you, my Yahoo

7
A Simple JSP Page
(Blue: static, Red: Dynamic contents)
<html>
<body>
Hello World!
<br>
Current time is <%= new java.util.Date() %>
</body>
</html>

8
Output

9
JSP vs. Servlet

10
JSP Benefits over Servlet (for
View generation)
● Easier to author web pages (compared to
Servlets)
● Content and display logic are separated
● Web application development is simplified
with JSP, JavaBeans and tags (JSTL and
custom tags)
● Software reuse is possible through the use
of components (JavaBeans and tags)

11
JSP is “Servlet”
● JSP pages get translated into servlets
– Tomcat translates greeting.jsp into greeting$jsp.java
● Scriptlet (Java code) within JSP page ends up
being inserted into jspService() method of resulting
servlet
● Implicit objects for servlet are also available to JSP
page designers, JavaBeans developers, custom
tag designers

12
Should I Use Servlet or JSP?
● In practice, servlet and JSP are used together
– Via MVC (Model, View, Controller) architecture
– Servlet plays the role of the Controller
– JSP plays the role of the View

13
Servlet/JSP vs. Web Frameworks

● Limitations of vanilla Servlet/JSP


– Vanilla Servlets/JSP are considered too low-level for
building real-life production-quality Web applications
– Vanilla Servlets/JSP do not provide common features
needed for building web applications such as Dispatch
framework, Data binding, validation, layout,
internationalization, etc
● So it is highly likely you will use popular MVC-
based Web application frameworks, which
provide extra features over vanilla Servlet/JSP
– SpringMVC, Wicket, Tapestry, Struts, etc
14
JSP in Big Picture of
Java EE

15
JSP & Servlet as Web Components

16
JSP Architecture

17
Web Application Designs

18
JSP Architecture

19
Life cycle of a JSP page

20
How Does JSP Work?
User Request

Server

File JSP
Changed
?
Create Source

Compile

Execute Servlet
21
JSP Lifecycle Methods during
Execution Phase

22
Steps for building
JSP-based Web
application

23
Web Application Development
and Deployment Steps
1.Write the Web component code (Servlet and
JSP)
2.Create any static resources (for example, images
or CSS files)
3.Create deployment descriptor (web.xml)
4.Build the Web application (*.war file or
deployment-ready directory)
5.Install or deploy the web application into a Web
container
● Clients (Browsers) are now ready to access them via
URL
24
Resources

1. Java Servlet Technology


https://www.oracle.com/java/technologies/j
ava-servlet-tec.html

2. Java Server Pages (JSP) White Paper


https://www.oracle.com/java/technologies/j
avaserver-white-paper.html

3. Servlet & JSP Best Practices


https://www.oracle.com/technical-
resources/articles/javase/servlets-jsp.html

4. JPassion Servlet & JSP Programming


https://www.jpassion.com/java-web-
programming-basics-servlet/jsp/java-web-
programming-basics-servlet-jsp-with-
passion

You might also like