Title: CISH6960: Developing Enterprise Applications
1CISH-6960 Developing Enterprise Applications
2Architectures
- Extensible designs for web applications
3Architectures
- Developing web pages is easy
- Designing flexible and extensible web
applications that combine HTML, JSP, JavaBeans,
databases, etc., is not - We discuss two common approaches for building
such structures - Both use the Model-View-Controller design pattern
- Model 1 involves JSPs and JavaBeans
- Model 2 adds Servlets to act as a controller
4Approaches
- The default approach is to mix Java code inside
HTML, using scriptlets and the other built-in
tags - Difficult to maintain and extend
- Annoys the web content designers
- Another approach is to use JavaBeans to remove
the code from the web page - This is the so-called Model 1 architecture
- Recommended in the original JSP specification
5Model 1 Architecture
Browser
JavaBean
request
response
Business Objects
JSP Pages
JavaBean
JavaBean
access and modify
accesses
6Model 1 Architecture
- Browser submits requests to JSP pages
- JSPs access business objects indirectly, through
JavaBeans - Insulates the JSPs from changes in the business
objects - As long as bean interfaces remain constant, the
JSPs are independent of the business object
implementations
7Model 1 Architecture
- Software developers implement the business
objects and beans - Web content designers implement the JSP pages
- Oftentimes, however, the JSP pages decisions to
be made regarding destinations - Winds up incorporating Java into the page
8Model 2 Architecture
- The Model 2 architecture also separates content
generation from content presentation - Browser requests are submitted to a servlet
- Servlet accesses business objects to create
content - Most Java code goes here
- Content is stored in a JavaBean
- JSP pages access the beans for presentation
9Model 2 Architecture
JSP Pages (presents content)
Browser
response
request
accesses
create and modify
JavaBean
JavaBean
Servlet (generates content)
JavaBean
Business Objects
access and modify
10Model 2 Architecture
- Model 2 is a modified Model-View-Controller
architecture - The business objects and beans are the model
- The JSPs are the view
- The servlets are the controllers
11Servlets
- Extending web server capabilities with Java
classes
12Dynamic Web Sites
- Most web sites are static
- Browser requests page, server returns it
- HTTP request Hypertext Transfer Protocol
- Pages written in HTML
- Hypertext Markup Language
- Current version is 4.0
- XHTML reformulates HTML as XML
- Should eventually take over
- HTML is static wrap text in tags containing
both presentation and meaning information
13HTML
Web Server
HTTP request
Browser
HTML web page
lthtmlgt ltheadgt lttitlegtlt/titlegt lt/headgt
ltbodygt lots of content lt/bodygtlt/htmlgt
14Dynamic Web Sites
- How to make web sites dynamic?
- Client-side solutions
- Use clients CPU
- Decreases server load
- Server-side solutions
- Provide secure access to private resources
- Databases
- Enterprise JavaBeans
- Source not visible to client
15Client-Side Technologies
- Java applets
- JRE bundled in earliest version of Netscape
- Browser wars and Sun/Microsoft lawsuits hindered
versioning and compatibility - Sun has plug-in, but other technologies now
predominate - JavaScript
- Originally called LiveScript by Netscape
- Client-side scripting language
- Nothing to do with Java
- Standardized as ECMAScript, but not implemented
the same way, to the same extent, in both major
browsers
16Server-Side Technologies
- CGI
- Common Gateway Interface
- Web servers spawns requests to external programs
- Can be written in any language, but Perl is
currently most popular - Program generates output and returns it to web
server - New process for every request
- Does not scale well at all
17CGI Web Servers
Request for CGI 1
CGI 1 starts and ends
Web Server
CGI 2 starts and ends
Request for CGI 2
Request for CGI 1
CGI 1 starts and ends
Each CGI request (even ones for the same
process) results in a new process on the server
18Server-Side Technologies
- Java Servlets
- Java class loaded by server
- Extends server functionality
- Runs inside a JVM on the server
- Handled using multiple threads
- Efficient
- Scalable
- Portable across operating systems
- Portable across web servers
- Frequently act as the Controller in the MVC model
19Servlets
Request for Servlet 1
Web Server
Servlet Container
Servlet 1
Request for Servlet 2
Servlet 2
Request for Servlet 1
Requests handled by multiple threads inside the
servlet container
20Servlets
- Four packages
- Used for servlets
- javax.servlet
- javax.servlet.http
- Used for creating JSP custom tags
- javax.servlet.jsp
- javax.servlet.jsp.tagext
21Servlets
- Servlets created by inheritance
- Extend either
- GenericServlet
- HttpServlet
- Much more common, gives access to the so-called
CGI variables (request and response)
22GenericServlet
- Abstract class
- Contains abstract service method
- abstract void service(ServletRequest req,
ServletResponse res) - If you extend GenericServlet, override this method
23Extending GenericServlet
- The web server calls the service() method
import java.io.import javax.servlet. public
class MyGenericServlet extends GenericServlet p
ublic void service(ServletRequest
req, ServletResponse res) throws
IOException, ServletException res.setContentT
ype(text/plain) PrintWriter out
res.getWriter() out.println(Hello,
World!)
24Explanations
- The service method has two arguments
- ServletRequest req
- Contains information about the incoming HTTP
request - ServletResponse res
- Handle to assemble the output response
- Has setContentType(String type) method
- Acceptable types are text/plain, text/html,
text/xml, among others - Can include a character encoding as well
25Explanations
- The response also has methods for getting the
output stream - res.getWriter() returns a PrintWriter that can
return character data to the client - res.getOutputStream() returns a
ServletOutputStream for returning binary data to
the client - Use one or the other, after setting the content
type - Either method can throw an IOException
- Result has a println() method
26Servlet Location
- Now the hard part Where do you put the
servlets? - This used to be container dependent
- Since Servlet 2.2 specification, this has become
standardized - Now we build a web application, using an XML
configuration file called web.xml
27Web Application Structure
Name of war file is myapp.war
web.xml
Servlets not in packages
Servlets in packages
jar files
28Web Application Structure
- A web archive (war file) is created using Javas
jar command - myapp.war contains
- Files and directories accessible from outside
- HTML files
- Images
- Text, etc.
- WEB-INF directory
- Invisible to outside
- web.xml deployment descriptor
- classes subdirectory for servlets
- lib subdirectory for jar files
29Web Application Structure
- Servlets not in packages live in the
myapp/WEB-INF/classes directory - Accessed by http//localhost8080/myapp/servlet/My
Servlet - Servlets in packages live in the same directory,
in package structure - Servlet Hello in package com.mycompany lives in
directorymyapp/WEB-INF/classes/com/mycompany/ - Accessed by http//localhost8080/myapp/servlet/co
m.mycompany.MyServlet
30MyGenericServlet Result
31HttpServlet
- The only subclass of GenericServlet in the
standard library is HttpServlet - Also an abstract class
- Extended to create servlets suitable for a web
site - Several methods
- doGet, for HTTP GET requests
- doPost, for HTTP POST requests
- doPut, for PUT
- doDelete, for DELETE
- init and destroy
- getServletInfo
32Creating Servlets
- Most servlets extend HttpServlet
33HttpServlet
- Most applications will override doGet or doPost,
or both - The default service method dispatches the request
to the proper method, based on its HTTP type - Occasionally overridden, but not usually a good
idea - public void doGet(HttpServletRequest req,
HttpServletResponse res) - public void doPost(HttpServletRequest req,
HttpServletResponse res)
34doGet and doPost
- Originally, GET requests were designed merely to
request information - Append parameters to the URL
- Called URL rewriting
- http///HiThere?nameFred
- Result can be bookmarked
- POST requests were designed to add information to
a site - URL is left alone
35doGet and doPost
- When a servlet URL is put into a browser, its
doGet method is invoked - Therefore, one simple application is
- Create a form using doGet
- Make the form use a POST method
- Respond to the form using doPost
36HiThere Servlet
import java.io.import javax.servlet.import
javax.servlet.http. public class HiThere
extends HttpServlet public void
doGet(HttpServletRequest req, HttpServletRespon
se res) throws IOException, ServletException
res.setContentType(text/plain) PrintWriter
out res.getWriter() out.println("lthtmlgt")
out.println(" ltheadgtlttitlegtHi Therelt/titlegtlt/head
gt") out.println(" ltbodygt") out.println("
ltform action'/myapp/servlet/HiThere
method'POST'gt") out.println(" What is
your name? " "ltinput type'text'
name'myname'/gtltbrgt") out.println("
ltinput type'submit'gt") out.println("
lt/formgt") out.println(" lt/bodygt") out.print
ln("lt/htmlgt") continued on next
page
37HiThere Servlet
continued from previous page public void
doPost(HttpServletRequest req, HttpServletRespo
nse res) throws IOException, ServletException
res.setContentType(text/plain) PrintWriter
out res.getWriter() String name
req.getParameter("myname") out.println("lthtmlgt"
) out.println(" ltheadgtlttitlegtHi
Therelt/titlegtlt/headgt") out.println("
ltbodygt") out.println(" lth1gtHi there, "
name "!lt/h1gt") out.println("
lt/bodygt") out.println("lt/htmlgt")
38HiThere Servlet
- Both doGet and doPost generate HTML pages
- This can get tiresome and difficult to maintain
- Well discuss alternatives below
- doGet creates an HTML form
- The forms action attribute points back to the
servlet - The forms method attribute is POST, so doPost is
invoked - Form has an input field with name attribute
myname - doPost responds to the request
- The form variable myname is stored in the request
object automatically - HttpServletRequest class has a getParameter(String
) method for returning form parameters
39Configuration Parameters
- Using /servlet/ is awkward and misleading
- There is no servlet directory
- Set the URL pattern in the web.xml file
- XML files contain tags satisfying certain
conditions for well-formedness - Tags must be properly nested
- Every start tag must have an end tag
- Tags are case-sensitive
40Configuration Parameters
- Valid XML files adhere to rules
- Specified in either a Document Type Definition
(DTD) or XML Schema - Rules list
- Which tags are available
- Which tags are mandatory and which optional
- In what order they may be used
- How they may be nested
- What attributes they may have
- How many of each may occur
- etc.
41Configuration Parameters
- Servlet 2.2 specification defines a DTD for a
configuration file called web.xml - DTD is available at Suns web site
- Published in most servlet books
- Defines the ltweb-appgt tag, the ltservletgt tags,
and others associated with it - Allows URLs to be specified, initialization
parameters, security permissions, etc. - Called a deployment descriptor
42Simple web.xml File
lt?xml version1.0 ?gt lt!DOCTYPE web-app PUBLIC
-//Sun Microsystems, Inc.//DTD Web Application
2.2//EN http//java.sun.com/j2ee/dtds/web-app_2
_2.dtdgt ltweb-appgt ltservletgt ltservlet-namegthilt/
servlet-namegt ltservlet-classgtHiTherelt/servlet-cl
assgt lt/servletgt ltservlet-mappinggt ltservlet-nam
egthilt/servlet-namegt lturl-patterngt/yo.htmllt/url-p
atterngt lt/servlet-mappinggtlt/web-appgt
43Simple web.xml File
- First line is required for XML files
- DOCTYPE definition defines that the root tag is
web-app - Must be first in the file
- Only one allowed
- Other tags must be nested inside it
- Rules for file are public, owned by Sun
Microsystems, in English, at the listed URL
44Simple web.xml File
- ltservletgt tag defines characteristics of the
servlet - ltservlet-namegt gives the servlet a name,
associated with ltservlet-classgt - ltservlet-mappinggt connects a servlet to the URL
defined in lturl-patterngt - Pattern may be explicit, as here
- Can have wildcards
- .hi
45Simple web.xml File
- Now the servlet can be accessed via
- http///myapp/yo.html
- http///myapp/servlet/hi
- http///myapp/whassup.hi
- http///myapp/dude/how/are/you.hi
- XML file can be edited without recompiling
anything - For Tomcat, may need to restart the server
- Not necessary for many commercial servers
46The Servlet Lifecycle
- Servlets are used differently than most Java
applications - The web server instantiates a single instance of
each servlet to handle all requests - Efficient, but
- All servlet instance variables are shared across
all requests - To the outside world, instance variables act like
static variables
47Counter
import java.io.import javax.servlet.import
javax.servlet.http. public class Counter
extends HttpServlet private int count public
void doGet(HttpServletRequest req, HttpServletR
esponse res) throws IOException,
ServletException count res.setContentTyp
e(text/plain) PrintWriter out
res.getWriter() out.println(Since loading,
this servlet ) out.println(has been accessed
count times)
48Counter
- Access this servlet
- http///myapp/servlet/Counter
- The count variable every time the servlet is
requested - Hit the reload button and watch the count change
49Setting Initialization Parameters
- Initialization parameters can be specified in the
web.xml file
ltweb-appgt ltservletgt ltservlet-namegthilt/servlet-n
amegt ltservlet-classgtHiTherelt/servlet-classgt lti
nit-paramgt ltparam-namegtstartCountlt/param-namegt
ltparam-valuegt10000lt/param-valuegt lt/init-param
gt lt/servletgt lt/web-appgt
50Modified Counter
public class Counter extends HttpServlet privat
e int count public void init() throws
ServletException String initial
getInitParameter(startCount) try count
Integer.parseInt(initial) catch
(NumberFormatException nfe) count
0 public void doGet(HttpServletRequest
req, HttpServletResponse res) throws
IOException, ServletException as before
51Request and Response
- Http is a stateless protocol
- Each request is considered independent of any
other request - We overcome this using Cookies and the
HttpSession class (discussed below) - Http uses the so-called request/response
paradigm - Each request from the browser has
- A line containing a command
- A set of headers
- An optional request body
- Each response contains
- A line containing a command
- A set of headers
- An optional body
52The Request Object
- The request info is encapsulated in the classes
- javax.servlet.ServletRequest
- javax.servlet.http.HttpServletRequest
53The Request Object
- Some methods in javax.servlet.http.ServletRequest
- public Enumeration getParameterNames()
- Returns the names of all request parameters
- public String getParameter(String name)
- Returns the value of a single parameter
- If there are multiple values, returns the first
one - public String getParameterValues(String name)
- Returns all the values for a single parameter
54The Request Object
- There are methods in HttpServletRequest for
getting header information - String getHeader(String name)
- Enumeration getHeaders()
- etc.
- Other methods frequently used are
- String getMethod()
- Returns GET or POST
- RequestDispatcher getRequestDispatcher(String
path) - This is a very important method well discuss
below - HttpSession getSession()
- Session information well also discuss later
55The Response Object
- The response is encapsulated by
- javax.servlet.ServletResponse
- javax.servlet.http.HttpServletResponse
- Among the methods in these classes are
- PrintWriter getWriter()
- ServletOutputStream getOutputStream()
- void setContentType(String type)
- void sendError(int statusCode)
- void sendRedirect(String location)
56The Response Object
- PrintWriter getWriter()
- Used for character-based data
- ServletOutputStream getOutputStream()
- Used for binary data
- void setContentType(String type)
- Some common types
- text/html
- text/xml
- image/gif, image/jpeg
- application/vnd.ms-excel
57A Simple HTML Form
- Now well examine how servlets handle HTML form
input - The form is shown on the next slide
- A servlet that acts as the form handler is shown
subsequently - Retrieving form parameters is discussed
- Forwarding to other resources is then presented
58A Simple HTML Form
lthtmlgt ltheadgt lttitlegtLog In Formlt/titlegt lt/hea
dgt ltbodygt lth1gtPlease log inlt/h1gt ltform
actionLoginServlet methodGETgt lttablegt
lttrgt lttdgtName lt/tdgt lttdgtltinput
typetext namename /gtlt/tdgt lt/trgt lttrgt
lttdgtPassword lt/tdgt lttdgtltinput
typepassword namepassword
/gtlt/tdgt lt/trgt lt/tablegt ltinput
typesubmit valueLogin /gt lt/formgt lt/bodygt
lt/htmlgt
59A Simple HTML Form
- The HTML page has a form element
- The forms action attribute is set to the form
handler servlet (login) - The form contains two text fields
- Each has a name attribute
- Used as parameters in the request object
- The password field comes up as s
- The form also has a submit button
- When pressed, the values of the text fields are
assigned as parameters to the request
60The Form Handler
public class LoginServlet extends
HttpServlet public void init()
initialize the database public void
doGet(HttpServletRequest req, HttpServletRespon
se res) throws IOException, ServletException
String name (String)req.getParameter(name)
String password (String)req.getParameter(pass
word) validate the input name and password
RequestDispatcher rd req.getRequestDispat
cher(welcome.jsp) rd.forward(req,res)
61The Form Handler
- You can see the beginnings of an overall
architecture starting to form here - The form handler is a servlet
- The servlet
- Initializes a database connection in init()
- Uses getParameter(String) to access the form
parameters from the request object - Validates the user against the info in the
database - Forwards the browser to a new page
62The Form Handler
- The getParameter(String) method
- Is in the javax.servlet.ServletRequest class
- Returns the value of the form element with the
same name as the argument - If there is no form element matching the name,
the method returns null - If there are multiple values under the same name
(as there might be for a series of checkboxes,
for instance), can use - getParameterValues(String) returns String
63RequestDispatcher
- The RequestDispatcher interface is how control is
passed from one servlet to another - Method available
- public RequestDispatcher getRequestDispatcher(Stri
ng path) - In the ServletRequest class
- Accepts relative path names
64RequestDispatcher
- RequestDispatcher has two methods
- forward(ServletRequest req, ServletResponse res)
- include(ServletRequest req, ServletResponse res)
65RequestDispatcher
- rd.forward(req,res)
- Forwards a request from a servlet to another
resource on the server - The client does not know the forward occurred
- Unlike res.sendRedirect(String location)
- Attributes can be added to the request before
forwarding - Can also set headers or status codes, but cant
add output content
66RequestDispatcher
- forward() vs. sendRedirect()
- Biggest difference
- RequestDispatchers dont return to the client
until finished, so no additional network overhead - forward() works best when one component performs
business logic and needs to share the results
with another component - sendRedirect() works best when the client should
actually be sent to another page
67RequestDispatcher
- rd.include()
- Includes the content of a resource into the
current response - Sort of a programmatic server side include
- Calling servlet retains control
- Can add content both before and after the
included content - Well see more of this later when we talk about
server architectures
68Session Tracking
- HTTP is a stateless protocol
- Every request is considered independent of every
other request - Many web applications need to maintain a
conversational state with the client - A shopping cart is a classic example
- There are two primary mechanisms used to track
state - Cookies
- HttpSession objects
69Persistent Cookies
- Cookies were introduced in a very early version
of Netscape Navigator, but have become pervasive - Cookies are small text files (usually lt1Kb in
size) containing name/value pairs - Cookies are added to the response and fetched
from the request
70Persistent Cookies
- Servlet API has a Cookie class
- javax.servlet.http.Cookie
- Constructor takes two Strings
- Cookie cookie new Cookie(ID, 123)
- Cookie is then added to the response
- res.addCookie(cookie)
71Persistent Cookies
- Unfortunately, theres no way to ask for only a
single cookie - Need to fetch them all, and search for the one
you want
Cookie cookies req.getCookies() if
(cookies ! null) for (int j 0 j lt
cookies.length j) String name
cookiesj.getName() String value
cookiesj.getValue()
72Persistent Cookies
- The Cookie class also has a method to say when
the cookie should expire - public void setMaxAge(int expiry)
- Specifies the age in seconds before it expires
- The default is 1, which implies that the cookie
expires when the browser exits
73Cookies
- Most shopping carts dont add all the items to
separate cookies - Would bloat the request horribly
- Instead, they add a session id to a cookie, which
corresponds to a data structure on the server - Since cookies are sent with each request, this
keeps the size of the request down
74The Session Tracking API
- The alternative for servlet developers is the
Session Tracking API - Every user of a site is associated with an
instance of javax.servlet.http.HttpSession
75The Session Tracking API
- Very easy to use
- Get the session object
- req.getSession()
- If a session doesnt exist, this will create one
- req.getSession(boolean create)
- Will disable creation if argument is false
- Set and get attributes in the session
- public void setAttribute(String name, Object
value) - public Object getAttribute(String name)
76The Session Tracking API
- Can also get the names of all the objects bound
to a session - public Enumeration getAttributeNames()
- Can remove an attribute
- public void removeAttribute(String name)
- These are standard in Servlet API 2.2
- Servlet API 2.1 used setValue(), getValue(),
getValueNames(), and removeValue() - These still work, but are deprecated
77The Session Tracking API
- If the browser does not support cookies,
HttpSession will use URL rewriting - If the servlet is returning a URL, or redirecting
the response to another URL, there is a method to
handle this - public String encodeURL(String url)
- Includes the session id if necessary
- public String encodeRedirectURL(String url)
- All calls to sendRedirect() method ought to go
through this first - res.sendRedirect(res.encodeRedirectURL(/servlet/o
ther))
78Set Session Time Out
- Session time out can be set in the web.xml
deployment descriptor
lt?xml version1.0 ?gt lt!DOCTYPE web-app PUBLIC
-//Sun Microsystems, Inc.//DTD Web Application
2.2//EN http//java.sun.com/j2ee/dtds/web-app_2
_2.dtdgt ltweb-appgt lt!-- --gt ltsession-configgt
ltsession-timeoutgt 60 lt/session-timeoutgt lt/s
ession-configgt lt/web-appgt
79Set Session Time Out
- The number in the web.xml file represents minutes
- If 60 minutes pass without any user request, the
server can invalidate the users session and
unbind all its objects - Time out can be configured in a servlet
- public void setMaxInactiveInterval(int secs)
- public int getMaxInactiveInterval()
- Sessions can also be manually invalidated
- public void invalidate()
- Can check whether the session is new
- public boolean isNew()
80Sessions
- JSP Session tracking
- There is an implicit object called session,
which is an instance of the javax.servlet.http.Htt
pSession class - Beans are frequently instantiated and placed in
the session by setting their scope to session
81Servlets Summary
- Java Servlets are Java classes
- Extend either GenericServlet, or, more commonly,
HttpServlet - Override methods
- doGet() for GET requests
- doPost() for POST requests
- init() for initialization parameters
- destroy() for non-memory cleanup
82Servlets Summary
- The request and response objects allow the
servlet to - Access HTTP header information
- Access request parameters
- Set in the URL, or directly from a form
- Set the content type of the response
- Set and get attributes
- Send control to another resource, either by
- response.sendRedirect(), or
- Get access to a RequestDispatcher and call
forward() or include()
83Servlets Summary
- Information can be stored across requests
- Use the Cookie class
- Use the HttpSession class
- Uses cookies if they are available
- Uses URL Rewriting if they are not
84Servlet Summary
- Servlet information is configured using the
structure of a web archive - Specifies where classes and jar files should be
stored - Hides files in the WEB-INF directory from the
client - Contains an XML file called a deployment
descriptor - WEB-INF/web.xml
- Configures many different variables, including
URLs and session timeouts, without requiring any
recompilation of the servlets