1 / 35

Servlets: Building Your First Servlet

Servlets: Building Your First Servlet. Ethan Cerami New York University. Road Map. Generic Template for Creating Servlets Servlet 2.2 API Hello World Examples Outputting Text, HTML, and the current time. Compiling your own Servlets Instructions for installing/compiling servlets on I5

arotz
Download Presentation

Servlets: Building Your First Servlet

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. Servlets:Building Your First Servlet Ethan Cerami New York University First Servlet

  2. Road Map • Generic Template for Creating Servlets • Servlet 2.2 API • Hello World Examples • Outputting Text, HTML, and the current time. • Compiling your own Servlets • Instructions for installing/compiling servlets on I5 • Packaging Servlets • HTML Utilities First Servlet

  3. Generic Servlet Template First Servlet

  4. Servlet Template • First, let’s take a look at a generic servlet template. • The code does not actually do anything, but all your future servlets will follow this general structure. • The most important pieces are noted in yellow. First Servlet

  5. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers // (e.g. cookies) and HTML form data (e.g. data the user // entered and submitted). // Use "response" to specify the HTTP response status // code and headers (e.g. the content type, cookies). PrintWriter out = response.getWriter(); // Use "out" to send content to browser } } First Servlet

  6. Generic Template • Import the Servlet API: import javax.servlet.*; import javax.servlet.http.*; • To create servlets, you must remember to always use these two import statements. First Servlet

  7. Generic Template • All your servlets must extend HTTPServlet. • HTTPServlet represents the base class for creating Servlets within the Servlet API. • The Full Servlet API is available at: • http://www.java.sun.com/products/servlet/2.2/javadoc/index.html • Once you have extended HTTPServlet, you must override one or both: • doGet(): to capture HTTP Get Requests • doPost(): to capture HTTP Post Requests First Servlet

  8. doGet and doPost • The doGet() and doPost() methods each take two parameters: • HTTPServletRequest: encapsulates all information regarding the browser request. • Form data, client host name, HTTP request headers. • HTTPServletResponse: encapsulate all information regarding the servlet response. • HTTP Return status, outgoing cookies, HTML response. • If you want the same servlet to handle both GET and POST, you can have doGet call doPost or vice versa. First Servlet

  9. Getting an OutputStream • The HTTPResponse object has a getWriter() method. • This method returns a java.io.PrintWriter object for writing data out to the Web Browser. PrintWriter out = response.getWriter(); First Servlet

  10. Hello World! First Servlet

  11. Hello World! • We are finally ready to see our first real servlet. • This servlet outputs “Hello World!” as plain text, not HTML. • Note: All examples are available on the web site. • Let’s take a look at the code, and then see the servlet in action. First Servlet

  12. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); } } First Servlet

  13. Output Stream • Once you have an OutputStream object, you just call the println() method to output to the browser. • Anything you print will display directly within the web browser. • As we will now see, you can also output any HTML tags. First Servlet

  14. Generating HTML • To generate HTML, you need to add two steps: • Tell the browser that you are sending back HTML. • Modify the println() statements to return valid HTML. First Servlet

  15. HelloWWW.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>"); } } First Servlet

  16. Generating HTML • To return HTML, you must set the content MIME type to text/html: • response.setContentType("text/html"); • Remember that you must set the content type before you output any content. • Once you have set the MIME type, you can return any HTML document you want. First Servlet

  17. Time Servlet • Let’s try one more simple servlet… • Using the java.util.Date object, you can obtain the current time. • Let’s create a simple Servlet that outputs the current time. First Servlet

  18. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class TimeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Date now = new Date(); PrintWriter out = response.getWriter(); out.println("<HTML>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n"+ "<H2>Time is now: "+now+"</H2>"+ "</BODY></HTML>"); } } First Servlet

  19. Installing / Compiling Servlets First Servlet

  20. Basic Setup • I5 now has the Jakarta-Tomcat Servlet Engine installed. • Tomcat is an open source servlet engine. • Supports both Servlets and JSPs. • Maintained by the same group that develops the Apache Web Server. First Servlet

  21. Tomcat Set-up Send request to port 9712 Web Browser Tomcat Servlet Engine Hello World Servlet First Servlet

  22. Getting Started • Let’s take a look at today’s handout…. • Handout is also available online at: • http://ecerami.com/applied_fall_2001/handouts/i5_servlets.php4 • Change to handout: • CLASSPATH="/usr/local/jakarta-tomcat-3.2.3/lib/servlet.jar:." Add :. to Classpath! First Servlet

  23. Packaging Servlets First Servlet

  24. What is a Package? • Package: Group of related classes. • For example: • package coreservlets; • In real web sites, multiple programmers may be creating multiple servlets. • By dividing your code base into packages, it helps to modularize the code. • A very common practice in the real world, and used throughout our textbook. First Servlet

  25. Creating Packages • To create your own package, you need to follow three steps: • Move your .java files to a subdirectory that matches your package name. • For example, the text book uses the package name coreservlets. • You therefore need to create a coreservlets directory within ~/public_html/tomcat/WEB-INF/classes and place your code here. First Servlet

  26. Creating Packages • Insert a package statement in the first line of your class file • For example: package coreservlets; • Compile your Java code like this: type: servlets type: javac coreservlets/HelloWWW2.java First Servlet

  27. package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>\n" + "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" + "<H2>This is a servlet within a package.</H2>"+ "</BODY></HTML>"); } } First Servlet

  28. Invoking a Packaged Servlet • To invoke a packaged servlet, you need to specify the package name and the servlet name: • http://host/servlet/packageName.servletName • For example, to access the HelloWWW2 servlet on ecerami.com: • http://ecerami.com/servlet/coreservlets.HelloWWW2 • To access the servlet on I5: • http://i5.nyu.edu:9712/eqc3844/servlet/coreservlets.HelloWWW2 First Servlet

  29. HTML Utilities First Servlet

  30. Servlet Utilities • Author of our text book has created a class called ServletUtilities. • This class contains some simple HTML utilities that you can use. • As we read further in the book, the author adds more utilities to this class. • Let’s first examine the ServletUtilities class, and then examine how to use it. First Servlet

  31. ServletUtilities.java • For now, let us examine just one method: headWithTitle(). • This method outputs: • HTML DOCTYPE, used to specify which version of HTML we are using. • The title of the page via the HTML <TITLE> tag. First Servlet

  32. package coreservlets; import javax.servlet.*; import javax.servlet.http.*; /** Some simple time savers. Note that most are static methods. */ 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"); } ... } First Servlet

  33. Using Servlet Utilities • To use the Servlet Utilities class, you just need to call the headWithTitle() method: ServletUtilities.headWithTitle("Hello WWW"); • If you are placing your servlet in a different package, you also need to import coreservlets; First Servlet

  34. package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW3 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(ServletUtilities.headWithTitle("Hello WWW") + "<BODY>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>"); } } First Servlet

  35. Compiling • To compile this servlet: • Download ServletUtilities.java and copy to your coreservlets directory. • Download HelloWorldWWW3.java and copy to your coreservlets directory. • Type: • javac coreservlets/HelloWWW3.java • Then, open browser and go to: • http://i5.nyu.edu:9712/[NET-ID]/servlet/coreservlets.HelloWWW3 First Servlet

More Related