Objectives Java Servlet Web Components Support Environments for Java Servlets Servlets with CGI Compared to Java Applets Functionality of Java Servlets Java Servlet API Java Servlet Debugging
Introduction to Java Servlets Java Servlets technology provides an HTTP-based request and response paradigm on web servers. Java Servlets can handle generic service requests and respond to the client’s requests. Java Servlets are used in embedded systems, wireless communication, and any other generic request/response application. The Common Gateway Interface (CGI) was a popular technology used to generate dynamic HTTP web contents in the mid-1990s.
CGI and Java Servlets Technology
Java Servlets Advantages Efficiency: Reduction of the time need for creating new processes and initialization and reduction of memory requirements as well. Convenience: All needed functionality is provided by the Servlets API. Portability: Cross-platform, Write Once Run Anywhere (WORA) code. Security: Built-in security layers. Open source: Free Servlet development kits available for download. Functionality: Session tracking, data sharing, JDBC database connections, etc.
Java Applet and Java Servlet
Java Applet and Java Servlet, contd.
Introduction to Java Servlets, contd. A Servlet component can delegate the requests to its back-end tier such as a database management system, RMI, EAI, or other Enterprise Information System (EIS). A Servlet is deployed as a middle tier just like other web components such as JSP components. The Servlet components are building block components, which always work together with other components such as JSP components, JavaBean components, Enterprise Java Bean (EJB) components, and web service components. A Servlet component is also a distributed component, which can provide services to remote clients and also access remote resources.
Support Environments for Java Servlets A Java Servlet application is supported by its Servlet container. The Apache Tomcat web server is the official reference implementation of Servlet containers, supporting Servlets and JSP.
Web Server Configuration An XML format file called server.xml is used to control and configure the behavior and setting of the Tomcat web server. This file is located in the conf subdirectory of the Tomcat installation directory.
Web Server Configuration, contd. 1. Reset the server port number where the Servlet class or other web component will listen for requests. 2. Turn on Servlet reloading so that you don’t need to reload the recompiled Servlet.
Java Servlets Basics The Java Servlet is a server-side web component that takes a HTTP request from a client, handles it, talks to a database, talks to a JavaBean component, and responds with a HTTP response or dispatches the request to other Servlets or JSP components. Servlets can dynamically produce text-based HTML markup contents and binary contents as well contents based on the client’s request.
Java Servlet Architecture A Java Servlet is a typical Java class that extends the abstract class HttpServlet. The HttpServlet class extends another abstract class called GenericServlet. The GenericServlet class implements three interfaces: javax.servlet.Servlet, javax.servlet.ServletConfig, and java.io.Serializable.
Java Servlet Class Hierarchy
Servlet Lifecycle A Servlet has a lifecycle just like a Java applet. The lifecycle is managed by the Servlet container. There are three methods in the Servlet interface, which each Servlet class must implement. They are init(), service(), and destroy().
The Lifecycle of a Servlet
Processing of HTTP Requests and Responses The prototypes of doGet() and doPost() void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException; void doPost( HttpServletRequest request, HttpServletResponse response )
Processing of HTTP Requests and Responses, contd. HttpServletRequest and HttpServletResponse are the two interfaces that provide the Servlet with full access to all information from the request and the response sent back to the client. When the doGet() or doPost() is called, the Servlet container passes in the HttpServletRequest and HttpServletResponse objects.
import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; import java.text.DecimalFormat; public class TestServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws javax.servlet.ServletException, java.io.IOException String temperature = req.getParameter("temperature"); DecimalFormat twoDigits = new DecimalFormat("0.00"); try double tempF = Double.parseDouble(temperature); String tempC = twoDigits.format((tempF -32)*5.0/9.0); PrintWriter out = res.getWriter(); out.println("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body>"); out.println("<h3>" + temperature + " Fahrenheit is converted to " + tempC + " Celsius</h3><p>"); out.println("</body>"); out.println("</html>"); } catch(Exception e) res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "There was an input error");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <head> </head> <body> <h3>Please enter Fahrenheit temperature:</h3><p> <form action="/conv/test"> Temperature(F) : <input type="text" name="temperature"><br> <input type="submit" value="Submit"> </form> </body> </html>
Communication from Clients to HTTP Servlets For GET type HTTP requests you can also directly type http://<host>/<servletName> in the URL location field of the browser if you don’t want to pass in any parameter values. If you do need to pass in some parameter values with the request you can type http://<host>/<servletName>?<paramterName>=<value> such as http://localhost:8080/conv/conversion?feet=100.
Ways Servlets Communicate with Other Web Components There are four web component scopes: page, request, session, and application. The page scope only covers the current page. Web components can share and delegate the data within a request, session, or application scope.
Attribute Scopes in Servlet
Web Client Session Tracking HTTP is a stateless protocol that takes requests from web clients and responds with a file. It does not memorize what has happened in the past. FTP and Telnet protocols know the client states, such as users, connections, and disconnections but HTTP does not. A client session consists of a series of conversations between the client and web applications on the web server.
Web Client Session Tracking, contd. There are two mechanisms to handle client session tracking. One is to save the client identification and session information on the server side once the Servlet gets a request from the client. The other is to save the client information on the client browser at the client side for subsequent request use.
Web Client Session Tracking, contd. The hidden form field is a form field that does not appear on the GUI interface, but it can carry user input data just like any other input field. We can pass data via a hidden form field in a static or dynamic HTML page in an HTML form as follows: <input type =”HIDDEN” name=”myId” value=”1234” />
Web Client Session Tracking, contd. URL Rewriting http://<host>/servlet/Servlet1;jsessionid=ABC123, where ABC123 is produced by the encodeURL() method of HttpServletResponse.
Web Client Session Tracking, contd. Servlet Cookies Cookies are text files that store sets of param/value pairs. The Servlet at the server side generates the cookie based on the client’s HTTP request. The cookie is created on the server side and sent back to the client along with the HttpServletResponse object. The cookie is stored in the client’s browser.
Servlet Cookie
HttpSession Object in Session Tracking Using the HttpSession API in session management is quite straightforward, and it may be the best option for session tracking in most cases. The HttpSession object can hold a session id that can be used to identify whether the requests are within the same session so that they can share the same data. Each HttpSession object represents a single user HTTP session.
Debugging Servlets The best solution to fix a runtime logic error is to plug in the Tomcat Servlet container to JBuilder, Eclipse, or VisualAge, or just use an integrated debugger in your IDE such as Sun One Studio, BEA WebLogic, or IBM WebSphere.
Debugging Servlets, contd. Check the generated HTML source code by using View Source from the web browser menu. Some simple HTML errors can be easily found this way, which can help to locate the Servlet error. Use the sendError(int sc) method of HttpServletResponse to send an error response to the client with the specified status code and a default message. Use the out.println() method to print debugging messages on the client page. Use the jdb Java debug utility to debug the Servlet.
Debugging Servlets, contd. Use the void log(String message) method of HttpServlet to write debug information into the log file in the Tomcat installation directory. Use System.out.println() or System.err.println() to write error messages. The error messages will be displayed on the server console if Tomcat is started in developer mode. Check the request data and response data separately. Determine whether clients have sent the right data or the Servlets responded the right data. You can have separate classes to detect these problems.
Chapter 2 The End