1 / 105

Chapter 2 Java Servlets

Chapter 2 Java Servlets. Objectives. Introduce concepts of Java Servlet Web components Support Environments for Java Servlets Compare Servlet with CGI and Java Applets Discuss the functionality of Java Servlets Discuss the Java Servlet API Discuss the Java Servlet Debugging

dominique
Download Presentation

Chapter 2 Java Servlets

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. Chapter 2 Java Servlets

  2. Objectives • Introduce concepts of Java Servlet Web components • Support Environments for Java Servlets • Compare Servlet with CGI and Java Applets • Discuss the functionality of Java Servlets • Discuss the Java Servlet API • Discuss the Java Servlet Debugging • Provide step-by-step tutorials on building, deploying, and using Java Servlet components

  3. 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. • Applications include embedded system, wireless communication, and any other generic request/response application. • Java Web HTTP Servlets take HTTP requests, process them, and respond to the client with process results via HTTP protocol.

  4. CGI and Java Servlet

  5. Java Servlets (cont.) • Java Servlets are written in Java and run on the Java Runtime Environment (JRE). CGI is written in Perl or other scripting language. Java Servlets have many advantages: • Efficiency: reduction of the time on 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 and others

  6. Java Servlets (cont.) • The Java Servlet resembles a Java Applet. A Java Applet is an enhancement to a Web client and a Java Servlet is an addition to the Web server’s functionality. • A Java applet is embedded into an HTTP page and is downloaded with the page from the Web server where the HTTP page resides. It is run by the client browser at the client site. • A Java Servlet object is created on the Web servers and runs on the server. An applet is called Java client-side program and a Servlet is called a Java server-side program.

  7. Java Servlets (cont.) • A Servlet object is supported by a Servlet container, which is supported by an HTTP Web server. • The Servlet container is responsible of managing the life cycle of a Servlet object. Functions of the Servlet container include taking input requests from clients; instantiating an instance of the Servlet class; passing the requests to the Servlet object and letting the Servlet object process the requests; forwarding the results to clients. • The results returned to the client by a Servlet Web component may be in a format of TEXT/HTML, TEXT/XML, TEXT/PLAIN, IMAGE/JPEG, or in other binary types of formats.

  8. Java Servlets (cont.) Java Applet and Java Servlet

  9. Java Servlets (cont.) • 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). In this case the Servlet plays a role of the middle tier in a 3-tier architecture. • A Servlet is deployed as a middle tier just like other Web component such as JSP components. The Servlet Web components are always parts of the Web application. • For example, in J2EE, Servlet Web components and Java Server Pages (JSP) Web components can be deployed in a .WAR file; EJB components can be deployed in a .JAR file

  10. Java Servlets (cont.) • All together, An Enterprise application can be deployed in an .EAR file, which consists of .JAR files and .WAR files. • 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.

  11. Support Environments for Java Servlets • A Java Servlet application is supported by its Servlet container. The container may be an add-on Servlet container or standalone container, which comes as a part of a Web server. • Since a Java Servlet itself is a Java class. It needs Java API support, specifically the Java Servlet API that is available in an archive file called servlet-api.jar in Tomcat.

  12. Support Environments for Java Servlets (cont.) • The Apache Tomcat web server is the official reference implementation of Servlet containers, supporting Servlets and JSP. • Tomcat itself can be a standalone Web server and can also be an add-on Servlet/JSP engine/container for other web servers. • Tomcat 5.x is the newest edition at the time of this writing, which supports Servlet 2.4 and JSP 2.0.

  13. Support Environments for Java Servlets (cont.) • The Tomcat Web server is an open source Servlet container originally developed by Sun Microsystems. • There are many other Web servers supporting Servlets and JSP, such as Sun’s Java Web server, and Macromedia s JRun, Caucho Resin, and Jetty. • Many application servers, like Sub Java System Application Server, BEA WebLogic and IBM WebSphere, Oracle Application Server, Pramati Server, JBoss also support Servlets and JSP.

  14. Web Server Configuration (server.xml) • 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. • Some common changes needed in the configuration of Tomcat Web server may be: • 1. Reset the server port number where the Servlet class or other Web component will listen for requests. • <Connector port=”80” … /> • where 8080 is the initial port number. It is replaced by 80 to make it much more convenient for clients to access Servlets since 80 is the default HTTP port.

  15. Web Server Configuration (server.xml) (cont.) • 2. Turn on the Servlet reloading so that you don’t need to reload the recompiled Servlet. • <DefaultContext reloadable=”true”/> is inserted in the Service tag. • A sample of server.xml. • . . . • <Server port="8005" shutdown="SHUTDOWN" debug="0"> • . . . • <Service name="Catalina"> •   <Connector port="80" maxThreads="150" minSpareThreads="25" • maxSpareThreads="75" enableLookups="false" redirectPort="8443" • acceptCount="100" debug="0" connectionTimeout="20000" • disableUploadTimeout="true" /> • <Engine name="Catalina" defaultHost="localhost" debug="0"> • <Host name="localhost" debug="0" appBase="webapps" unpackWARs="true" • autoDeploy="true"> • . . . •   <DefaultContext reloadable="true" /> •   <Context path="" docBase="ROOT" debug="0" /> •   </Host> •   </Engine> • </Service> • </Server>

  16. Java Servlet Deployment Descriptor (web.xml) • An XML format file called web.xml in WEB-INF subdirectory of your Web application directory is used to control and configure the behavior and setting of Java Servlets in your specific Web application. There is another server-wide web.xml in the same place as server.xml. • The server-wide configurations will apply to all Web components on the server. As each application is deployed, this file is processed first, followed by the "/WEB-INF/web.xml" deployment descriptor from your own applications. The application specific resource configurations should go in the "/WEB-INF/web.xml" in your application. • A sample Web server-wide web.xml for Tomcat 5.

  17. Java Servlet Deployment Descriptor (web.xml) (cont.) web.xml example “myPackage” <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <display-name>Welcome to Tomcat</display-name> <description>Welcome to Tomcat</description> <servlet> <servlet-name>myServlet</servlet-name> <servlet-class>myPackage.myServlet</servlet-class> >

  18. Java Servlet Deployment Descriptor (web.xml) (cont.) <init-param> <param-name>key1</param-name> <param-value>value1</param-value> </init-param> <init-param> <param-name>key2</param-name> <param-value>value2</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/GetMyServlet</url-pattern> </servlet-mapping> </web-app

  19. Basics of Java Servlets • The Java Servlet is a server-side Web component which takes a HTTP request from a client, handles it, talks to a database, talks to a JavaBean component, and responds a HTTP response or dispatch the request to other Servlets or JSP components. • Servlets can dynamically produce text-based HTML markup contents and binary contents as well based on the client’s request. Since a Servlet is a Web component it needs be deployed in a Servlet supporting web server with its deployment descriptor.

  20. Java Servlet architecture • A Java Servlet is just a typical Java class which extends an abstract class HttpServlet. • The HttpServlet class extends another abstract class GenericServlet . The GenericServlet class implements three interfaces: javax.servlet.Servlet, javax.servlet.ServletConfig, and java.io.Serializable.

  21. 1. public interface Servlet • The Servlet interface provides Servlet lifecycle method and Servlet configuration information access methods. The lifecycle methods are called in this sequence: • The Servlet is loaded, then initialized with the init() method; The calls from clients to the service method are handled; • The Servlet is taken out of service, then destroyed with the destroy method, then garbage collected. It also provides the getServletConfig() method, which the Servlet can use to get any startup information, and the getServletInfo() method to get basic information , such as the Servlet version. The following list shows the often used methods in this interface:

  22. 1. public interface Servlet (cont.) • public void init(ServletConfig config) throws ServletException • //Called by the servlet container when the servlet is loaded. • public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException • //Called by the servlet container to let servlet respond to a request. • public void destroy() • //Called by the servlet container when the servlet is unloaded • public ServletConfig getServletConfig() • //Returns a Servlet object with initialization and startup parameters of this servlet. • //The init() method can use this object to get the servlet configuration information.

  23. 1. public interface Servlet (cont.) • 2. public interface ServletConfig • The ServletConfig interface provides many methods for the Servlet to get Servlet configuration initialization information which is set in web.xml. • The following list shows the often-used methods in this interface: public String getInitParameter(String name) //Returns the value of the named initialization parameter defined in web.xml, or null if the name does not exist. public ServletContextgetServletContext() //Returns a reference to the ServletContext in the Web application scope • The ServletContext interface keeps one context per Web application. It has following methods: public Enumeration getInitParameterNames() //Returns the names of the context's initialization parameters in Enumeration of String objects,

  24. 1. public interface Servlet (cont.) • public String getInitParameter(String name) • //Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist. • public Enumeration getInitParameterNames() • //Returns the names of the context's initialization parameters as an Enumeration of String • public Enumeration getAttributeNames() • //Returns an Enumeration containing the attribute names available within this servlet context.

  25. public Object getAttribute(String name) • //Returns the servlet container attribute with the given name, or //null. • public void setAttribute(String name, Object object) • //Binds an object to a given attribute name in this servlet context. • public void removeAttribute(java.lang.String name) • //Removes the attribute with the given name from the servlet //context.

  26. 1. public interface Servlet (cont.) • 3. public abstract class GenericServlet extends Object implements Servlet, ServletConfig, java.io.Serializable • In addition to the methods derived from all the interfaces it implements this class also adds a few methods such as: • public void init() throws ServletException //A convenience method which can be overridden so that there's no need to call super.init(config).

  27. 1. public interface Servlet (cont.) • 4. public abstract class HttpServlet extends GenericServlet implements java.io.Serializable • The HttpServlet Provides an abstract class to be subclassed to create an HTTP Servlet object. • A subclass of HttpServlet must override at least one method, usually one of these: doGet() for HTTP GET requests and doPost() for HTTP POST requests. • The Serializable interface provides the mechanism to implement Servlet session tracking, such as Servlet cookies. Not all methods are listed in the figure. All Web application Servlets must be subclasses of HttpServlet class.

  28. 1. public interface Servlet (cont.) Java Servlet Class Hierarchy

  29. 1. public interface Servlet (cont.) • The doGet() and doPost() methods are two widely used methods provided by the HttpServlet class. There are two basic HTTP request types in HTTP protocol: GET or POST. • The GET request is commonly used to retrieve data or images from a Web server and the POST request is commonly used to send form data to the Web server. GET and POST methods can be used alternatively in some cases such as submitting a HTTP form.

  30. 1. public interface Servlet (cont.) • Although GET is basically used for reading it can also include some short data along with the request. • The GET type request is the default type. It can also be made by clicking on a hyperlink that points to the Servlet. The SET type request is also URL book mark able if it is used as part of URL. It is better to use POST method if you don’t want anybody see the contents of your request or the contents of the request are very large.

  31. 1. public interface Servlet (cont.) • An example of a HTTP form which makes a request to an HTTP Servlet. . <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Processing post requests with data</title> </head> <body> <form action = " /conv/conversion" method = "post"> <p><label> Convert from Feet to Meters. Enter the feet value in the field. <br /><input type = "text" name = "feet" /> <input type = "submit" value = "Submit" /> </p></label> </form> </body> </html>

  32. 1. public interface Servlet (cont.) • You can see the POST method type is specified in this form request to a Servlet named conversion as the action attribute of the form tag. The Servlet class name is not necessarily the same as this name since the deployment descriptor may map a virtual name to the actual Servlet class name. • The HTTP form which invokes the Servlet conversion is shown here. “conv” is this Web application’s ROOT directory.

  33. 1. public interface Servlet (cont.)

  34. Servlet Life Cycle • A Servlet has a life cycle just like a Java applet. The life cycle 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().

  35. Servlet Life Cycle (cont.)

  36. Servlet Life Cycle (cont.) • The init() method is called only once. The Servlet object can be instantiated either by the web.xml Servlet configuration file ( <load-on-startup/> in its servlet tag in the web.xml file), or by its first request access. • The init() method is called by the Servlet container right after the Servlet object is loaded. Some routine processes such as database connection can be specified in the init() method so that the connection time can be reduced significantly. Otherwise, these functions must be performed for each HTTP Servlet request, which may require substantial time.

  37. Servlet Life Cycle (cont.) • All subsequent requests are handled by service() method. If an application Servlet is a generic Servlet instead of HTTP Servlet the service() method must be specified. The service() method is called by the Servlet container once per request. • If the request to the Servlet is an HTTP request then the service() method will forward the request to either doPost() method or doGet() method respectively according to the HTTP request types. Here are the prototypes of these two methods.

  38. Processing of HTTP Requests and Responses (cont.) • The prototypes of these two methods. void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException; void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException; • First, let’s take a look at the two parameters of doGet() and doPost().

  39. a. public abstract interface HttpServletRequest extends ServletRequest • This interface has many methods. The important ones of them are shown here: • public Cookie[] getCookies() • //Returns an array containing the entire Cookie //objects the browser sent with this request. This //method will be discussed again in the Cookie //section

  40. public String getQueryString() //Returns the query string that is contained in the //HTTP request URL after the path. • public HttpSessiongetSession(boolean create) //Returns the current HttpSession of this request //or, if necessary, creates a new session for the //request. Use true to create a new session, or use //false to return the current //HttpSession.

  41. (cont.) • public String getRequestedSessionId() • //Returns the session ID specified by the client. • The following methods are inherited from ServletRequest interface: • public void setAttribute(java.lang.String key,java.lang.Object o) • //Stores an attribute in the context of this request. //Attributes are reset when the request is switched. • public Object getAttribute(String name) • //Returns the value of the named attribute as an Object. • public String getParameter(String name) • //Returns the value of a request parameter or null if the //parameter does not exist.

  42. (cont.) • public abstract void sendError(int sc) throws IOException • //Sends an error response to the client using the //specified status code and a default message. • public abstract void sendRedirect(String location) throws IOException • //Sends a redirect response to the client using the //specified redirect location URL. The location may //point to a static or dynamic resource.

  43. b. public abstract interface HttpServletResponse extends ServletResponse • The following methods are inherited from ServletResponse interface. • public ServletOutputStreamgetOutputStream()throws java.io.IOException //Returns a ServletOutputStream for writing binary //data in the response. The servlet container does not //encode the binary data. • public PrintWriter getWriter()throws java.io.IOException • //Returns a PrintWriter object that can send character //text to the client.

  44. (cont.) • 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.

  45. The method String getParameter(String name) returns the value of a parameter as a part of GET or POST type requests. In the Servlet Conversion,request.getParameter(“feet”) returns the value that the client input in the feet text field of the HTML form. The types of the component parameters can be a radio button, check box, combo box, etc. • The method HttpSession getsession(Boolean create) returns an HttpSession object which can be shared by all Web components within client’s current session. There are many other methods such as getParameters() which returns all parameter names, getCookies() which returns Cookie objects used to identify the client of the Servlet.

  46. (cont.) • The HttpServletResponse interface comes with some useful methods. • The setContextType(String type) method is used to tell the client browser the MIME type of the response. It can be “text/html”, “text/xml”, or others. • The PrintWriter getWriter() method is widely used to return a text output stream for sending text data to clients. The ServletOutputStream getOutputStream() method is used to return a byte output stream for sending binary data such as music or image to clients. There are also some other methods such as addcookie(Cookie cookie).

  47. Servlet example • A simple Servlet which takes a input of feet units from a HTML page and converts it to meter units in the metric system. • import java.util.*;import java.text.*;import javax.servlet.*;import javax.servlet.http.*;import java.io.*;

  48. public class Conversion extends HttpServlet { // process "post" request from client protected void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { String feet = request.getParameter( "feet" ); Double feetNum = Double.valueOf(feet); Double meters = 0.3048; Double metersHeight = feetNum*meters; response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); DecimalFormat decimalFormatter = new DecimalFormat("0.000"); String mtrs = decimalFormatter.format(metersHeight);

  49. // send HTML document to client out.println( "<html>" ); // head section of document out.println( "<head>" ); out.println( "<title>Processing get requests with data</title>" ); out.println( "</head>" ); // body section of document out.println( "<body>" ); out.println( "<h1>"+feet+" ft = " + mtrs + " meters<br />" ); out.println( "Thanks!</h1>" ); out.println( "</body>" ); // end HTML document out.println( "</html>" ); out.close(); // close stream to complete the page } }

  50. Let’s take a look how the Servlet dynamically produces HTML content. The response object’s method • setContentType() specifies the type of content as text/html format rather than some other format such as image/gif etc. The response object’s method getWriter() gets a reference out pointing to a PrintWriter object to let the Servlet send HTML contents to the client. The rest of the out.println() statements just appends the HTML contents to the outgoing page one line per statement. • Here is the output HTTP page dynamically generated by this Servlet. You can see that the header title specified in the head tag on the top of the page and the output result in the body section is displayed in the side of “h1”

More Related