Laboratorul 2 - Servlets servlets
Transcript of Laboratorul 2 - Servlets servlets
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 1/66
PART 1Basic Servlet Programming
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 2/66
Objectives
• Explain servlets and the Servlet API• Compare the Servlet API with CGI
• Use the primary classes in servlet programming
• Implement simple servlets
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 3/66
Need for Dynamic Content
•Applets
– Limitation: based entirely on the client’s platform
• CGI scripts
– Based on the server platform to generate dynamiccontent
– Limitations:• Lack of scalability
• Platform dependence
• Java Servlet technology
– a portable way to provide dynamic, user-oriented content.
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 4/66
Development Component: ServletsCLIENT
WEB SERVER
Back End
Application Server
Business Logic
Servlet
Services
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 5/66
What is a Servlet?
• Standard, server-side Java application thatextends the capabilities of a Web Server
– Runs completely on the server
• Nothing is ever downloaded to the browser
– A replacement for CGI scripts
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 6/66
Why use Servlets?
• Servlets have advantages in several areas:– Portability and flexibility
– Security
– Performance
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 7/66
Portability and Flexibility
• A rich set of platform-neutral Java APIs toconnect to most backend assets
• Platform independence through 'write once
run anywhere'
• Reusable objects (JavaBeans)
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 8/66
Security Advantage
• Called within server context– Can restrict servlet access
– Can be part of a Single (global) Sign On
security architecture
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 9/66
Performance Advantage
• Run in the same context as application server • Execute and remain in memory
• Can be preloaded or loaded on demand
• Maintain sessions across HTTP requests
– Reducing activity to backend systems
• Are multithreaded • Scale with multiprocessors and heterogeneous
systems
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 10/66
Generic Servlet Invocation
• Client makes a request of WebServer naming aServlet as part of the URL
• WebServer forwards request to Servlet engine
which locates an instance of a Servlet class• Servlet engine calls Servlet's service method
Browser(Client)
Web Server Application ServerURL
Request
Servlet Instance
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 11/66
Java Servlet API
• The JSDK includes two packageswhich provide interfaces and classesfor writing servlets
– javax.servlet
– javax.servlet.http
• Servlet interface define life-cyclemethods
– GenericServlet class for generic services
– HTTPServlet class for HTTP-specificservices
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 12/66
Servlet
• Represents a service• Usually requested via URL
• Servlets are loaded by an ApplicationServer
– At initialization of Server (if preload)
– At first client request
– Upon servlet reload
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 13/66
Servlet Lifecycle
• The lifecycle of a servlet is controlled by thecontainer in which the servlet has been deployed.
– If an instance of the servlet does not exist, the Web
container a. Loads the servlet class.
b. Creates an instance of the servlet class.
c. Initializes the servlet instance by calling the init method.
– Invokes the service method
– It finalizes (removes) the servlet by calling the
servlet's destroy method.
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 14/66
Servlet Lifecycle(continued)
First request mapped to servlet
init()
service()
destroy()
Request mappedto servlet
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 15/66
HTTP Servlet
•An HTTP specific request handler
• Adds two HTTP specific methods
– doGet()
– doPost()
• Subclasses override these methods and may
override init() and destroy()
• doGet() and doPost() are called by the service
• Additional methods:
– doPut(), doOptions(), doTrace(), doDelete()
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 16/66
Requests and Responses• The service(), doGet() and doPost() methods
each have two parameters:– HttpServletRequest -- provides access to request
data (parameters), HttpSession information, etc.
– HttpServletResponse -- provides services to allowthe servlet to supply a reply to the requesting client
• Most servlet programming amounts to readinga request and writing a response
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 17/66
HTTP Servlet Request
• Represents client's request
• "Getters" for aspects of request, e.g.,
– Request header, content type, length, method...
– Request URL as a String– Servlet "path"
– Client security type
– Access request parameters (by name)
– Scope for data sharing among participant objects in the
request
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 18/66
Request Protocol
• getParameterNames()
– Returns an Enumeration of parameters on the HTML
page
• getParameterValues(String name)– Returns the value of a multi-valued parameter
• getParameter (String name)
– Returns the value of a specific named parameter
• getReader()
– Returns a BufferedReader to view input
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 19/66
Example HTML Form
<P>Please fill out this form with your name. Thanks! </P>
<FORM METHOD="POST"
ACTION="/servlet/NameServlet">
<P>Please enter your name:</P>
<P>First name: <INPUT NAME="first" TYPE="TEXT"
SIZE="12" MAXLENGTH="20"></P>
<P>Surname: <INPUT NAME="surname" TYPE="TEXT"
SIZE="15" MAXLENGTH="25"> </P>
<P>Thank you! </P>
<INPUT TYPE="SUBMIT"> <INPUT TYPE="RESET">
</FORM>
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 20/66
Reading a POSTpublic void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
…
Enumeration enum= req.getParameterNames();
while (enum.hasMoreElements()) {
String name = (String) enum.nextElement();
String value = req.getParameter(name);//… do something with each pair...
}
}
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 21/66
HTTP Servlet Response
• Represents communication channel back toclient
• Allows servlet to return content and/or
errors
• Set content header (type, length, ...)
• Redirect server to return a particular URL
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 22/66
Response Protocol
• getWriter()– Returns a PrintWriter for output
• setContentType(String type)
– Set the content type for this response
– Type is a MIME type
• sendRedirect(String anURL)
– Redirect the browser to a new URL
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 23/66
Simple Servletpublic class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// get stream to output HTML on!
res.setContentType("text/html");
PrintWriter out = res.getWriter();
// send out a simple banner
out.println("<HTML><BODY>");
out.println("<h1>Hello World!</h1>");
out.println("</BODY></HTML>");
}}
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 24/66
Invoking a Servlet
• The most common way to call an HttpServlet is by
classname, e.g.,
– http://www.ibm.com/servlets/com.ibm.a.MyServlet
• Support for this "load/run by classname" is provided by another servlet called "Invoker"
• The "Invoker" servlet attempts to find the servlet's
class on its classpath
• A servlet loaded this way is often considered an
anonymous servlet
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 25/66
Invoking a Servlet (2)
• Alternatively most servlet engines supportregistering servlets by name
– Allows initialization parameters to be supplied
• Parameters customize servlet behavior • One servlet may provide different services (under
different "short names")
• Parameters available in the init() method – Allows servlet to be preloaded
– Permits easy location by RequestDispatcher
– Allows for the servlet to be secured
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 26/66
Summary
• We've seen the advantages Servlets haveover CGI
– Security, Portability, Performance
• We've introduced the basic Servlet classes
and interfaces:
– Servlet, GenericServlet, HttpServlet,– HttpServletRequest, HttpServletResponse
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 27/66
PART 2Cookie API
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 28/66
HTTP Sessions in the ArchitectureCLIENT
WEB SERVER
Back End
Application Server
Business Logic
Servlet Servlet Services
Services
Cookie Data
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 29/66
Cookies
• Cookies are a way to place persistentinformation on the client machine
(accessible from the browser)
– A good way to handle preferences or shortcuts
• Cookies have a name
and a value – Like hash table entries
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 30/66
Cookies: Attributes
• domain
– domain to which the Cookie shall be sent
• maxAge
• name• path
– prefix of all URLs for which this cookie is targeted
• secure• value
• Version
• comment
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 31/66
Cookies: Applications
• By using cookies several problems can besolved:
– Identifying a user during a session
• Example: storing “shopping cart” items during an e-commerce session
– Avoiding username and password
– Customizing a site
– Focusing advertising
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 32/66
Cookies: Security Issues
• Cookies are a good alternative for low-security sites.
• Proper used cookies are not a serious
security threat.– Cookies are never interpreted or executed in any
way, and thus can't be used to insert viruses or
attack your system in any way.– Cannot be used to fill up someone’s disk or launch
other DoS attacks
• Cookies may be a threat to privacy
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 33/66
Proper Cookie Use
• Cookies shouldn't be used for things best kept on
the server, such as:
– Validation information
– Secure information (credit card numbers)• Cookies can be used to give added value to a site,
but the site should not depend on them
– Users can turn off cookies on their computers
• The Session API typically uses the Cookie API
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 34/66
Cookie API
• Creating cookies
– Cookie(String name,String value)
• Saving a cookie
– HttpServletResponse.addCookie(Cookie
aCookie)
• Retrieving cookies – HttpServletRequest.getCookies()
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 35/66
Cookie API
• Getting/setting a cookie’s name – getName/setName
• Getting/setting a cookie’s value – getValue/setValue
• Getting/setting security
– getSecure/setSecure
• Getting/setting a cookie’s version,
comment, path, domain, MaxAge
(continued)
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 36/66
Cookie Examplepublic void doGet(HttpServletRequest req, HttpServletResponse res) {
String userType = "novice";
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (int i=0; i<cookies.length; i++) {
if (cookies[i].getName().equals("userType"))userType = cookies[i].getValue();
}}
if (userType.equals("expert"))
// do expert HTML
else
// do novice HTML
}
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 37/66
Cookie Applicability• Cookies have an "expiration date"
– setMaxAge (int expiryInSeconds)
• Default expiration date is -1
– Means the cookie is not stored persistently
– Lasts only as long as the browser is open
• A MaxAge of 0 is a request sent for the browser to
delete the cookie• Can restrict the applicable URLs to which a
Cookie will be sent
– setPath(String) – setDomain(String)
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 38/66
PART 3HTTPSession: Management of
Application Data
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 39/66
Objectives
• Explain Session Management
• Tie Servlets with Session Management
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 40/66
The Need for Tracking Sessions
• HTTP is a “stateless” protocol
• Typical solutions
– Cookies
• Problem: user can disable cookies – URL rewriting
• Problem: server-side program has a lot of tedious
processing to do – Hidden form fields
• Problem: every page should be dynamically
generated
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 41/66
HTTP Session:Managing Application Data
CLIENT
WEB SERVER
Back End
Application Server
Business Logic
Servlet Session Data
Services
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 42/66
Session Management
• Web Applications must manage state information
– Current customer, shopping cart, ...
– Application will involve several Servlets Servlets
– need to be stateless• The HttpSession interface is the application state
management API
– Represents a client/server connection
– Lifetime spans multiple servlets
– Identified within requests via a Session identifier
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 43/66
HTTP Session
• Ask for a Session from HttpRequest object
– request.getSession(boolean create)
– Returns the current HttpSession
– If create is true AND no current Session exists,a newly created session is returned
• HttpSessions store application-specific
information via a "key" – void setAttribute(String, Object)
– Object getAttribute(String)
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 44/66
Sessions at Runtime: Server
• HttpSessions are
managed by the servlet
engine
• Registered by id • Id must be delivered to
client initially and
presented back toserver on subsequent
“requests”
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 45/66
Sessions at Runtime: Client
• Preferred(default) delivery
vehicle for session id is
“transient cookie”
• Alternative “URLEncoding”supported by
HttpServletResponse
– No automatic support in JSP – Requires Ad hoc support for
client-side script generated
URLs
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 46/66
Sessions at Runtime
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 47/66
Session Invalidation
• Sessions can be invalidated either programmatically or through a timeout
– session.invalidate()
– Removes all values from the session• The Session timeout (inactive interval) can
be set for the application server as a whole
• Also session.setMaxInactiveInterval(int)can provide session specific timeout value
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 48/66
Session Example
• We'll follow a simple e-commerce exampleusing the Session API to run an on-line
bookstore
• We have two Servlets: – BookChoiceServlet
• Allows the user to select choices
• Can browse without purchasing
– CreditInformationServlet
• Takes credit card information
• Confirms and processes the order
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 49/66
Bookstore Domain Classes• Very simple, standard domain objects
– Java Beans (but not required)
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 50/66
Book Choice Servlet• Order is the key
– Get the session
– Create a domain object from thePOSTed data
– Put the new object on the session for later use by other servlets
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 51/66
Book Choice Servlet
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 52/66
Credit Information Servlet
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 53/66
Thread Safety• The HttpSession object is an "infrequently“ shared
resource
– If the Session is volatile (many reads and writes over its
lifetime) -- access should be synchronized
– Do not synchronize indirectly (e.g. synchronizing
various Servlet's doPost() methods)
• Instead, wrap sets of putValue() and getValue() ina synchronized block
synchronized (aSession) {
aSession.setAttribute("aKey", anObject);}
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 54/66
HttpSession Classes
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 55/66
Session Serialization
• Objects stored in a session must be
serializable
– To share between servers in a "clustered server
configuration"
• Make sure objects reachable from the
Session are also Serializable
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 56/66
PART 4Miscellaneous Servlet APIs
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 57/66
Objectives
• Explain the Request Dispatcher Interface
• Explain the Servlet Context API
• Use send/redirect to handle errors
S l t API
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 58/66
Servlet APIs
CLIENT
WEB SERVER
Back End
Application Server
Business Logic
Servlet Servlet Services
Services
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 59/66
Request Dispatcher
• JSDK (Servlet API) 2.1 added a new
interface, javax.servlet.RequestDispatcher
• Used to support both forwarding processing
to and including response from a variety of local Web resources
• A RequestDispatcher is acquired from theServletContext
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 60/66
RequestDispatcher
Sample Use of RequestDispatcher
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 61/66
Sample Use of RequestDispatcher
getServletConfig().getServletContext().
getRequestDispatcher("/WDDisplayOffers").forward(req, res);
getServletConfig().getServletContext().
getRequestDispather("/pages/navigation_bar.html").
include(req, res);
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 62/66
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 63/66
Servlet Context Bindingwas.WebDev.com
/HRApps /WDInternet
/app1 /app2 /WDLogin /WDDisplayOffer
Servletcontextapp1
Servletcontextapp2
Servletcontext
WDInternet
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 64/66
Servlet Context
• Servlet Context Attributes – Allows for simple application scoped data
sharing between servlets
– getAttribute/setAttribute methods
• ServletContext.getResource()
– Allows a servlet to load resources without
assuming a directory structure on the server
(continued)
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 65/66
Handling Servlet Life-Cycle Events• Define listener objects whose methods get invoked when life cycle
events occur
• Life-cycle events
– Web context object
• Initialization/destruction
– javax.servlet.ServletContextListener and ServletContextEvent
• Attribute added, removed, replaced
– javax.servlet.ServletContextAttributeListener and ServletContextAttributeEvent
– Session object
• Creation, invalidation, timeout
– javax.servlet.http.HttpSessionListener and HttpSessionEvent
• Attribute added, removed, replaced
– javax.servlet.http.HttpSessionAttributeListener and HttpSessionBindingEvent
7/28/2019 Laboratorul 2 - Servlets servlets
http://slidepdf.com/reader/full/laboratorul-2-servlets-servlets 66/66
Sharing Information• Collaborating Web components share information
via objects maintained as attributes of four scopeobjects.Scope Object Class Accessible from
Web context javax.servlet.ServletCont
ext
Web components within a Web
context
session javax.servlet.http.HttpSes
sion
Web components handling a request
that belongs to the session
request Subclass of:
javax.servlet.ServletRequ
est
Web components handling the request
page javax.servlet.jsp.PageCon
text
JSP page that creates the object