Java Servlets: A QuickStart for CS Educators Dawn Wilkins and Kathy Gates The University of Mississippi Workshop Description This workshop is designed to give CS educators, who have a working knowledge of Java, a good introduction to Java servlets. The servlet architecture and life cycle will be explained, and examples will be provided to demonstrate the use of the Java Servlet API. Advanced features including accessing databases through a servlet and session tracking will be covered. Setting up Java servlet development environment for students will also be addressed. Contents Background Java Servlet Basics A Comparison of Servlets & CGI The Servlet Architecture A Few Example Servlets IDE’s & Server Options Servlet Basics: A Closer Look Servlets & JDBC Session Tracking Java Server Pages Practical Applications Resources Software Demonstration Setup Windows NT Internet Explorer Borland Jbuilder Apache with Tomcat Mysql Database – www.mysql.com PHP & phpMyAdmin A Historical Perspective First efforts at dynamic Web content – Common Gateway Interface (CGI) – Fast CGI Proprietary Solutions – Microsoft’s Active Server Pages – Netscape’s Javascript CGI: What is it? Common Gateway Interface (CGI) programs can be written in many languages, including Java. Perl is the most common language for CGI's, due to its advanced text processing capabilities. A standard interface between a Web server and an application. One of the first practical ways for generating dynamic content. Runs as a separate process from the Web server. Interaction with CGIs (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 8) An Example CGI Program Hello World – See demonstration. Common Gateway Interface Advantages – Easy to get started – Simple programming interface – Popular scripting languages such as Perl offer powerful way to quickly develop new applications – Widely used Disadvantages – New process is started for each CGI call – Separate process means limited interaction with Web server and possible loss of communication – May hit operating system limits on number of processes Java Servlet Basics First there was the applet -- high hopes, but probably did not reach expected potential. – Slow to load – Not operable on all browsers – Security issues So, what is a servlet? – Java embedded in a Web server to extend the Web server's capabilities. – Whereas applets run in the Web browser, servlets run in the Web server. Terms to Note: – Container vs. Engine – Filtering vs. Chaining – Contexts vs. Zones Interaction with Servlets (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 6) Advantages of Servlets Efficient – Servlets are loaded once instead of each time they are executed. – The servlet is first loaded via the init() method and can perform potentially costly start-up functions once. Adds Persistence to a Stateless Web – The servlet's thread doesn't have to terminate once it sends back a response. Platform Independent – Servlets port easily to other systems with JVM. More Advantages Built-in Support for Many Server Features – The developer can be free of certain server details. Extensible – Object-oriented approach facilitates new development. Function as Direct Extensions of the Web Server – Supports interaction with the server itself Gaining Wide-Spread Acceptance Disadvantages of Servlets Servlets can be more complicated to set up. Servlets must be recompiled whenever a change is made. On their own, servlets do not provide a way to embed code into HTML documents such as with ColdFusion or PHP; however, this is addressed with JSP. Guidelines for Choosing When should you use Servlets instead of CGI? Nature of the Application – What is the hardware/software platform? – How long-term is it? – How much development time is available? – Who will maintain the application? – What other information systems does it interface with? – How many hits do you anticipate? A Review of HTTP Hypertext Transfer Protocol (HTTP) Simple & Stateless The client makes a request and the Web server responds. The client request includes: – an HTTP command or “method” that tells what action to perform – a URL – the version of the HTTP protocol it is using. HTTP Responses The server processes the request and sends back a response. The first line of the response specifies: – the version of the HTTP protocol the server is using, – a status code, and – a description of the status code. For example, 200 means successful. The server also sends the client info telling what kind of software it is running and the content of the response. HTTP Methods The two most popular HTTP methods are GET & POST. GET is generally used by a client to request a resource from the server. POST is normally used to pass user input to the server. The GenericServlet Request (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 13) Generic Servlet API Methods The interface javax.servlet.Servlet provides the framework for all servlets through five methods. getServletConfig() – Returns startup configuration and initialization parameters. * service() – Receives two objects: ServletRequest and ServletResponse getServletInfo() – Provides the servlet user with information about the servlet itself. * init() – Servlet is constructed and initialized. * destroy() – Signifies the end of the servlet’s life. * Life cycle methods Servlet Requests & Responses The service() method accepts two parameters: ServletRequest ServletResponse. ServletRequest allows access to names of parameters passed by the client, the protocol, etc. ServletResponse allows the servlet to set the content length & MIME type of the reply and provides a means by which the servlet can send the reply data. Generic vs. HTTP Servlets The HttpServlet Class is extended from GenericServlet. Generic servlets should override the service() method; however, service() is already implemented in HttpServlet. HttpServlets override doGet() to handle GET requests and doPost() to handle POST requests. Other HttpServlet methods are also available. The HttpServlet Request (From Developing Java Servlets: The Authoritative Solution by James Goodwill, p. 14) An Example Servlet Hello World – See demonstration. Skeleton Servlet public class skeletonServlet extends HttpServlet { // declaration of instance variables public void init (ServletConfig config) throws ServletException { super.init (config); // initialize resources here } Skeleton Servlet, part 2 public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... } public void doPost (HttpServletRequest request, HttpServletResponse response) {…} Skeleton Servlet, part 3 public String getServletInfo () { return “The purpose of this servlet is …” } public void destroy () { { // free resources here } } // skeletonServlet Servlets & HTML Creating HTML Documents – setContentType() – getWriter() Retrieving Form Data – getParameterNames() – getParameter() – getParameterValues() Invoking the Servlet More Servlet Examples Vacation Example – See demonstration. Quiz #1 – See demonstration. Java IDE’s & Servlets IDE – Integrated Development Environment Examples – Borland Jbuilder – IBM Visualage Servlet Aids – Automatic Code Generation – Test Environment Servlet-Enabled Web Servers Apache with Tomcat iPlanet IBM Websphere Other See http://java.sun.com/products/servlet/industry.html for a more comprehensive list. The Servlet Specification Created from a Sunsponsored open process to develop and revise JavaTM technology specifications Newest servlet specification includes: – Concept of a Web Application (Servlets, JSP, HTML, Classes, other resources) with conventions for the directory structure – Web Application Archive (WAR) files – Filtering Allows on-the-fly transformations of HTTP content (request or response); for example, to transform XML content – Other http://java.sun.com/aboutJava/communityprocess/first/jsr053/index.html Servlet Basics: A Closer Look The ServletRequest Interface – Defines an object used to encapsulate information about the client’s request. – Includes information about parameter name/value pairs. The ServletResponse Interface – Defines an object for sending MIME data back to the client from the servlet’s service() method. HttpServletRequest Interface A Few Methods – – – – – – – getAuthType() getCookies() getDateHeader() getHeader() getHeaderNames() getIntHeader() getMethod() – – – – – – – – getPathInfo() getPathTranslated() getQueryString() getRemoteUser() getRequestedSessionId() getRequestedURI() getServletPath() getSession() HttpServletResponse Interface Static Final Variables – For example, SC_OK represents a status code of 200, and SC_NOT_FOUND represents a status code of 404. A Few Methods – – – – – – – addCookie() encodeURL() sendError() sendRedirect() setDateHeader() setHeader() setStatus() Servlet Tips Place costly functions in init(). Let doGet() call doPost() or vice versa: public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } Be careful with multiple threads; SingleThreadModel may be necessary. JDBC Java Database Connectivity Relational Databases SQL Refresher – – – – – CREATE INSERT UPDATE DELETE SELECT JDBC Features A Java API for: – Opening a connection to a database – Executing a SQL statement – Processing the results – Closing the connection to the database Easy Object to Relational Mapping Database Independence Distributed Computing Basic JDBC Methods Establishing a connection with getConnection() Creating SQL Statements – CreateStatement() executeQuery() executeUpdate() execute() Getting the results with ResultSet SQLExceptions A Simple Servlet with JDBC HowFar – See demonstration. Session Tracking HTTP is stateless, so no inherent way to determine that a series of requests all come from the same client. Think about a shopping cart application example. Possible Solutions Traditional CGI Techniques – – – – User-authorization Hidden form fields URL rewriting Persistent cookies Servlet API Built-in Support Session-tracking API support Uses persistent cookies where possible and reverts to URL rewriting when cookies do not work. Each user is associated with a javax.servlet.http.HttpSession object. Information about the user can be stored in the session object, e.g. shopping cart contents or database connection. Session Tracking Example Quiz #2 – See demonstration. Java Server Pages Supports embedded scripting and tags. These co-exist with HTML. Provide a means for separating content and presentation. Reuse and code sharing are enhanced when JSP is used with JavaBeans. Steps of a JSP Request – Client requests a JSP page. – The JSP engine compiles the JSP into a servlet. – The generated servlet is compiled and loaded. – The compiled services the request and sends a response back to the client. from Pure JSP by Goodwill JSP Directives Page – A global definition that is sent to the JSP engine – Used to embed small code blocks. Ex: <%@ page errorPage=“/error.jsp” %> <% scriptlet %> Include – Allows the substitution of text or code Declarations Comments – Two forms: <!-- comments …--> <%-- comments … --%> Ex: <%@ include file=“copyright.html” %> Scriptlets Expressions – Contains Java variables and methods called from an expression block. – Scriptlet fragments whose results can be converted to String objects. Syntax: <%! Declaration(s) %> <%= expression %> HowFar as a JSP file HowFar.jsp – See demonstration. JSP and JavaBeans Supports the creation of dynamic content JavaBeans – Reusable software components that can be manipulated visually in a builder tool – Minimum Requirements: Supports JDK 1.1 and later Serialization Model Uses Get/Set accessors to expose its properties Tags – jsp:useBean Declares the JavaBean object that you want to use within the JSP – jsp:getProperty Inserts the String type of the object into the output stream – jsp:setProperty Sets properties of the Bean HowFar2 as a JSP file with a JavaBean HowFar2.jsp – See demonstration. Practical Applications Useful for serving as the “glue” to connect heterogeneous information systems that require a web interface. XML makes this scenario even more attractive. University of Mississippi IT Applications – E-forms Requires data from Cold Fusion/SQL Server and SAP via Java Connector – Web-to-SAP Business Connector Java Connector Servlet Resources See accompanying handouts. For More Information Dawn Wilkins Kathy Gates Department of Computer Science University of Mississippi (662) 915-7309 dwilkins@cs.olemiss.edu Office of Information Technology University of Mississippi (662) 915-7206 kfg@olemiss.edu