The document provides an overview of servlet basics, including:
- The main job of a servlet is to read data from the client request, generate a response, and send data back to the client.
- A simple "Hello World" servlet is presented that generates plain text. Another example generates HTML output.
- Helper classes can be used to avoid duplicating code across servlets.
- Servlets are given URLs either through the @WebServlet annotation or by mapping in the web.xml file.
- The servlet life cycle and debugging strategies are briefly discussed. Advanced topics like the service method are also covered.
4. A Servlet That Generates Plain
Text (HelloWorld java)Text (HelloWorld.java)
package testPackage; // Always use packages.
import java io *;import java.io. ;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;p j p
@WebServlet("/hello")
public class HelloWorld extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
th S l tE ti IOE ti {throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}}
}
8
URL assumes you have deployed from a project named âtest-appâ. Code can be downloaded from
Web site. General form is http://hostName/appName/address-from-WebServlet-annotation.
Review previous tutorial section for info on how to deploy the app from Eclipse.
Interpreting HelloWorld Servlet
âą @WebServlet("/address")
â This is the URL relative to the app name. More later.
âą doGet
C d f HTTP GET t d P t lâ Code for an HTTP GET request. doPost also common.
âą HttpServletRequest
Contains anything that comes from the browserâ Contains anything that comes from the browser
âą HttpServletResponse
â Used to send stuff to the browser. Most common isUsed to send stuff to the browser. Most common is
getWriter for a PrintWriter that points at browser.
âą @Override
â General best practice when overriding inherited methods
âą But, I will omit on many of my PowerPoint slides to
conserve space. Downloadable source has @Override.9
5. A Servlet That Generates HTML
âą Tell the browser that youâre sending it HTML
â response.setContentType("text/html");
âą Modify the println statements to build a
legal Web pagelegal Web page
â Print statements should output HTML tags
âą Check your HTML with a formal syntaxâą Check your HTML with a formal syntax
validator
â http://validator.w3.org/p g
â http://www.htmlhelp.com/tools/validator/
10
Caveat: As of 2010, it has become moderately conventional to use the HTML 5 DOCTYPE: <!DOCTYPE html>. Even though few browsers have full support for HTML 5, this
declaration is supported in practice by virtually all browsers. So, most validators will give some warnings or errors, and you have to search for the ârealâ errors in the list, or use a
different declaration. My examples use a mix of this doc type, the formal HTML 4 doc type, and the formal xhtml doc type.
A Servlet That Generates HTML
(Code)(Code)
@WebServlet("/test1")
public class TestServlet extends HttpServlet {public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException IOException {throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.printlnout.println
("<!DOCTYPE html>n" +
"<html>n" +
"<head><title>A Test Servlet</title></head>n" +ead t t e est Se et /t t e / ead
"<body bgcolor="#fdf5e6">n" +
"<h1>Test</h1>n" +
"<p>Simple servlet for testing.</p>n" +p p g /p
"</body></html>");
}
}11
7. Idea
âą All Java code goes in the same place
â In Eclipse, it is src/packageName
âą It does not matter if code is for a servlet, helper class,
filter, bean, custom tag class, or anything else, , g , y g
âą Donât forget OOP principles
â If you find you are doing the same logic multiple times,
put the logic in a helper class and reuse it
âą Simple example here
Generates HTML B ilding HTML from a helper class isâ Generates HTML. Building HTML from a helper class is
probably not really worth it for real projects, but we
havenât covered logic in servlets yet. But the general
principle still holds: if you are doing the same thing in
several servlets, move the code into shared helper class.
14
A Simple HTML-Building Utility
public class ServletUtilities {
public static String headWithTitle(String title) {public static String headWithTitle(String title) {
return("<!DOCTYPE html>n" +
"<html>n" +
"<head><title>" + title + "</title></head>n");)
}
...
}
âą Donât go overboard
â Complete HTML generation packages
usually work poorlyusually work poorly
âą The JSP framework is a better solution
â More important is to avoid repeating logic.p p g g
ServletUtilities has a few methods for that, as will
be seen later
15
8. TestServlet2
...
@WebServlet("/test-with-utils")
public class TestServlet2 extends HttpServlet {
public void doGet(HttpServletRequest requestpublic void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Test Servlet with Utilities";
out.println
(ServletUtilities headWithTitle(title) +(ServletUtilities.headWithTitle(title) +
"<body bgcolor="#fdf5e6">n" +
"<h1>" + title + "</h1>n" +
"<p>Simple servlet for testing.</p>n" +
/ /"</body></html>");
}
}
16
TestServlet2: Result
Assumes project is named test-app.
17
10. Example: URLs with
@WebServlet@WebServlet
package testPackage;
âŠâŠ
@WebServlet("/test1")
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response getWriter();PrintWriter out = response.getWriter();
out.println
("<!DOCTYPE html>n" +
âŠ);
}
}
20
Defining Custom URLs in
web xml (Servlets 2 5 & Earlier)web.xml (Servlets 2.5 & Earlier)
âą Java code
package myPackage;package myPackage; ...
public class MyServlet extends HttpServlet { ... }
âą web.xml entry (in <web-app...>...</web-app>)
Gi t l tâ Give name to servlet
<servlet>
<servlet-name>MyName</servlet-name>
<servlet class>myPackage MyServlet</servlet class><servlet-class>myPackage.MyServlet</servlet-class>
</servlet>
â Give address (URL mapping) to servlet
<servlet-mapping><servlet-mapping>
<servlet-name>MyName</servlet-name>
<url-pattern>/my-address</url-pattern>
</servlet-mapping>pp g
âą Resultant URL
â http://hostname/appName/my-address
21
11. Defining Custom URLs: Example
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2 4"
Don't edit this manually.
Should match version supported
by your server If your server<web app version 2.4
... >
<!-- Use the URL http://hostName/appName/test2 for
by your server. If your server
supports 3.0, can omit web.xml
totally and use annotations.
p pp
testPackage.TestServlet -->
<servlet>
<servlet-name>Test</servlet-name>
Fully qualified classname.
<servlet-class>testPackage.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
< l t >T t</ l t >
Any arbitrary name.
But must be the same both times.
<servlet-name>Test</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
</web-app> The part of the URL that comes after the app (project) name.
</web-app>
22
Should start with a slash.
Defining Custom URLs: Result
âą Eclipse details
f li j iâ Name of Eclipse project is âtest-appâ
â Servlet is in src/testPackage/TestServlet.java
â Deployed by right-clicking on Tomcat Add and Removeâ Deployed by right-clicking on Tomcat, Add and Remove
Projects, Add, choosing test-app project, Finish,
right-clicking again, Start (or Restart)23
13. Why You Should
Not Override serviceNot Override service
âą The service method does other thingsg
besides just calling doGet
â You can add support for other services later by adding
d P t d T tdoPut, doTrace, etc.
â You can add support for modification dates by adding a
getLastModified methodg
â The service method gives you automatic support for:
âą HEAD requests
âą OPTIONS requestsâą OPTIONS requests
âą TRACE requests
âą Alternative: have doPost call doGet
26
Debugging Servlets
âą Use print statements; run server on desktop
âą Use Apache Log4Jâą Use Apache Log4J
âą Integrated debugger in IDE
â Right-click in left margin in source to set breakpoint (Eclipse)
â R-click Tomcat and use âDebugâ instead of âStartâR click Tomcat and use Debug instead of Start
âą Look at the HTML source
âą Return error pages to the client
â Plan ahead for missing or malformed datag
âą Use the log file
â log("message") or log("message", Throwable)
âą Separate the request and response data.p q p
â Request: see EchoServer at www.coreservlets.com
â Response: see WebClient at www.coreservlets.com
âą Make sure browser is not caching
â Internet Explorer: use Shift-RELOAD
â Firefox: use Control-RELOAD
âą Stop and restart the server27