Title: Servlets: Building Your First Servlet
1ServletsBuilding Your First Servlet
- Sana Odeh
- New York University
2Road Map
- Generic Template for Creating Servlets
- Servlet 2.3/2.4 API
- Hello World Examples
- Outputting Text, HTML, and the current time.
- Compiling your own Servlets
- Tips for installing/compiling servlets on Apache
Tomcat - Live demo of Tomcat/JCreator running locally.
- Packaging Servlets
- HTML Utilities
3- Servlets
- Thin clients
- Request/response mechanism
- redirection
- Tomcat
- Jakarta project
- Official reference implementation of the JSP and
servlet standards
4Servlet Overview and Architecture
- Servlet container (servlet engine)
- Server that executes a servlet
- Web servers and application servers
- Sun ONE Application Server
- Microsofts Internet Information Server (IIS)
- Apache HTTP Server
- BEAs WebLogic Application Server
- IBMs WebSphere Application Server
- World Wide Web Consortiums Jigsaw Web Server
5Generic Servlet Template
6Servlet Template
- First, lets 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.
7import 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
8Generic 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.
9Generic 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//java.sun.com/products/servlet/2.3/javadoc/i
ndex.html - Once you have extended HTTPServlet, you must
override one or both - doGet() to capture HTTP Get Requests
- doPost() to capture HTTP Post Requests
10doGet 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 encapsulates 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.
11Getting 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()
12Hello World!
13Hello World!
- We are finally ready to see our first real
servlet. - This servlet outputs Hello World! as plain
text, not HTML. - Lets take a look at the code, and then see the
servlet in action. - BTW, all examples used here can be downloaded
from CoreServlet website - http//volume1.coreservlets.com/archive/Chapter2.h
tml
14import 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")
15Output 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.
16Generating 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.
17HelloWWW.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") PrintWrite
r out response.getWriter() out.println("ltHTMLgt
\n" "ltHEADgtltTITLEgtHello
WWWlt/TITLEgtlt/HEADgt\n"
"ltBODYgt\n" "ltH1gtHello
WWWlt/H1gt\n" "lt/BODYgtlt/HTMLgt")
18Generating 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.
19Time Servlet
- Lets try one more simple servlet
- Using the java.util.Date object, you can obtain
the current time.
20import java.io. import java.util. import
javax.servlet. import javax.servlet.http. pub
lic 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("ltHTMLgt\n"
"ltHEADgtltTITLEgtHello
WWWlt/TITLEgtlt/HEADgt\n"
"ltBODYgt\n" "ltH1gtHello
WWWlt/H1gt\n" "ltH2gtTime is now
"now"lt/H2gt" "lt/BODYgtlt/HTMLgt")
21Installing / Compiling Servlets
22Basic Setup
- It is recommended that you do all development on
a local computer. - This enables you to have complete control over
all your servlets and JSPs. - If you do not have access to your own computer,
you can also do all your development on a UNIX
account (email me for account information.) - The next few slides provide an overview of local
installation. Complete details are available in
Chapter 2 of our text and todays (virtual)
handout. - http//www.cs.nyu.edu/courses/spring05/V22.0480-00
1/jsp_serv_software.html
23Local Installation - Overview
- Download and install the Java Software
Development Kit (SDK). - Download Apache Tomcat Servlet Engine.
- Configure Apache Tomcat.
- Set up your development environment, including
CLASSPATH. - Test your setup.
- Establish a simplified deployment method.
24Step 1 Download Java SDK
- Complete details and URLs are available in
handout. - It is best to download Java SDK 1.4.2_07
- Make sure you download full SDK and (NOT only THE
JRE files) - JRE Runtime Environment will allow you to run
.class files. - You need to be able to run application, so you
need SDK Software Development Kit (SDK) to create
applications - Once you have installed the SDK, verify that it
works (see handout.)
25Step 2 Download a Server
- A number of Servlet engines are available for
download - Apache Tomcat Open Source Servlet Engine.
- Macromedia JRun
- Caucho Resin
- New Atlanta ServletExec
- Jetty
- Recommended Apache Tomcat
26Step 3 Configure Tomcat
- Again, complete details are in the virtual
handout. - Important Details
- Specify a server port 8080 or 80.
- Enable Servlet Reloading When activated, Tomcat
will automatically reload modified class files.
Otherwise, you have to continually stop/start the
server (very annoying) - Enable the ROOT context good place to put all
your class projects. - Turn on the Servlet Invoker makes it easier to
deploy new servlets with minimal configuration.
27Step 4 Dev. Environment
- Once you have confirmed that your servlet engine
is running, you need to set-up your development
environment. - Set up your CLASSPATH
- You must modify your CLASSPATH to include
servlet.jar.
28Step 5 Test your Setup
- Handout includes three tests to verify that your
set-up is working correctly - Create a servlet that does not use packages.
- Create a servlet that does use packages.
- Create a servlet that does use packages and a
separate utility class.
29Step 6 Simplify Development
- Handout includes several options.
- Recommended, but not required the best option
is to use a Java IDE to do servlet development. - A number of Java IDEs are available.
- If you are already familiar to one, feel free to
use it. - Otherwise, try out JCreator http//www.jcreator.
com/ (Freeware)
30Tips on Using JCreator
- Course web site includes tutorials on using
JCreator. - To use JCreator for servlet development
- Make sure that servlet.jar is in your CLASSPATH.
- Output class files to your tomcat directory
webapps/ROOT/WEB-INF/classes
31Live Demo
- On my laptop, I have
- Java 1.4
- Apache Tomcat
- JCreator
- Lets see how it all works
32Packaging Servlets
33What 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.
34Creating 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 named
coreservlets. - You therefore need to create a coreservlets
directory and place your code here.
35Creating Packages
- Insert a package statement in the first line of
your class file - For example package coreservlets
- Compile your Java code like this
- type javac coreservlets/HelloWWW2.java
36package coreservlets import java.io. import
javax.servlet. import javax.servlet.http. pub
lic class HelloWWW2 extends HttpServlet
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html")
PrintWriter out response.getWriter()
out.println("ltHTMLgt\n"
"ltHEADgtltTITLEgtHello WWWlt/TITLEgtlt/HEADgt\n"
"ltBODYgt\n" "ltH1gtHello
WWWlt/H1gt\n" "ltH2gtThis is a
servlet within a package.lt/H2gt"
"lt/BODYgtlt/HTMLgt")
37Invoking 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
38HTML Utilities
39Servlet 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. - Lets first examine the ServletUtilities class,
and then examine how to use it.
40ServletUtilities.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 ltTITLEgt tag.
41package coreservlets import javax.servlet. impo
rt javax.servlet.http. / Some simple time
savers. Note that most are static
methods. / public class ServletUtilities
public static final String DOCTYPE
"lt!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
"Transitional//EN\"gt" public static
String headWithTitle(String title)
return(DOCTYPE "\n" "ltHTMLgt\n"
"ltHEADgtltTITLEgt" title
"lt/TITLEgtlt/HEADgt\n") ...
42Using 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
43package coreservlets import java.io. import
javax.servlet. import javax.servlet.http. pub
lic 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") "ltBODYgt\n"
"ltH1gtHello WWWlt/H1gt\n"
"lt/BODYgtlt/HTMLgt")
44Next Steps
- Start Studying the Servlet API
- HttpServlet, HttpServletRequest,
HttpServletResponse are very important. - Study the beginner examples.
- Start working on Tomcat. Get your servlets
running today. - Experiment with packaged servlets.
- Experiment with the Servlet Utilities class.