© 2010 Marty Hall
S
Servlet
l t Basics
B i
Originals of Slides and Source Code for Examples:
[Link]
Customized Java EE Training: [Link]
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
2 Developed and taught by well-known author and developer. At public venues or onsite at your location.
© 2010 Marty Hall
For live Java EE training, please see training courses
at [Link]
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring, g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP, JSP and this [Link] Available at public
venues,Customized
or customized versions
Java EE Training: can be held on-site at your
[Link]
organization. Contact hall@[Link] for details.
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
• The basic structure of servlets
• A simple servlet that generates plain text
• A servlet that generates HTML
• Servlets and packages
• Some utilities that help build HTML
• The servlet life cycle
• Servlet debugging strategies
A Servlet’s Job
• Read explicit data sent by client (form data)
• Read implicit data sent by client
(request headers)
• Generate
G t the
th resultslt
• Send the explicit data back to client (HTML)
• Send
S d the
th implicit
i li it data
d t to
t client
li t
(status codes and response headers)
5
A Servlet That Generates Plain
Text (HelloWorld
([Link])
java)
import [Link].*;
import [Link].
javax servlet *;
;
import [Link].*;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = [Link]();
[Link]("Hello World");
}
}
URL assumes you have deployed from
an Eclipse project named “intro”. Code
was in src/[Link]
A Servlet That Generates HTML
• Tell the browser that you’re sending it HTML
– [Link]("text/html");
• Modify the println statements to build a
legal Web page
– Print statements should output HTML tags
• Check your HTML with a formal syntax
validator
– [Link]
p g
– [Link]
7
A Servlet That Generates HTML
(Code)
public class HelloServlet extends HttpServlet {
public void doGet(HttpServletRequest request
request,
HttpServletResponse response)
throws ServletException, IOException {
response setContentType("text/html");
[Link]( text/html );
PrintWriter out = [Link]();
String docType =
<!DOCTYPE HTML PUBLIC \
"<!DOCTYPE \"-//W3C//DTD
//W3C//DTD HTML 4.0 "+
+
"Transitional//EN\">\n";
[Link](docType +
\
"<HTML>\n" +
"<HEAD><TITLE>Hello</TITLE></HEAD>\n"+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
/ \
"<H1>Hello</H1>\n" +
"</BODY></HTML>");
}
8 }
A Servlet That Generates HTML
(Result)
Assumes project named intro. Code in src/[Link].
9
Using Packages
• Create a package
–RR-click
li k on src folder
f ld
– New Package
• Dropping servlet in package
– Copy/paste from filesystem or existing project
– Eclipse will automatically change the package statement
at the top of the .java
java file
• Development strategy
– Start with existingg servlets and use them as the startingg
points for later servlets
• Start with HelloServlet2 at beginning
– Always
y use ppackages
g
– Do not do New Servlet
• Results in ugly code with unnecessary parts
10
Using Packages (Continued)
• Manual packaging (no IDE)
– Move
M the
h fil
files to a subdirectory
bdi that
h matches
h the
h package
k name
• For example, I’ll use the coreservlets package for most of the rest of the
servlets in this course. So, the class files need to go in a subdirectory
called coreservlets.
– Insert a package statement in the class file
• E.g., top of [Link]:
package coreservlets; Dot. Not slash!
• Include package name in URL
– [Link]
• This assumes yyou have enabled the “invoker servlet” that lets
you run servlets without explicitly giving them addresses (good
for testing and learning). Assumes project is “intro”.
• You can also give explicit addresses as briefly mentioned in the
l t llecture
last t andd as will
ill b
be di
discussed
d iin more d
detail
t il llater
t ((always
l
used for real-life apps).
11
Using Packages:
HelloServlet2 (Code)
package coreservlets;
public class HelloServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String docType =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "+
"Transitional//EN\">\n";
[Link](docType
p yp +
"<HTML>\n" +
"<HEAD><TITLE>Hello (2)</TITLE></HEAD>\n"+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>Hello (
(2)</H1>\n"
) +
"</BODY></HTML>");
}
}
12
Using Packages:
HelloServlet2 (Result)
Assumes project named intro. Code in src/coreservlets/[Link].
If you made
d the
th [Link]
b l entries
t i ffrom th
the previous
i llecture,
t you could
ld also
l use
the URL [Link]
13
Some Simple HTML-Building
Utilities
public class ServletUtilities {
public static final String
p g 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");
}
...
}
• Don’t go overboard
– Complete
p HTML generation
g packages
p g
usually work poorly
14
– The JSP framework is a better solution
HelloServlet3: HelloServlet with
Packages and Utilities
package coreservlets;
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloServlet3 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
String title = "Hello
Hello (3)";
(3) ;
[Link]([Link](title)+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1>" + title + "</H1>\n" +
"</BODY></HTML>");
/ /
}
}
15
HelloServlet3: Result
Assumes project named intro. Code in src/coreservlets/[Link]
and src/coreservlets/[Link].
16
The Servlet Life Cycle
• 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
p to doGet, doPost, etc.
Do not override this method!
• doGet, doPost, doBlah
–HHandles
dl GET,
GET POST,
POST etc. requests.
– Override these to provide desired behavior.
• destroy
– Called when server deletes servlet instance.
17 Not called after each request.
Why You Should
Not Override service
• The service method does other things
g
besides just calling doGet
– You can add support for other services later by adding
d P t doTrace,
doPut, d T etc.
t
– You can add support for modification dates by adding a
ggetLastModified method
– The service method gives you automatic support for:
• HEAD requests
• OPTIONS requests
• TRACE requests
• Alternative: have doPost call doGet
18
Debugging Servlets
• Use print statements; run server on desktop
• Use Apache Log4J
• Integrated debugger in IDE
– Right-click in left margin in source to set breakpoint (Eclipse)
– R
R-click
click Tomcat and use “Debug”
Debug instead of “Start”
Start
• Look at the HTML source
• Return error pages to the client
– Plan ahead for missingg or malformed data
• Use the log file
– log("message") or log("message", Throwable)
• Separate
p the request
q and response
p data.
– Request: see EchoServer at [Link]
– Response: see WebClient at [Link]
• Make sure browser is not caching
– Internet Explorer: use Shift-RELOAD
– Firefox: use Control-RELOAD
19
• Stop and restart the server
Summary
• Main servlet code goes in doGet or doPost:
– The HttpServletRequest contains the incoming
information
– The
Th HttpServletResponse
Htt S l tR l t you sett outgoing
lets t i
information
• Call setContentType to specify MIME type
• Call getWriter to obtain a Writer pointing to client (browser)
• One-time setup code goes in init
– Ser
Servlet
let gets initialized
initiali ed and loaded once
– Servlet gets invoked multiple times
– Initialization parameters set in [Link]
• Covered in later lecture
20
© 2010 Marty Hall
Questions?
Customized Java EE Training: [Link]
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
21 Developed and taught by well-known author and developer. At public venues or onsite at your location.