PART 1 Basic Servlet Programming

Objectives
• Explain servlets and the Servlet API • Compare the Servlet API with CGI • Use the primary classes in servlet programming • Implement simple servlets

Need for Dynamic Content
• Applets
– Limitation: based entirely on the client’s platform

• CGI scripts
– Based on the server platform to generate dynamic content – Limitations:
• Lack of scalability • Platform dependence

• Java Servlet technology
– a portable way to provide dynamic, user-oriented content.

Development Component: Servlets CLIENT WEB SERVER Application Server Business Logic Servlet Services Back End .

What is a Servlet? • Standard. server-side Java application that extends the capabilities of a Web Server – Runs completely on the server • Nothing is ever downloaded to the browser – A replacement for CGI scripts .

Why use Servlets? • Servlets have advantages in several areas: – Portability and flexibility – Security – Performance .

Portability and Flexibility • A rich set of platform-neutral Java APIs to connect to most backend assets • Platform independence through 'write once run anywhere' • Reusable objects (JavaBeans) .

Security Advantage • Called within server context – Can restrict servlet access – Can be part of a Single (global) Sign On security architecture .

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 .

Generic Servlet Invocation • Client makes a request of WebServer naming a Servlet 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) URL Request Servlet Instance Web Server Application Server .

Java Servlet API • The JSDK includes two packages which provide interfaces and classes for writing servlets – javax.http • Servlet interface define life-cycle methods – GenericServlet class for generic services – HTTPServlet class for HTTP-specific services .servlet – javax.servlet.

Servlet • Represents a service • Usually requested via URL • Servlets are loaded by an Application Server – At initialization of Server (if preload) – At first client request – Upon servlet reload .

Creates an instance of the servlet class. – If an instance of the servlet does not exist.Servlet Lifecycle • The lifecycle of a servlet is controlled by the container in which the servlet has been deployed. b. . Loads the servlet class. the Web container a. – Invokes the service method – It finalizes (removes) the servlet by calling the servlet's destroy method. Initializes the servlet instance by calling the init method. c.

Servlet Lifecycle (continued) First request mapped to servlet init() service() Request mapped to servlet destroy() .

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(). doTrace(). doOptions(). doDelete() .

doGet() and doPost() methods each have two parameters: – HttpServletRequest -. etc.Requests and Responses • The service(). HttpSession information. – HttpServletResponse -.provides access to request data (parameters).provides services to allow the servlet to supply a reply to the requesting client • Most servlet programming amounts to reading a request and writing a response .

content type. e..HTTP Servlet Request • Represents client's request • "Getters" for aspects of request.g. method.. length. 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 .. – – – – – – Request header.

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 .

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

HttpServletResponse res) throws ServletException.hasMoreElements()) { String name = (String) enum..Reading a POST public void doPost(HttpServletRequest req. IOException { … Enumeration enum = req.getParameterNames(). String value = req.nextElement(). //… do something with each pair.getParameter(name). } } .. while (enum.

.HTTP Servlet Response • Represents communication channel back to client • Allows servlet to return content and/or errors • Set content header (type. length...) • Redirect server to return a particular URL .

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 .

PrintWriter out = res. IOException { // get stream to output HTML on! res. out. }} .println("<HTML><BODY>").Simple Servlet public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req.setContentType("text/html").println("</BODY></HTML>").getWriter().println("<h1>Hello World!</h1>"). HttpServletResponse res) throws ServletException. // send out a simple banner out. out.

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

Invoking a Servlet (2)
• Alternatively most servlet engines support registering 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

Summary
• We've seen the advantages Servlets have over CGI
– Security, Portability, Performance

• We've introduced the basic Servlet classes and interfaces:
– Servlet, GenericServlet, HttpServlet, – HttpServletRequest, HttpServletResponse

PART 2 Cookie API .

HTTP Sessions in the Architecture Cookie Data CLIENT WEB SERVER Application Server Business Logic Servlet Services Servlet Services Back End .

Cookies • Cookies are a way to place persistent information 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 .

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 .

Cookies: Applications • By using cookies several problems can be solved: – Identifying a user during a session • Example: storing “shopping cart” items during an ecommerce session – Avoiding username and password – Customizing a site – Focusing advertising .

– Cannot be used to fill up someone’s disk or launch other DoS attacks • Cookies may be a threat to privacy .Cookies: Security Issues • Cookies are a good alternative for lowsecurity sites. and thus can't be used to insert viruses or attack your system in any way. • Proper used cookies are not a serious security threat. – Cookies are never interpreted or executed in any way.

such as: – Validation information – Secure information (credit card numbers) • Cookies can be used to give added value to a site.Proper Cookie Use • Cookies shouldn't be used for things best kept on the server. but the site should not depend on them – Users can turn off cookies on their computers • The Session API typically uses the Cookie API .

Cookie API • Creating cookies – Cookie(String name.getCookies() .addCookie(Cookie aCookie) • Retrieving cookies – HttpServletRequest.String value) • Saving a cookie – HttpServletResponse.

domain. path. comment.Cookie API (continued) • 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. MaxAge .

getValue().getCookies().equals("userType")) userType = cookies[i]. i<cookies. Cookie[] cookies = req.equals("expert")) // do expert HTML else // do novice HTML } . if (cookies != null) { for (int i=0. i++) { if (cookies[i]. HttpServletResponse res) { String userType = "novice".length.Cookie Example public void doGet(HttpServletRequest req. }} if (userType.getName().

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

PART 3 HTTPSession: Management of Application Data .

Objectives • Explain Session Management • Tie Servlets with Session Management .

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 .

HTTP Session:Managing Application Data CLIENT WEB SERVER Application Server Business Logic Servlet Services Session Data Back End .

shopping cart..Session Management • Web Applications must manage state information – Current customer. – 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 .. .

getSession(boolean create) – Returns the current HttpSession – If create is true AND no current Session exists. Object) – Object getAttribute(String) . a newly created session is returned • HttpSessions store application-specific information via a "key" – void setAttribute(String.HTTP Session • Ask for a Session from HttpRequest object – request.

Sessions at Runtime: Server • HttpSessions are managed by the servlet engine • Registered by id • Id must be delivered to client initially and presented back to server on subsequent “requests” .

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 .

Sessions at Runtime .

Session Invalidation • Sessions can be invalidated either programmatically or through a timeout – session.setMaxInactiveInterval(int) can provide session specific timeout value .invalidate() – Removes all values from the session • The Session timeout (inactive interval) can be set for the application server as a whole • Also session.

Session Example • We'll follow a simple e-commerce example using 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 .

Bookstore Domain Classes • Very simple. standard domain objects – Java Beans (but not required) .

Book Choice Servlet • Order is the key – Get the session – Create a domain object from the POSTed data – Put the new object on the session for later use by other servlets .

Book Choice Servlet .

Credit Information Servlet .

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.setAttribute("aKey". synchronizing various Servlet's doPost() methods) • Instead.} . wrap sets of putValue() and getValue() in a synchronized block synchronized (aSession) { aSession. anObject).

HttpSession Classes .

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 .

PART 4 Miscellaneous Servlet APIs .

Objectives • Explain the Request Dispatcher Interface • Explain the Servlet Context API • Use send/redirect to handle errors .

Servlet APIs CLIENT WEB SERVER Application Server Business Logic Servlet Services Servlet Services Back End .

Request Dispatcher • JSDK (Servlet API) 2.RequestDispatcher • Used to support both forwarding processing to and including response from a variety of local Web resources • A RequestDispatcher is acquired from the ServletContext .1 added a new interface.servlet. javax.

RequestDispatcher .

getServletConfig().html"). getRequestDispatcher("/WDDisplayOffers").Sample Use of RequestDispatcher getServletConfig(). res). . include(req. getRequestDispather("/pages/navigation_bar.getServletContext().getServletContext().forward(req. res).

servlet.ServletContext .Servlet Context • A Servlet Context defines a group of related servlets – Allows for virtual hosting and relative paths – Rooted at a particular point in the URL namespace – Scope for data sharing among servlets – Scope for class reloading for related servlets • Programmatically accessed via javax.

Servlet Context Binding was.com /HRApps /WDInternet /app1 /app2 /WDLogin /WDDisplayOffer Servlet context app1 Servlet context app2 Servlet context WDInternet .WebDev.

Servlet Context (continued) • 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 .

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.http.servlet. removed.ServletContextListener and ServletContextEvent • Attribute added.servlet. removed.http.servlet.HttpSessionAttributeListener and HttpSessionBindingEvent . timeout – javax. invalidation. replaced – javax.HttpSessionListener and HttpSessionEvent • Attribute added.servlet. replaced – javax.ServletContextAttributeListener and ServletContextAttributeEvent – Session object • Creation.

servlet.jsp.ServletRequ est Web components within a Web context Web components handling a request that belongs to the session Web components handling the request page javax.http.servlet. Scope Object Class Accessible from Web context session request javax.ServletCont ext javax.Sharing Information • Collaborating Web components share information via objects maintained as attributes of four scope objects.servlet.servlet.HttpSes sion Subclass of: javax.PageCon JSP page that creates the object text .

Sign up to vote on this title
UsefulNot useful