1 / 45

Java Servlet Technology

Java Servlet Technology. Introduction. Servlets are Java programs that run on a Web server , handle HTTP requests and build Web pages S ervlet specification versions [v ersion 1.0 ] June 1997 [v ersion 2.4] November 2003 [v ersion 2.5] September 2005. J2EE architecture.

Download Presentation

Java Servlet Technology

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Servlet Technology

  2. Introduction • Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages • Servlet specification versions • [version 1.0] June 1997 • [version 2.4]November 2003 • [version 2.5]September 2005

  3. J2EE architecture Distributed component-based multi-tier enterprise application model

  4. Servlets in J2EE Java Servlet - a Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web clients using a request-response paradigm

  5. What is Servlet? • Java™ objects which are based on servletframework and APIs and extend thefunctionality of a HTTP server • Mapped to URLs and managed bycontainer with a simple architecture • Available and running on all majorweb servers and application servers • Platform and server independent

  6. A Servlet That Generates Plain Text import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World!“); } ... }

  7. A Servlet That Generates HTML import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException { response.setContentType("text/html“); PrintWriter out = response.getWriter(); out.println("<title>Hello World!</title>“); } ... }

  8. Mapping URLs to Servlets • When a request is received by the web container it must determine which web component should handle the request • Need to add a servlet definition and a servlet mapping for each servlet to web.xml file <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping>

  9. URL patterns • Four types of URL patterns • Exact match:<url-pattern>/dir1/dir2/name</url-pattern> • Path match:<url-pattern>/dir1/dir2/*</url-pattern> • Extension match:<url-pattern>*.ext</url-pattern> • Default resource:<url-pattern>/</url-pattern>

  10. Servlets and JSP - Comparison JSP is a text-based document capable of returning dynamic content to a client browser Servlets typically are used for returning non-HTML data

  11. Servlet Request & Response Model

  12. What Does Servlet Do? • Receives client request (mostly in the form ofHTTP request) • Extract some information from the request • Do content generation or business logic process(possibly by accessing database, invoking EJBs,etc) • Create and send response to client (mostly in theform of HTTP response) or forward the request toanother servlet or JSP page

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

  14. Servlet Interfaces & Classes interfaces classes

  15. Servlet Life Cycle • The life cycle of a servlet is controlled by the container • When a HTTP request is mapped to a servlet, the container performs the following steps • If an instance of the servlet does not exist, the web container • Loads the servlet class • Creates an instance of the servlet class • Initializes the servlet instance by calling the init method • Invokes the service method, passing request and response objects

  16. Servlet Life Cycle Methods

  17. Servlet Life Cycle Methods • Invoked by container • container controls life cycle of a servlet • Defined in • javax.servlet.GenericServlet class • init() • destroy() • service() - this is an abstract method • javax.servlet.http.HttpServlet class • doGet(), doPost(), doXxx() • service() - implementation

  18. init() & destroy() • init() • Invoked once when the servlet is first instantiated • Not called for each request • Perform any set-up in this method • setting up a database connection • destroy() • Invoked before servlet instance is removed • Not called after each request • Perform any clean-up • closing a previously created database connection

  19. Example: init() public class CatalogServlet extends HttpServlet { private BookDB bookDB; // Perform any one-time operation for the servlet, // like getting database connection object. // Note: In this example, database connection object is assumed // to be created via other means (via life cycle event // mechanism) // and saved in ServletContext object. This is to share a same // database connection object among multiple servlets public void init() throws ServletException { bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException("Couldn't get database"); } ... }

  20. Example: destroy() public class CatalogServlet extends HttpServlet { private BookDB bookDB; public void init() throws ServletException { bookDB = (BookDB)getServletContext(). getAttribute("bookDB"); if (bookDB == null) throw new UnavailableException( "Couldn't get database"); } public void destroy() { bookDB = null; } ... }

  21. service() • Is called in a new thread by server for each request • Dispatches to doGet, doPost, etc • service() methods take generic requests and responses: service(ServletRequest request, ServletResponse response) • Do not override this method!

  22. doGet, doPost, doXxx • Handles GET, POST and other requests • Override these to provide desired behavior

  23. Things to 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

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

  25. 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>") } }

  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 • 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: Classes • Web context javax.servlet.ServletContext • Session javax.servlet.http.HttpSession • Request javax.servlet.http.HttpServletRequest • Page javax.servlet.jsp.PageContext

  29. WebContext (ServletContext) • Used by servets to • Set and get context-wide (application-wide)object-valuedattributes • Get request dispatcher • To forward to or include web component • Access Web context-wide initialization parametersset in the web.xml file • Access Web resources associated with the Webcontext • Log • Access other misc information

  30. Scope of ServletContext • There is one ServletContext object per "web application" per Java Virtual Machine

  31. How to Access ServletContext? • Within your servlet code, call getServletContext() 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 newUnavailableException( "Couldn't get database"); }

  32. Dispatching to Another Component public void doGet (HttpServletRequest request,HttpServletResponseresponse) 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></html>"); // Get the dispatcher; it gets the banner to the user RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/banner"); if (dispatcher != null) dispatcher.include(request, response); ...

  33. Logging public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... getServletContext().log(“Life is good!”); ... getServletContext().log(“Life is bad!”, someException);

  34. Session Tracking • Why session tracking? • User registration • Web page settings • On-line shopping cart • HTTP is stateless! • Have to use specific methods: • Cookies • Hidden Form Fields • URL Rewriting

  35. Cookies • Idea: associate cookie with data on server String sessionID = makeUniqueString(); HashMap sessionInfo = new HashMap(); HashMap globalTable = findTableStoringSessions(); globalTable.put(sessionID, sessionInfo); Cookie sessionCookie = new Cookie("JSESSIONID", sessionID); sessionCookie.setPath("/"); response.addCookie(sessionCookie); • Still to be done: • Extracting cookie that stores session identifier • Setting appropriate expiration time for cookie • Associating the hash tables with each request • Generating the unique session identifiers

  36. Hidden Form Fields • Idea: <INPUT TYPE="HIDDEN" NAME="session" VALUE="..."> • Advantage • Works even if cookies are disabled or unsupported • Disadvantages • Lots of tedious processing • All pages must be the result of form submissions

  37. URL Rewriting • Idea • Client appends some extra data on the end of each URL that identifies the session • Server associates that identifier with data it has stored about that session • E.g., http://host/path/file.html;jsessionid=1234 • Advantage • Works even if cookies are disabled or unsupported • Disadvantages • Must encode all URLs that refer to your own site • All pages must be dynamically generated • Fails for bookmarks and links from other sites

  38. The Session Tracking API • Session tracking API built on top of URL rewriting or cookies • Look up HttpSession object associated with current request (or create new one) • All cookie/URL rewriting mechanics hidden • Look up information associated with a session • Associate information with a session

  39. Example: Looking Up Session HttpSession session = request.getSession(true); ShoppingCart sc = (ShoppingCart) session.getAttribute("shoppingCart"); if (cart == null) { cart = new ShoppingCart(); session.setAttribute("shoppingCart", cart); } ... // do something with your shopping cart object

  40. HttpSession Methods • getAttribute(String name) • Extracts a previously stored value from a session object. Returns null if no value is associated with given name. • setAttribute(name, value) • Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener. • removeAttribute(name) • Removes values associated with name • getAttributeNames() • Returns names of all attributes in the session • getId() • Returns the unique identifier

  41. HttpSession Methods • isNew() • Determines if session is new to client (not to page) • getCreationTime() • Returns time at which session was first created • getLastAccessedTime() • Returns time at which session was last sent from client • getMaxInactiveInterval, setMaxInactiveInterval • Gets or sets the amount of time session should go withoutaccess before being invalidated • invalidate() • Invalidates current session

  42. Getting Request Parameters • A request can come with any number ofparameters • 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("paramName”) • Returns the value of paramName • Returns null if no such parameter is present • Works identically for GET and POST requests

  43. Getting Information From Response • Client information • String request.getRemoteAddr() • String request.getRemoteHost() • Server information • String request.getServerName() • int request.getServerPort() • Misc • ServletInputStream getInputStream() • BufferedReader getReader() • String getProtocol() • String getContentType() • boolean isSecure()

  44. Servlet 2.4 vs Servlet 2.5 • A new dependency on J2SE 5.0 • Support for annotations • @Resource, @PostConstruct and @PreDestroy, @EJB, @WebServiceRef, @DeclareRoles, @RunAs • Several web.xml conveniences • Servlet name wildcarding • Multiple patterns in mappings • A handful of removed restrictions • Error handling • Session tracking • Some edge case clarifications

  45. References • Java Servlet Specification 2.4http://jcp.org/aboutJava/communityprocess/final/jsr154/index.html • J2EE Tutorial “Java Servlet Technology” http://java.sun.com/javaee/5/docs/tutorial/doc/bnafd.html • New features added to Servlet 2.5 http://www.javaworld.com/javaworld/jw-01-2006/jw-0102-servlet.html?page=3 • Servlet Basics presentation http://www.javapassion.com/j2ee/ServletBasics_speakernoted.pdf

More Related