Title: An introduction to Servlet and JSP
1An introduction to Servlet and JSP
- Alessandro Marchetto
- Fondazione Bruno Kessler-IRST,
- Centro per la Ricerca Scientifica e Tecnologica
2Link
- Page of the Web Applications section in the LSA
2007 course http//sra.itc.it/people/marchetto/co
urses/trento/lsa/07/ - It is linked (also) by the main page of the
course http//sra.itc.it/people/ceccato/courses/ls
a/
3Outline
- Just a quick introduction
- After this lecture you will be able to read and
write simple servlets/JSP.
- Web sites and Web applications.
- Java Servlet
- Servlet engine
- How to write a servlet
- How to Process a request (Form data)
- Servlet session tracking
- JavaServer Pages
- Model-View-Controller architecture
4Web sites
- The Web server distributes pages of formatted
information to clients that request it. - HTML Pages are transmitted using the http
protocol - The browser renders (static) HTML pages.
- HTML pages are stored in a file system
(database) contained on the web server.
5HTML and DOM
- The HTML Document Object Model (HTML DOM) defines
a standard way for accessing and manipulating
HTML documents. - The DOM presents an HTML document as a
tree-structure (a node tree), with elements,
attributes, and text.
lthtmlgt ltheadgt lttitlegtMy titlelt/titlegt lt/headgt ltbo
dygt lth1gtMy headerlt/h\gt lta hrefgtMy
linklt/agt lt/bodygt lt/htmlgt
its DOM
http//www.w3.org/TR/html401/
http//www.w3.org/TR/DOM-Level-2-HTML/html.html
6Dynamic Web sites
- In some cases the content of a page (HTML) is not
necessarily stored inside a file. - The content can be assembled at run-time
according to user inputs and informations stored
in a database. It can come from the output of a
program (server script). - Servlets and JavaServer Pages are the Java
technologys answer to dynamic Web sites. They
are programs that run on a Web server and build
Web pages.
Web Server
Script/program
DB
http request
http response
Client
7Outline
- Just a quick introduction
- After this lecture you will be able to read and
write simple servlets/JSP.
- Web sites and Web applications
- Java Servlet
- Servlet engine
- How to write a servlet
- How to Process a request (i.e., Form data)
- Servlet session tracking
- JavaServer Pages
- Model-View-Controller architecture
8Servlet Engine
- A servlet engine (or servlet container) provides
the run-time environment in which a servlet is
executed. - The servlet engine manages the life-cycle of
servlets (i.e., from their creation to their
destruction). - The servlet engine loads, executes and destroyes
servlets - Apache Tomcat is a servlet container
http//tomcat.apache.org
Relationships between Web server, Servlet engine
and Servlets.
9The Life-Cycle of a Servlet
- Servlet are Java classes. To execute them it is
necessary compiling them in bytecode. - The servlet engine perform the following tasks
- it loads the servlet when it is requested (only
the first time). - it calls the init() method of the servlet.
- it handles the requests calling the service()
method of the servlet. - at the end, it calls the destroy() method.
10How to write a Java servlet
HttpServlet implements the Servlet interface
- All servlets implement the Servlet interface or
extend a class the implements it. - We will use HttpServlet and these methods
- doGet
- doPost
- init
- destroy
- getServletInfo
- To write a servlet some of these methods must be
overridden .....
11Generic Template (1)
- The generic template to write Servlet
import java.io. import javax.servlet. import
javax.servlet.http. public class
ServletTemplate extends HttpServlet public
void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
// Use request to read incoming HTML form data
(e.g. submitted data) // Use response to
specify the HTTP response status (e.g., content
type) PrintWriter out
response.getWriter() // Use out to send
content to browser
12Generic Template (2)
- All your servlets must extend HTTPServlet.
- HTTPServlet represents the base class for
creating Servlets within the Servlet API. - The Full Servlet API is available at
- http//java.sun.com/javaee/5/docs/api/
- Once you have extended HTTPServlet, you must
override one or both - doGet() to capture HTTP Get Requests
- doPost() to capture HTTP Post Requests
13Generic Template (3)
- The doGet() and doPost() methods each take two
parameters - HTTPServletRequest encapsulates all information
regarding the browser request. - Form data, client host name, HTTP request
headers. - HTTPServletResponse encapsulates all
information regarding the servlet response. - HTTP Return status, outgoing cookies, HTML
response. - If you want the same servlet to handle both GET
and POST, you can have doGet call doPost or vice
versa.
14Generic Template (4)
- The HTTPResponse object has a getWriter() method.
- This method returns a java.io.PrintWriter object
for writing data out to the Web Browser. - PrintWriter out response.getWriter()
15Helloworld
- First example of servlet
- We override doGet()
- The execution of it produces a HTML response
import java.io. import javax.servlet. import
javax.servlet.http. public class
HelloClientServlet extends HttpServlet
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
response.setContentType(text/html)
PrintWriter out response.getWriter()
out.println(ltHTMLgtltHEADgtltTITLEgtHello
Client!lt/TITLEgt
lt/HEADgtltBODYgtHello Client!lt/BODYgtlt/HTMLgt)
out.close()
16How to compile and execute a Servlet? How to use
Eclipse to done this task? ... Helloworld demo
...
17Context
ServletContext
- The Context can be used to store global
information shared among the servlets of a given
application. - The Context is initialized when the Servlet
container starts and destroyed when it shuts
down. For this reason, it is suited for keeping
the long lived information - It is implemented with javax.servlet.ServletConte
xt - The methods
- -getServletContext() obtain the context
- -getAttribute(String key) get an attribute from
the context - -setAttribute(String key, Object value) set an
attribute
1
1
Common Data
Servlets
18Forms and Servlets (1)
- How to exchange data between client and server?
ltform methodGET/POST actionThreeParamsgt
First Par ltinput typetext nameparam1 /gt
Second Par ltinput typetext nameparam2 /gt
Third Par ltinput typetext nameparam3 /gt
ltinput typesubmit valueSubmit /gt lt/formgt
GET In a URL the part after the question mark
(?) is known as form data, and is a way to send
data from a Web page to a server-side program
http//host/ThreeParams POST a data packege is
created and attached to the HTTP requests sent to
the server
? param1 hallparam2 gatesparam3 mcnealy
19Forms and Servlets (2)
20Forms and Servlets (3)
import java.io. import javax.servlet. import
javax.servlet.http. import java.util. 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 "Reading Three Request Parameters"
out.println( ServletUtilities.headWithTitle(title
) "ltBODYgt\n" "ltH1
ALIGNCENTERgt" title
"lt/H1gt\n" "ltULgt\n" "
ltLIgtparam1 "
request.getParameter("param1") "\n"
" ltLIgtparam2 "
request.getParameter("param2") "\n"
" ltLIgtparam3 "
request.getParameter("param3") "\n"
"lt/ULgt\n" "lt/BODYgtlt/HTMLgt")
21Forms and Servlets (4)
22HTTP - Stateless protocol (1)
- The Web server cant remember previous
transactions since HTTP is a stateless
protocol. - E.g., a shopping cart
- it contains all items that have been selected
from an online store's catalog by a customer - the customer can check the content of the cart at
any time during the session - thus, the server must be able to maintain the
cart of the user across several Web page requests.
23- How to maintain the state
HTTP - Stateless protocol (2)
- There are four ways to maintain the state
- Cookies
- javax.servlet.http.Cookie(String nome, String
val) - methods setName(String cookieName),
setValue(String cookieValue), etc. - Hidden fields in forms
- ltinput typehidden valueltvaloregt /gt
- URL rewriting
- e.g., http//host/serveltPages/ShowSessionjsessi
onidE4D371A0710 - String encodeURL(String url) of the class
HttpServletResponse - where url is the original lURL and the output
is the rewritten one - Servlets (HttpSession API)
24Saving the state in general
First request
The Server marks the client with an unique ID and
creates a memory partition that will contain the
data (state)
xyz5
Every subsequent connection must send the ID. In
this way the server recognize/identify the client
25Using the HTTPSession API
Servlet Sessions (1)
Looking up the HttpSession object associated with
the current request.
- This is done by calling the getSession method of
HttpServletRequest - HttpSession session request.getSession(true)
- The browser requests a servlet
- If is this the first request then a new session
object is created. Otherwise the session object
connected with the client is recovered. - When the object session is recovered it is
possible to store/read information on it.
26Servlet Sessions (2)
Looking up information associated with a session
- HttpSession objects live on the server. These
session objects have a builtin data structure
that let you store any number of keys and
associated values (objects). - The method getAttribute("key") is used to look up
a previously stored value. The return value is
null if there is no such attribute.
getAttribute
Key Value
Key Value
Session
Web pages
27Servlet Sessions (3)
Assuming ShoppingCart is some class you have
defined yourself that stores information on
items being purchased
HttpSession session request.getSession(true) Sh
oppingCart previousItems
(ShoppingCart)session.getAttribute("previousItems"
) if (previousItems null)
previousItems new ShoppingCart(...)
String itemID request.getParameter("itemID")
previousItems.addEntry(Catalog.getEntry(itemID))
session.setAttribute("previousItems",
previousItems)
28Outline
- Just a quick introduction
- After this lecture you will be able to read and
write simple servlets/JSP.
- Web sites and Web applications
- Java Servlet
- Servlet engine
- How to write a servlet
- How to Process a request (Form data)
- Servlet session tracking
- JavaServer Pages
- Model-View-Controller architecture
29JavaServer Pages (JSP)
- JavaServer Pages (JSP) lets you separate the
dynamic part of your pages from the static HTML. - You simply write the regular HTML in the normal
manner. - You then enclose the Java code for the dynamic
parts in special tags, most of which start with
lt and end with gt.
30JSP are Servlets
- We write a JSP page
- Then the JSP is automatically converted into
servlet (by the servlet container)
- You normally give your file a .jsp extension, and
typically install it in any place you could place
a normal Web page. - Although what you write often looks more like a
regular HTML file than a servlet the JSP page
just gets converted to a normal servlet. - This is normally done the first time the page is
requested.
31JSP structure
- The dynamic code of a given JSP can be composed
of the following - structures
- expressions,
- scriplets,
- declarations,
- directives,
- predefined variables,
- actions
- ....
32JSP Expressions
- A JSP expression is used to insert Java values
directly into the output. It has the following
form - lt Java Expression gt
- The Java expression is evaluated, converted to a
string, and inserted in the page. This evaluation
is performed at run-time (when the page is
requested), and thus has full access to
information about the request. - For example, the following shows the date/time
that the page was requested - Current time lt new java.util.Date() gt
33A small example
... lthtmlgt ltheadgt lttitlegtSimple JSP
Pagelt/titlegt lt/headgt ltbodygt ltpgtThis JSP
page contains some HTML code .... lth1gtand
a small piece of dynamic code lt new
java.util.Date() gt lt/pgt lt/bodygt lt/htmlgt
34package org.apache.jsp import javax.servlet. im
port javax.servlet.http. import
javax.servlet.jsp. import org.apache.jasper.runt
ime. public class facile_Jsp extends
HttpJspBase public void _jspService(HttpServl
etRequest request,
HttpServletResponse response) throws
java.io.IOException, ServletException
JspWriter out pageContext.getOut()
out.println(lthtmlgt)
out.println(ltheadgt) out.println(lttitlegtSer
vlet Semplicelt/titlegt) out.println(lt/headgt
) out.println(ltbodygt)
out.println(ltpgtQuesta servlet contiene tanto
codice HTML) out.println(....)
out.println(e un piccolo elemento dinamico )
out.println(new java.util.Date() )
out.println(lt/pgtlt/bodygt)
out.println(lt/htmlgt) public void
service(HttpServletRequest request,
HttpServletResponse response)
_jspService(request, response)
- simple.jsp converted into a servlet
35JSP Scriplets
- If you want to do something more complex than
insert a simple expression, JSP scriptlets let
you insert arbitrary code into the servlet method
that will be built to generate the page.
Scriptlets have the following form - lt Java Code gt
- Scriplets can contain not-complete Java
statements, and blocks left open can affect the
static HTML outside of the scriptlets. - lt if (Math.random() lt 0.5) gt
- Have a ltBgtnicelt/Bgt day!
- lt else gt
- Have a ltBgtlousylt/Bgt day!
- lt gt
36A small example
lthtmlgt ltbodygt lt String name(String)request.
getParameter(param1)gt ltpgtWelcome, lt
out.print(name)gt Today is lt Date d new
java.util.Date() out.print(d) gt lt/pgt
lt/bodygt lt/htmlgt
37JSP Declarations
- A JSP declaration lets you define methods or
fields that get inserted into the main body of
the servlet class - lt! Java Code gt
- Since declarations do not generate any output,
they are normally used in conjunction with JSP
expressions or scriptlets. - lt! private int accessCount 0 gt
- Accesses to page since server reboot
- lt accessCount gt
38A small example
lt! private int number 0 private int
randomNamber() return Math.abs(new
Random().nextInt() 100) 1 gt lthtmlgt ltheadgt
lt/headgt ltbodygt lth1gtExample of JSP
declarationslt/h1gt lth2gtVariable values
ltttgtnumberlt/ttgt lt number gt
lt/h2gt lth2gtrandom number lt randomNamber()
gt lt/bodygt lt/htmlgt
39JSP Directives
- A JSP directive affects the overall structure of
the servlet class. It usually has the following
form - lt_at_ directive attribute"value"
attributeN"valueN gt - Examples
- lt_at_ page import"java.util." gt
- lt_at_ include file"navbar.html" gt
- There are three main directive
- page
- include
- taglib
40JSP Directive Page
- lt_at_ page attribute1value1, attribute2value2,
gt - Attributes
- Import define the package to be imported
- lt_at_ page import"java.util." gt
- content-type define the response content-type
(default is text/html) - Session verify if the page is tied to a session
- lt_at_ page session"true" gt
- errorPage redirect to the error page in case of
error - lt_at_ page errorPage"error.jsp" gt
- isErrorPage define a page that can be used as an
error page - lt_at_ page isErrorPage"true" gt
41JSP Directive Include
- This directive lets you include files at the time
the JSP page is translated into a servlet. - lt_at_ include filenome-file gt
- It has a unique attribute file.
- The value of this attribute can be an URL
(related to a JSP or - a HTML page)
- e.g., lt_at_ include file"/navbar.html" gt
-
42JSP Directive Taglib
It allows the JSP page to use custom tag (i.e.,
custom tag extensions) Custom tags are special
types of tags tied to Java code that are usable
in JSP pages E.g.,
lt_at_ taglib uritagLibraryURI prefixtagPrefix
gt
Prefix to be used into the JSP page to identify
the tags of the libray lttagPrefixtagname /gt
URI related to the tag library to be used
43A small example
- JSP without and with taglib
lt_at_ taglib urihttp//java.sun.com/jsp/jstl/c
ore prefixc gt lthtmlgt ltheadgt
lttitlegtCount with JSTLlt/titlegt lt/headgt
ltbodygt ltcforEach vara begin1
end10 step1gt ltcout valuea
/gt ltbr /gt lt/cforEachgt lt/bodygt lt/htmlgt
lthtmlgt ltheadgt lttitlegtCount without JSTL
lt/titlegt lt/headgt ltbodygt lt for(int
a1alt10a) gt ltagtltbr/gt lt gt
lt/bodygt lt/htmlgt
see http//java.sun.com/products/jsp/jstl/ (and
click on theAPI Specification link)
44Predefined Variables
- To simplify code in JSP expressions and
scriptlets, you are supplied with eight
automatically defined variables. - Request. HttpServletRequest associated with the
request - Response. HttpServletResponse associated with the
response to the client. - Out. PrintWriter used to send output to the
client. - Session. HttpSession object associated with the
request. - Application. ServletContext as obtained via
getServletConfig().getContext().
45Actions
JavaBeans are software components
- JSP actions use constructs in XML syntax to
control the behavior of the servlet engine. - jspinclude - Include a file at the time the page
is requested. - jspuseBean - Find or instantiate a JavaBean.
- jspsetProperty - Set the property of a JavaBean.
- jspgetProperty - Insert the property of a
JavaBean into the output. - jspforward - Forward the requester to a new
page..
46Using JavaBean (1)
SimpleBean.java package hall public class
SimpleBean private String message "No
message" public String getMessage()
return(message) public void
setMessage(String message) this.message
message
47Using JavaBeans (2)
BeanTest.jsp ltHTMLgt ltHEADgt lt/HEADgt ltBODYgt ltCENT
ERgt ltTABLE BORDER5gt ltTRgtltTH CLASS"TITLE"gt
Reusing JavaBeans in JSPlt/TABLEgt lt/CENTERgt ltPgt lt
jspuseBean id"test" class"hall.SimpleBean"
/gt ltjspsetProperty name"test"
property"message" value"Hello
WWW" /gt ltH1gtMessage
ltIgt ltjspgetProperty name"test"
property"message" /gt lt/Igtlt/H1gt
lt/BODYgt lt/HTMLgt
instantiate the JavaBean SimpleBean testnew
SimpleBean()
Set the property (message) messageHello WWW
Get the value of message Hello WWW
48Bean Test result
49Outline
- Just a quick introduction
- After this lecture you will be able to read and
write simple servlets/JSP.
- Web sites and Web applications
- Java Servlet
- Servlet engine
- How to write a servlet
- How to Process a request (Form data)
- Servlet session tracking
- JavaServer Pages
- Model-View-Controller architecture
50Model-View-Controller
Ideally a Web application can be divided into
three logic components
- Model implements the processing/business logic
(i.e. the application functionalities) and
maintains the state of the application. - View assembles the actual interface
representation for the client on the network (it
produces the responses). - Controller receives and handles client requests.
51Architecture 1
- There are two philosophical approaches for
building applications using JSP. - In the Model 1 the JSP page is responsible for
processing the incoming request and replying back
to the client. - There is still separation of presentation from
content, because all data access is performed
using beans.
- Controller and View are glued together
- Model is implemented using beans
- It is better to separate the controller from
- the view
52Architecture 2
- This approach combines the use of both servlets
and JSP, using JSP to generate the presentation
layer and servlets to perform process-intensive
tasks. - The servlet acts as the controller and is in
charge of the request processing and the creation
of any beans or objects used by the JSP, as well
as deciding, depending on the user's actions,
which JSP page to forward the request to. - There is no processing/business logic within the
JSP page itself .
53References
- Tutorial about Servlets and JSP
www.apl.jhu/7Ehall/java/Servlet-Tutorial - Understanding Architecture 2 www.javaworld.com/j
avaworld/jw-12-1999/jw-12-ssj-jspmvc.html - Sun http//java.sun.com/products/servlet/
- Sun (Servlet and JSP) API http//java.sun.com/java
ee/5/docs/api/ - Sun (Servlet) Documentation http//java.sun.com/pr
oducts/servlet/docs.html - Sun J2EE Tutorial http//java.sun.com/javaee/5/doc
s/tutorial/doc/ - Apache Tomcat http//tomcat.apache.org/
- Tomcat (servlet) API http//tomcat.apache.org/tomc
at-5.0-doc/servletapi/index.html - Tomcat (jsp) API http//tomcat.apache.org/tomcat-5
.0-doc/jspapi/index.html - Tomcat in Eclipse http//www.sysdeo.com/eclipse/to
mcatplugin (a Tomcat installation is required) - Tutorial about how to intregrate Tomcat in
Eclipse http//plato.acadiau.ca/courses/comp/dsilv
er/2513/EclipseAndTomcatTutorial/
54Tomcat configuration (1)
Tomcat directory organization TOMCAT_HOME/weba
pps TOMCAT_HOME/webapps/myApplication TOMCAT_H
OME/webapps/myApplication/.html
TOMCAT_HOME/webapps/myApplication/.jsp TOMCAT
_HOME/webapps/myApplication/WEB-INF/ TOMCAT_HOME
/webapps/myApplication/WEB-INF/web.xml TOMCAT_HO
ME/webapps/myApplication/WEB-INF/classes/.class
TOMCAT_HOME/webapps/myApplication/WEB-INF/lib/.
jar TOMCAT_HOMEwebapps/myApplication/WEB-INF/s
rc/.java
55Tomcat configuration (2)
- web.xml
- XML file used by Tomcat
- it is a deployment descriptor
- used to set specific parameters for the current
application, such as - name of the servlet (that can be reached though
HTTP) - URL corresponding to servlet files (e.g., into
/WEB-INF/classes/) - sessions timeout
- etc.
- it is loaded during the application installation
- It is composed of the tags
- servlet set alias and parameters to initialize
a given servlet - servlet-mapping set URL(s) to a given servlet
56Sample of web.xml
lt?xml version"1.0" encoding"ISO-8859-1"?gt ltweb-a
pp xmlns"http//java.sun.com/xml/ns/j2ee"
xmlnsxsi"http//www.w3.org/2001/XMLSchema-instan
ce" xsischemaLocation"http//java.sun.com/xm
l/ns/j2ee http//java.sun.com/xml/ns/j2ee/web-
app_2_5.xsd" version"2.5"gt ltservletgt
ltservlet-namegtHelloServletlt/servlet-namegt
ltservlet-classgtHelloClientServletlt/servlet-classgt
lt/servletgt ltservlet-mappinggt
ltservlet-namegtHelloServletlt/servlet-namegt
lturl-patterngt/HelloClientServletlt/url-patterngt
lt/servlet-mappinggt lt/web-appgt
Name of the class
Alias to use in HTTP request