Internet Technologies 6 - Servlets I F. Ricci 2010/2011
Content Basic Servlets Tomcat Servlets lifecycle Servlets and forms Reading parameters Filtering text from HTML-specific characters Reading headers Sending compressed content Differentiating among browsers Referer Most of the slides were made available by www. coreservlets.com
Servlet Roles Read the explicit data sent by the client Read the implicit HTTP request data sent by the browser Generate the results Send the explicit data (i.e., the document) to the client Send the implicit HTTP response data
HelloWorld import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Very simplistic servlet that generates plain text. * <P> * Taken from More Servlets and JavaServer Pages * from Prentice Hall and Sun Microsystems Press, * http://www.moreservlets.com/. * © 2002 Marty Hall; may be freely used or adapted. */ public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); } code }
Servlet Architecture HTTP Response HTTP Servlet Container Request Java Virtual Machine (JVM) Servlet 1 Servlet 2 Client Web Web Server Servlet n
Installing and Running Tomcat Tomcat is distributed as a ZIP archive http:// tomcat.apache.org unzip the download file, for instance into a root- level directory: C:\apache-tomcat-6.0.16 To run Tomcat you'll need to tell it where to find your J2SE SDK installation Set the JAVA_HOME environment variable to C:\Program Files\Java\jdk1.6.0_04 To run Tomcat : open a command window change directory to Tomcat's bin directory Type startup
Tomcat Directory Structure Tomcat binaries: startup, shutdown All jar libraries: e.g. servlet-api.jar Configuration files: e.g. when you build your application in Netbeans a new file is added to indicate where is deployed (e.g., C:\apache- tomcat-6.0.16\conf \Catalina\localhost \coresjsp.xml) Directories of the web applications deployed here, possibly generated by .war files deployed here (with a web.xml file)
Catalina Base Go to netbeans: tools>servers to look at these details
web.xml <?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> <servlet> <servlet-name>bob</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>bob</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> </web-app>
Compiling and deploying Create a directory in \webapps called hello Create a directory in \webapps\hello called WEB-INF and then a subdirectory classes where to put the sources and the compiled files Set the classpath C:\>set CLASSPATH=\apache-tomcat-6.0.16\common \lib\servlet-api.jar Compile C:\>javac HelloWorld.java Deploy the web.xml file in C:\apache- tomcat-6.0.16\webapps\hello\WEB-INF Or use an IDE (Netbeans) – separating sources ( web directory) and deployment ( build directory).
Starting Tomcat /bin/startup.bat or startup.sh Point Browers to http://localhost:8080 should see default page All the Docs are there on the default page! Check out the examples pages, good tutorials
Basic Servlet Structure Here's the outline of a basic servlet that handles GET and POST requests in the same way: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); // Use "out" to send content to browser } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
HelloWorld HTML import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>Hello (2)</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>Hello</H1>\n" + "</BODY></HTML>"); } code }
Some Simple HTML-Building Utilities public class ServletUtilities { public static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">"; public static String headWithTitle(String title) { return(DOCTYPE + "\n" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n"); } ... code } Don’t go overboard Complete HTML generation packages usually work poorly The JSP framework is a better solution
HelloServlet3: Packages and Utilities package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloServlet3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Hello (3)"; out.println(ServletUtilities.headWithTitle(title)+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1>" + title + "</H1>\n" + "</BODY></HTML>"); code } }
The Servlet Life Cycle ( Servlet Interface) init Executed once when the servlet is first loaded Not called for each request service Called in a new thread by server for each request Dispatches to doGet, doPost, etc. Do not override this method! doGet, doPost, doXxx Handles GET, POST, etc. requests Override these to provide desired behavior destroy Called when server deletes servlet instance Not called after each request. javadoc
Example of usage of init If a servlet get a request for a url with the http header if-Modified-Since: Mon, 12 Nov 2010 18:00:00 GMT It can check if something has really changed the output after that date – if not the servlet sends back a reply: HTTP/1.1 304 Not Modified And the browser shows the cashed url The servlet must only implement the following method to know when it has been modified the last time: public long getLastModified(HttpServletRequest request) The app server will call it when a client requests the servlet And will send back a result only if the page was modified (according to the value returned by the method) after Mon, 12 Nov 2010 18:00:00 GMT
Code The init method set the time the page was modified public void init() throws ServletException { // Round to nearest second (i.e, 1000 milliseconds) modTime = System.currentTimeMillis()/1000*1000; for(int i=0; i<numbers.length; i++) { numbers[i] = randomNum(); } } An then overwrite the method that tells when the page was modified public long getLastModified(HttpServletRequest request) { return(modTime); } LotteryNumbers code
Calls to the servlet The page was not modified The page was modified after after 9:00:00 GMT 8:00:00 GMT
Calls to the servlet You can do the same experiments with a telnet connection (e.g., using putty)
HTML Form <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD> <BODY> <H2 ALIGN="CENTER">A Sample Form Using GET</H2> <FORM ACTION="http://localhost:8080/coresjp/ServletForm"> <CENTER> First name: <INPUT TYPE="TEXT" NAME="FirstName" VALUE=""><BR/> Last name: <INPUT TYPE="TEXT" NAME="LastName" VALUE=""><P> <INPUT TYPE="SUBMIT"> </CENTER> </FORM> </BODY> </HTML> form
Reading form data in servlets request.getParameter(“FirstName") Returns URL-decoded value of first occurrence of FirstName parameter in query string Works identically for GET and POST requests Returns null if no such parameter is in query data request.getParameterValues(“FirstName") Returns an array of the URL-decoded values of all occurrences of FirstName parameter in query string Returns a one-element array if param is not repeated Returns null if no such parameter is in the query request.getParameterNames() or request.getParameterMap() Returns Enumeration or Map of request parameters Usually reserved for debugging.
Recommend
More recommend