450 likes | 573 Vues
Java Servlets are dynamic Java programs that run on web servers, processing HTTP requests and generating responses in various formats, including HTML and plain text. Established by the servlet specification, these components play a vital role in Java EE architecture, enabling distributed, component-based, multi-tier enterprise applications. This overview covers servlet definitions, life cycle, mapping URLs, and the servlet request-response model, along with examples demonstrating servlet operations. Explore the key features and workings of Java Servlets in web application development.
E N D
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
J2EE architecture Distributed component-based multi-tier enterprise application model
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
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
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!“); } ... }
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>“); } ... }
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>
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>
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
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
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
Servlet Interfaces & Classes interfaces classes
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
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
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
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"); } ... }
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; } ... }
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!
doGet, doPost, doXxx • Handles GET, POST and other requests • Override these to provide desired behavior
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
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
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>") } }
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
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
Four Scope Objects: Classes • Web context javax.servlet.ServletContext • Session javax.servlet.http.HttpSession • Request javax.servlet.http.HttpServletRequest • Page javax.servlet.jsp.PageContext
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
Scope of ServletContext • There is one ServletContext object per "web application" per Java Virtual Machine
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"); }
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); ...
Logging public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... getServletContext().log(“Life is good!”); ... getServletContext().log(“Life is bad!”, someException);
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
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
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
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
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
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
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
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
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
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()
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
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