Download presentation
Presentation is loading. Please wait.
1
Servlets 1: Introduction
©SoftMoore
2
Overview of Servlets and JSP
Servlets are Java classes that support the request/response computing model of the web. Servlet methods are invoked by the web server in the process of handling requests. Servlets run on the server, not the client. server-side, not client-side The most basic type of servlet writes an HTML page as the response. ©SoftMoore Consulting
3
Servlets 1: Introduction
Basic Idea Use Java to support a request/response computing model that is commonly used in web servers Servlet API is a standard extension defined primarily in two packages javax.servlet javax.servlet.http Related Concepts JavaServer Pages (JSP) JavaServer Faces (JSF) ©SoftMoore
4
Servlets 1: Introduction
Functions of a Servlet Respond to HTTP method calls GET, POST, etc. Read form data submitted by the client Read header information sent by the client Generate the response back to the client Send the response back to the client HTML status codes response headers ©SoftMoore
5
Key Components of the Servlet Architecture
Servlets 1: Introduction Key Components of the Servlet Architecture javax.servlet «interface» Servlet «interface» ServletConfig «interface» ServletContext GenericServlet «interface» ServletRequest «interface» ServletResponse javax.servlet.http HttpSession HttpServlet «interface» HttpServletRequest «interface» HttpServletResponse ©SoftMoore
6
Servlets 1: Introduction
Servlet API Provides support in four categories: Servlet life cycle management Access to servlet context Utility classes HTTP-specific support classes While it is possible to create a general-purpose servlet by extending GenericServlet, most web applications will use the HTTP-specific classes. ©SoftMoore
7
Servlets 1: Introduction
The Servlet Interface Three main methods: init() service() destroy() Two ancillary methods: getServletConfig() getServletInfo() ©SoftMoore
8
Servlets 1: Introduction
The init() Method public void init(ServletConfig config) throws ServletException Invoked once when a servlet is first loaded (not called for each request) Class GenericSevlet provides a zero-argument convenience method init() that is called by its implementation of the one-argument method. public void init() throws ServletException Since most user-defined servlets extend GenericServletor or its subclass HttpServlet, they will usually just override the zero-argument version of method init() if they need additional initialization. ©SoftMoore
9
The init() Method (continued)
Servlets 1: Introduction The init() Method (continued) Initialization parameters for the servlet can be specified in the deployment descriptor (web.xml), or as part of annotation. (More on this later.) ©SoftMoore
10
Servlets 1: Introduction
The service() Method public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException Called in a new thread by the server for each request multiple service requests processed concurrently resource access must be thread-safe Reads the client request sent from the host server and produces the response message Class ServletRequest contains of name/value pairs of parameters and an InputStream. Class ServletResponse represents the servlet’s reply. Dispatches to doGet(), doPost(), etc. for HTTP ©SoftMoore
11
Servlets 1: Introduction
The destroy() Method public void destroy() Used clean up any resources such as open files or database connections before the servlet is unloaded Can be an empty method Important: Write destroy() to allow all service() calls to complete or to end them abruptly with a timeout, ©SoftMoore
12
Servlets 1: Introduction
The Servlet Life Cycle Server init() (called once) Request Client (Browser) service() doGet() doPost() ... Response destroy() (called once) ©SoftMoore
13
Servlets 1: Introduction
HTTP Support Package javax.servlet.http provides support for HTTP Class HttpServlet implements the Servlet interface. The service() method of HttpServlet dispatches the HTTP messages to one of several special methods doGet() − doPost() doPut() − doDelete() doHead() − doOptions() doTrace() ©SoftMoore
14
The service() Method in HttpServlet
Servlets 1: Introduction The service() Method in HttpServlet Server HttpServlet HTTP Client Request service() doGet() doPost() doPut() doDelete() doHead() doOptions() doTrace() ©SoftMoore
15
Servlets 1: Introduction
Using HttpServlet Create a new servlet by extending HttpServlet and overriding either doGet() or doPost(), or possibly both. Override other methods to get more fine-grained control. ©SoftMoore
16
Servlets 1: Introduction
Overriding doGet() A servlet’s doGet() method should Read request data, such as input parameters Set response headers (length, type, and encoding) Write the response data Remember: When overriding doGet(), the HTTP GET method is expected to be safe and idempotent. ©SoftMoore
17
Servlets 1: Introduction
Overriding doPost() Override a servlet’s doPost() method When you need to process an HTML form posting To handle a large amount of data being sent by a client ©SoftMoore
18
Providing Identical Responses to GET and POST
Servlets 1: Introduction Providing Identical Responses to GET and POST It is possible to have your servlet support GET and POST with the same functionality by overriding doGet() to call doPost(). public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } Note: Normally this should be avoided. HTTP methods GET and POST should usually be used for different purposes. ©SoftMoore
19
Servlets 1: Introduction
Generating HTML Tell the browser that you are sending HTML. response.setContentType("text/html"); Obtain a Printwriter for building the HTML web page. PrintWriter out = response.getWriter(); Use print() and println() statements to write legal HTML. out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); ... Check your HTML with a formal syntax validator ©SoftMoore
20
Example: HelloWorld Servlet (HelloWorld.java)
Servlets 1: Introduction Example: HelloWorld Servlet (HelloWorld.java) package com.softmoore.hello; import java.io.PrintWriter; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { private static final long serialVersionUID = L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) try response.setContentType("text/html"); (continued on next slide) ©SoftMoore
21
Example: HelloWorld Servlet (continued)
Servlets 1: Introduction Example: HelloWorld Servlet (continued) PrintWriter out = response.getWriter(); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println(" <title>Hello</title>"); out.println("</head>"); out.println("<body>"); out.println(" <h1 align=\"center\">Hello, world.</h1>"); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { log("Unexpected exception", ex); ©SoftMoore
22
HelloWorld Servlet in a Browser
Servlets 1: Introduction HelloWorld Servlet in a Browser ©SoftMoore Consulting
23
Summary: Developing Servlets that Generate HTML
Servlets 1: Introduction Summary: Developing Servlets that Generate HTML Create a class that extends HttpServlet Override init() if necessary to handle one-time setup initialization Override doGet() or doPost() to perform main actions of the servlet HttpServletRequest contains incoming information HttpServletResponse lets you set outgoing information call setContentType() to specify MIME type call getWriter() to obtain a Writer pointing to client ©SoftMoore
24
Servlets 1: Introduction
Overriding doHead() If doGet() is overridden but doHead() is not, the HttpServlet class can generate an appropriate response to an HTTP HEAD request using doGet() HTTP HEAD is identical to HTTP GET minus the body of the message. Override doHead() to provide a more efficient and/or customized response. ©SoftMoore
25
Overview of Servlets and JSP
Using Servlets The real power of servlets becomes apparent when we need to create content dynamically based on user feedback. Servlets can handle requests with parameters; e.g., from HTML forms. The servlet can examine the parameters and formulate a response unique to the user. In formulating the response, the servlet can authenticate the user, query a database, etc. Example. Consider a query to Amazon or Barnes & Noble for books about Java. The results must be created dynamically. ©SoftMoore Consulting
26
Servlets 1: Introduction
Service Methods The service provided by a servlet is implemented in the service() method of a GenericServlet and in the doXXX() methods (doGet(), doPost(), doPut(), ...) of an HttpServlet. The term service method is used to refer for any of these methods. Service method have two parameters the request coming from the client the response to be returned to the client Service methods extract information from the request access external resources create the response ©SoftMoore
27
Information Contained in HttpRequest Objects
Servlets 1: Introduction Information Contained in HttpRequest Objects A request contains methods for accessing parameters − data passed from the client to the server (e.g., input fields from an HTML form) attributes − objects used to pass information between collaborating servlets, from a servlet to a JSP page, or from the server to a servlet headers − HTTP header fields such as Accept, Host, Referer [sic], and User-Agent. session − used to identify a user across multiple web pages and to store information about that user user authentication information ©SoftMoore
28
Parameters versus Attributes
Servlets 1: Introduction Parameters versus Attributes In the context of servlets and JSP, a parameter is a name-value pair passed from the client to the server as part of a request. parameter name has type String parameter value has type String usually specified in an HTML form but can be included as part of a query string An attribute is a name-value pair for server-side usage only (not part of the client request) attribute name has type String attribute value can be any object type (use wrapper classes for primitives) usually created within a servlet ©SoftMoore
29
Servlets 1: Introduction
Attribute Scopes An attribute exists within a specified (server-side) scope: page (JSP only) − available only for the current JSP page request − available only for the life of the request session − available only for the life of the session A session is an object that contains information about a user across multiple HTTP requests; e.g., a shopping cart would be part of a session. application − available for the entire life of the application Request and session attributes are probably the most common. ©SoftMoore
30
Accessing Parameters and Attributes
Servlets 1: Introduction Accessing Parameters and Attributes Example: accessing parameters in a request String Addr = request.getParameter(" Addr"); Example: accessing an attribute with request scope Customer customer = (Customer) request.getAttribute("customer"); Example: adding an attribute to a session ShoppingCart cart = new ShoppingCart(); ... // items added to shopping cart HttpSession session = request.getSession(true); session.setAttribute("cart", cart); Example: accessing an attribute with session scope ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); different servlets Note: Value returned from getAttribute() must be cast. ©SoftMoore
31
Selected Methods in HttpRequest
Servlets 1: Introduction Selected Methods in HttpRequest Object getAttribute(String name) String getHeader(String name) String getParameter(String name) Enumeration<String> getParameterNames() String[] getParameterValues(String name) String getRemoteUser() HttpSession getSession(boolean create) boolean isUserInRole(String role) void removeAttribute(String name) void setAttribute(String name, Object o) ©SoftMoore
32
Using Method ServletRequest.getParameter()
Servlets 1: Introduction Using Method ServletRequest.getParameter() Call method getParameter("paramName") to retrieve input data with the corresponding field name in the form returns null if there is no field with that name in the form returns an empty string (or possibly a string with whitespace) if the field is blank when the form is submitted Handling missing or malformed data use default values redisplay the form with error message(s) Example String userName = request.getParameter("userName"); if (userName != null && !userName.trim().equals("")) ... ©SoftMoore
33
Using Method ServletRequest.getParameterValues()
Servlets 1: Introduction Using Method ServletRequest.getParameterValues() It is possible to have multiple parameter values all with the same name; e.g., several check boxes with the same name or a drop-down list that allows multiple selections Call method getParameterValues("paramName") to retrieve all of the values as an array of String. returns null if there is no field with that name in the form returns an array of length one if the parameter has a single value Example String[] favorites = request.getParameterValues("favorites"); if (userName != null) { for (String favorite : favorites) ... ©SoftMoore
34
Constructing Responses
Servlets 1: Introduction Constructing Responses A response contains data that will be passed from the server back to the client. The response contains methods that allow you to Retrieve output streams for “writing” data to the client. PrintWriter for character data ServletOutputStream for binary data Set the content type (e.g., text/html) Set localization information Set HTTP status codes Manage cookies (e.g., for session tracking) ©SoftMoore
35
Selected Methods in HttpResponse
Servlets 1: Introduction Selected Methods in HttpResponse void addCookie((Cookie cookie) String encodeURL(String url) ServletOutputStream getOutputStream() PrintWriter getWriter() void sendRedirect(String location) void setContentType(String type) void setStatus(int sc) ©SoftMoore
36
Example: HTML Form (HelloUserForm.html)
Overview of Servlets and JSP Example: HTML Form (HelloUserForm.html) <html> ... <form method="get" action="HelloUser"> <table cellpadding="5" align="center"> <tr> <td align="right">Enter your name: </td> <td><input type="text" size="20" name="userName"/></td> </tr> <td> </td> <td><input type="submit" value="Submit"/></td> </table> </form> </html> calls servlet HelloUser ©SoftMoore Consulting
37
HelloUserForm.html in a Browser
Overview of Servlets and JSP HelloUserForm.html in a Browser ©SoftMoore Consulting
38
Using a Servlet to Process the Form (HelloUser.java)
Overview of Servlets and JSP Using a Servlet to Process the Form (HelloUser.java) package com.softmoore.hello; import java.time.LocalTime; import java.io.PrintWriter; import javax.servlet.http.*; public class HelloUser extends HttpServlet { private static final long serialVersionUID = L; private static final LocalTime NOON = LocalTime.of(12, 0, 0); (continued on next page) ©SoftMoore Consulting
39
Using a Servlet to Process the Form (continued)
Overview of Servlets and JSP Using a Servlet to Process the Form (continued) @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { try response.setContentType("text/html"); PrintWriter out = response.getWriter(); String userName = request.getParameter("userName"); String message; if(LocalTime.now().isBefore(NOON)) message = "Good morning, " + userName + "."; else message = "Good afternoon, " + userName + "."; (continued on next page) ©SoftMoore Consulting
40
Using a Servlet to Process the Form (continued)
Overview of Servlets and JSP Using a Servlet to Process the Form (continued) out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println(" <title>Hello</title>"); out.println("</head>"); out.println("<body>"); out.println(" <h1 align=\"center\">" + message + "</h1>"); out.println("</body>"); out.println("</html>"); } catch (Exception ex) { log("Unexpected exception", ex); ©SoftMoore Consulting
41
HelloUser Servlet in a Browser
Overview of Servlets and JSP HelloUser Servlet in a Browser Parameter name/value are passed as part of URL for GET method ©SoftMoore Consulting
42
Directory Structure for Tomcat on Windows
JavaServer Pages (JSP) Directory Structure for Tomcat on Windows install_directory /bin (executable files for Tomcat − “.bat” and “.sh”) /conf (configuration files) /lib (jar files for all web applications plus Tomcat) /logs /temp /webapps /ROOT (default web application directory) /webapp1 /webapp2 … /work (servlets generated from JSP files) ©SoftMoore Consulting
43
Directory Structure for a Web Application
JavaServer Pages (JSP) Directory Structure for a Web Application webapp1 *.html, *.jsp, JavaScript, style sheets, images, etc. subdirectories containing *.html, *.jsp, etc. /META-INF context.xml /WEB-INF web.xml (deployment descriptor) /classes (Java class files and associated resources) /lib (JAR files for this web application) /tags (implementations of tag libraries) Directory structure for HTML and JSP pages parallels URL path ©SoftMoore Consulting
44
Servlet Configuration and Mapping
Servlets 1: Introduction Servlet Configuration and Mapping A servlet container is the component of a web server that manages Java servlets. Informally we often refer to the web server itself as the servlet container. Servlets must be declared and mapped to a URL within the servlet container. Two approaches for declaring/mapping servlets in the deployment descriptor web.xml only approach prior to servlet version 3.0 annotations introduced in servlet API version 3.0 the deployment descriptor web.xml can be omitted, but if used, it must specify version 3.0 or later ©SoftMoore
45
Deployment Descriptor (web.xml)
Servlets 1: Introduction Deployment Descriptor (web.xml) The deployment descriptor is an XML file named web.xml with information about the servlet API version the application display name/description servlet declarations and URL mappings welcome file list error page mapping security constraints and roles etc. ©SoftMoore
46
Servlets 1: Introduction
Example: web.xml <?xml version="1.0" encoding="ISO "?> <web-app xmlns=" xmlns:xsi=" xsi:schemaLocation=" version="3.1" metadata-complete="true"> <description>A library web application.</description> <display-name>Libraries-R-Us</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.jsp</welcome-file> </welcome-file-list> (continued on next slide) ©SoftMoore
47
Example: web.xml (continued)
Servlets 1: Introduction Example: web.xml (continued) <servlet> <servlet-name>Admin</servlet-name> <servlet-class>com.example.library.Admin</servlet-class> </servlet> <servlet-mapping> <url-pattern>/admin/Admin</url-pattern> </servlet-mapping> Note: If servlets are specified in the deployment descriptor, then both <servlet> and <servlet-mapping> elements are required for each servlet. (continued on next slide) ©SoftMoore
48
Example: web.xml (continued)
Servlets 1: Introduction Example: web.xml (continued) <security-constraint> <web-resource-collection> <web-resource-name>Admin Security</web-resource-name> <description>Protect the Admin pages</description> <url-pattern>/admin/*</url-pattern> </web-resource-collection> <auth-constraint> <description>Authorized Admin Roles</description> <role-name>admin</role-name> </auth-constraint> </security-constraint> (continued on next slide) ©SoftMoore
49
Example: web.xml (continued)
Servlets 1: Introduction Example: web.xml (continued) <login-config> <auth-method>FORM</auth-method> <realm-name>Form-Based Authentication</realm-name> <form-login-config> <form-login-page>/login.jsp</form-login-page> <form-error-page>/error.jsp</form-error-page> </form-login-config> </login-config> <security-role> <description>Roles used by this application</description> <role-name>admin</role-name> </security-role> (continued on next slide) ©SoftMoore
50
Example: web.xml (continued)
Servlets 1: Introduction Example: web.xml (continued) <session-config> <session-timeout>60</session-timeout> <!-- 60 minutes --> </session-config> </web-app> (continued on next slide) ©SoftMoore
51
Attribute metadata-complete
Since version 3.0, the web-app element of the web deployment descriptor contains an attribute called metadata-complete. This attribute defines whether the web descriptor is complete or whether the class files of the web application should be examined for annotations that specify deployment information. If true, the servlet container ignores any servlet annotations present in the class files and uses only the configuration details mentioned in the deployment descriptor. If false or not specified, the servlet container scans all class files of the application for annotations. (can impact server startup performance) ©SoftMoore
52
Using Annotations to Declare/Map Servlets
Introduced in servlet API version 3.0, the can be used to declare a servlet class and map it to a URL. Example @WebServlet("/admin/Admin") public class Admin extends HttpServlet { ... } Note that the class must still extend HttpServlet. ©SoftMoore
53
Using Annotations to Declare/Map Servlets (continued)
replaces equivalent <servlet> and <servlet-mapping> configuration elements in the web deployment descriptor file (web.xml) Servlet containers process the annotated classes when the application is deployed. Note: Several additional annotations were also introduced in servlet API 3.0; e.g., @WebFilter ©SoftMoore
54
Annotations versus Deployment Descriptor
Primary advantage of using annotations to declare/map servlets − eliminates a lot of boilerplate XML Primary advantage of using the deployment descriptor to declare/map servlets − improved server startup performance when using a lot of servlets (provided attribute metadata-complete has been set to true). ©SoftMoore
55
Annotation Types Introduced in Servlet 3.0
@WebServlet ©SoftMoore
56
Servlet Initialization Parameters
Servlets 1: Introduction Servlet Initialization Parameters Are name-value pairs that can be used to initialize a servlet initialization parameter name has type String initialization parameter value has type String Can be declared in the deployment descriptor (web.xml), or as part of annotation. Are passed to the servlet via the ServletConfig parameter of the init() method Servlet initialization parameters are read only once − when the container initializes the servlet. ©SoftMoore
57
Example: Declaring Servlet Initialization Parameters in web.xml
<servlet> <servlet-name>Contact</servlet-name> <servlet-class>com.example.website.contact</servlet-class> <init-param> <param-name>adminName</param-name> <param-value>John Doe</param-value> </init-param> <param-name> Addr</param-name> </servlet> Note: Initialization parameters are declared in the <servlet> element. ©SoftMoore
58
Example: Declaring Servlet Initialization Parameters in the @WebServlet Annotation
@WebServlet("/contact", initParams = value="John } public class Contact extends HttpServlet { ... } ©SoftMoore
59
Accessing Servlet Initialization Parameters
Using the convenience method getInitParameter() inherited from class GenericServlet getInitParameter("adminName"); Using the ServletConfig object getServletConfig().getInitParameter("adminName"); There is also a method getInitParameterNames(), which returns an Enumeration<String> that can be used to iterate over all initialization parameters. The convenience method described in the first bullet above simply calls the ServletConfig method shown in the second bullet. ©SoftMoore
60
Servlet Context Information
Servlets 1: Introduction Servlet Context Information Class ServletContext is used to provide information to all servlets managed by the servlet container A ServletContext object is obtained by calling either of the following: getServletContext() convenience method inherited from GenericServlet getServletConfig().getServletContext(). Selected methods from ServletContext getAttribute(): returns the attribute with the given name getInitParameter(): returns an initialization parameter that is applicable to all servlets removeAttribute(): removes a named attribute setAttribute(): adds a key/value attribute ©SoftMoore
61
Servlets 1: Introduction
URL vs. URI Original URL is not directly accessible (but see HttpServletRequest.getRequestURL()) Uniform Resource Identifier (URI) is available through HttpServletRequest.getRequestURI() method URI = URL minus protocol, host, port, and query See also HttpServletRequest.getServletPath() URL URI /servlet/DateServlet /servlet/DateServlet/more ©SoftMoore
62
Interface RequestDispatcher
Servlets 1: Introduction Interface RequestDispatcher A RequestDispatcher can be used to send a request to another resource on the server such as a servlet, an HTML page, or a JSP page. A RequestDispatcher can be obtained by calling method getRequestDispatcher(String path) as part of a service method such as doGet() or doPost(). Example forwardingUrl = response.encodeURL("..."); RequestDispatcher dispatcher = request.getRequestDispatcher(forwardingUrl); dispatcher.forward(request, response); specifies a servlet, an HTML page, or a JSP page ©SoftMoore
63
Servlet-Related Exceptions
Servlets 1: Introduction Servlet-Related Exceptions javax.servlet.ServletException a general exception a servlet can throw when it encounters difficulty javax.servlet.UnavailableException an exception that a servlet or filter throws to indicate that it is permanently or temporarily unavailable ©SoftMoore
64
Servlet Methods for Logging
public void log(String message) Writes the specified message to a servlet log file, prepended by the servlet’s name. public void log(String message, Throwable t) Writes an explanatory message and a stack trace for a given exception to the servlet log file, prepended by the servlet’s name If desired, it is possible to configure Tomcat to use Apache’s Log4j instead of the default implementation. ©SoftMoore
65
Servlets 1: Introduction
Debugging Servlets Log exceptions and messages Use IDE debugger Separate the request and response data Request: see EchoServer at Response: see WebClient at Stop and restart the server ©SoftMoore
66
Servlets 1: Introduction
Special Characters Situations where special characters can cause problems: Displaying text in a browser special characters: < > & " replace with HTML entities: < > & " Inserting data into a database special character: ' (apostrophe) use two apostrophes: '' Including characters as part of a URL (e.g., when using an HTTP GET method) special characters: any character except letters, digits, and * , _ use java.net.URLEncoder and java.net.URLDecoder ©SoftMoore
67
Example: Encoding SQL Queries
Servlets 1: Introduction Example: Encoding SQL Queries /** * Encodes SQL queries by replacing all occurrences of a * a single quote (apostrophe) with two single quotes * (to apostrophes). */ public static String encode(String source) { if (source == null || source.length() == 0) return source; StringBuffer buffer = new StringBuffer(2*source.length()); (continued on next slide) ©SoftMoore
68
Example: Encoding SQL Queries (continued)
Servlets 1: Introduction Example: Encoding SQL Queries (continued) for (int i = 0; i < source.length(); ++i) { char c = source.charAt(i); if (c == '\'') buffer.append(c); } else if (Character.isWhitespace(c)) buffer.append(' '); else return buffer.toString(); ©SoftMoore
69
Integrating Servlets with JDBC
Servlets 1: Introduction Integrating Servlets with JDBC Use cached PreparedStatement objects whenever possible. Use connection pooling for high-volume data access servlets (preferably via a pooling database driver) Use stored procedures to implement complex SQL logic. Stored procedures are faster than dynamic SQL and minimize network traffic for high-volume applications Ensure that your destroy() method closes any open database connections. ©SoftMoore
70
Instance Variables and Thread Safety
Every new client request allocates a new thread that calls the service method of your servlet. Under most circumstances, there is only one instance of your servlet, no matter how many client requests are in process. At any given moment, there may be many threads executing code in the service method of the servlet instance, with all threads all sharing the same instance data. Avoid instance variables if possible. If they are required, access to instance variables should be synchronized. ©SoftMoore
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.