Building Web Apps in Java: Servlet
Reference: http://courses.coreservlets.com
Last lecture/lab we have installed and used Eclipse with Tomcat to deploy simple
servlets.
A Servlet’s Job
Read explicit data sent by client (form data)
Read implicit data sent by client (request headers)
Generate the results
Send explicit data back to client (HTML)
Send implicit data to client (status codes and response headers)
Why Build Web Pages Dynamically?
The Web page is based on data submitted by the user
- E.g., results page from search engines and order confirmation
pages at on-line stores
The Web page is derived from data that changes frequently
- E.g., a weather report or news headlines page
The Web page uses information from databases or other server-side
sources
- E.g., an e-commerce site could use a servlet to build a Web
page that lists the current price and availability of each item that
is for sale
Ten Most Popular Web Sites (Alexa.com, Summer 2010)
# Web site Technology
1 Google Java (Web), C++ (indexing)
2 Facebook PHP
3 YouTube Flash, Python, Java
4 Yahoo PHP and Java
5 Microsoft Live.com .NET
6 Baidu Unknown
7 Wikipedia PHP
8 Blogger Java
9 MSN .NET
10 Twitter Ruby on Rails, Scala, Java
Keywords in Job Postings
Extending the Power of Servlets: JavaServer Pages (JSP)
Idea:
- Use regular HTML for most of page
- Mark dynamic content with special tags
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>Welcome to Our Store</TITLE></HEAD>
<BODY>
<H1>Welcome to Our Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
<%= coreservlets.Utils.getUserNameFromCookie(request) %>
To access your account settings, click
<A HREF="Account-Settings.html">here.</A></SMALL>
<P>
Regular HTML for rest of on-line store’s Web page
</BODY></HTML>
Making New Apps in Eclipse
Make empty project
File New Project Web Dynamic Web Project
For “Target runtime”, choose “Apache Tomcat v7.0”
Give it a name (e.g., “test”)
Accept all other defaults
Shortcut
If you have made Dynamic Web Project recently in workspace, you can just do File
New Dynamic Web Project
Adding Code to Eclipse Projects
Simple Servlets
1. A Servlet That Generates Plain Text (HelloWorld.java)
package testPackage; // Always use packages.
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
@WebServlet("/hello")
public class HelloWorld extends HttpServlet {
@Override
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
}
Understanding HelloWorld Servlet
@WebServlet("/address")
- This is the URL relative to the app name. More later.
doGet
- Code for an HTTP GET request. doPost also common.
HttpServletRequest
- Contains anything that comes from the browser
HttpServletResponse
- Used 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
2. A Servlet That Generates HTML (Structure)
Tell the browser that you’re sending it HTML
- response.setContentType("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
- http://validator.w3.org/
- http://www.htmlhelp.com/tools/validator/
A Servlet That Generates HTML (Code)
@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();
out.println
("<!DOCTYPE html>\n" +
"<html>\n" +
"<head><title>A Test Servlet</title></head>\n" +
"<body bgcolor=\"#fdf5e6\">\n" +
"<h1>Test</h1>\n" +
"<p>Simple servlet for testing.</p>\n" +
"</body></html>");
}
}
A Servlet That Generates HTML (Result)
Using Helper Classes
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
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. 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.
A Simple HTML-Building Utility
public class ServletUtilities {
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 poorly
The JSP framework is a better solution
- More important is to avoid repeating logic. ServletUtilities has a few
methods for that, as will be seen later
TestServlet2
...
@WebServlet("/test-with-utils")
public class TestServlet2 extends HttpServlet {
public 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) +
"<body bgcolor=\"#fdf5e6\">\n" +
"<h1>" + title + "</h1>\n" +
"<p>Simple servlet for testing.</p>\n" +
"</body></html>");
}
}
TestServlet2: Result
Custom URLs and web.xml
Tomcat 7 or Other Servlet 3.0 Containers
Give address with @WebServlet
@WebServlet("/my-address")
public class MyServlet extends HttpServlet { … }
- Resulting URL
http://hostName/appName/my-address
Omit web.xml entirely
- You are permitted to use web.xml even when using @WebServlet, but the
entire file is completely optional.
In earlier versions, you must have a web.xml file even if there were no tags other
than the main start and end tags (<web-app …> and </web-app>).
Example: URLs with @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();
out.println ("<!DOCTYPE html>\n" +
…);
}
}
Defining Custom URLs in web.xml (Servlets 2.5 & Earlier)
Java code
package myPackage; ...
public class MyServlet extends HttpServlet { ... }
web.xml entry (in <web-app...>...</web-app>)
- Give name to servlet
<servlet>
<servlet-name>MyName</servlet-name>
<servlet-class>myPackage.MyServlet</servlet-class>
</servlet>
- – Give address (URL mapping) to servlet
<servlet-mapping>
<servlet-name>MyName</servlet-name>
<url-pattern>/my-address</url-pattern>
</servlet-mapping>
Resultant URL
- http://hostname/appName/my-address
Defining Custom URLs: Example
Defining Custom URLs: Result
Eclipse details
- Name of Eclipse project is “test-app”
- Servlet is in src/testPackage/TestServlet.java
- Deployed by right-clicking on Tomcat, Add and Remove Projects, Add,
choosing test-app project, Finish, right-clicking again, Start (or Restart)
Summary
Main servlet code goes in doGet or doPost:
- The HttpServletRequest contains the incoming information
- The HttpServletResponse lets you set outgoing information
Call setContentType to specify MIME type
Call getWriter to obtain a Writer pointing to client (browser)
Make sure output is legal HTML
Give address with @WebServlet or web.xml
@WebServlet("/some-address")
public class SomeServlet extends HttpServlet { … }
Resulting URL
- http://hostName/appName/some-address