Requests
import javax.servlet.http.*;
import java.io.*;
// Servlet that shows a simple form with two text fields,
// allowing the user to enter numbers and showing their sum
public class CalculatorServlet extends HttpServlet {
// Prints the calculator HTML
private void printCalculator(HttpServletResponse response, Integer result)
throws IOException {
response.setContentType("text/html; charset=UTF-8"); // HTML in UTF8
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
writer.print("<html><head><title>Calculator</title></head><body>");
writer.print("<form><input name='x'> + <input name='y'> <input type='submit' value='='> ");
if (result != null)
writer.print(result);
writer.print("</form></body></html>");
}
// handles GET and POST (more)
private void doAll(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Integer result = null;
String x = request.getParameter("x");
String y = request.getParameter("y");
// validation: check parameters are numeric (more)
if (x != null && y != null &&
x.matches("[0-9]+") && y.matches("[0-9]+")) {
result = Integer.parseInt(x) + Integer.parseInt(y);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
doAll(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException {
doAll(request, response);
}
}
How to find out which parameters have been sent
The Servlet API offers two ways of getting a list of all parameters. getParameterNames returns an Enumeration of names. The alternative, getParameterMap, returns a Map of all parameter name/value pairs, but with one catch: the value is a String array (more).
The following example uses getParameterMap to print all request parameters that it got:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain; charset=UTF-8"); // plain text (more)
response.setCharacterEncoding("UTF-8");
PrintWriter writer = response.getWriter();
Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap();
writer.println("Request parameters:");
for (String name: params.keySet())
for (String value: params.get(name)) // values are arrays (more)
writer.printf("%s=%s\n", name, value); // formatted print (more)
}
How to read header values
This example reads the User-Agent request header sent by the client to guess the user's browser (more):
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
response.setContentType("text/plain; charset=UTF-8"); // plain text (more)
response.setCharacterEncoding("UTF-8");
String userAgent = request.getHeader("User-Agent");
String browserGuess = "some other browser";
if (userAgent != null) {
if (userAgent.contains("Firefox/"))
browserGuess = "Firefox";
else if (userAgent.contains("MSIE"))
browserGuess = "Internet Explorer";
}
response.getWriter().println("Request parameters:");
}
Find out more about browser detection in the browser detection section below.
With the <servlet-mapping> element you can define for which paths your servlet will be invoked. Paths are defined using URL patterns.
URL Pattern
The <url-pattern> element in the servlet mapping supports only two kinds of wildcards:
- '/*' at the end, to map the servlet on a virtual directory
- '*.ext', to map the servlet on a file extension
Other uses of wildcards are not allowed.
Servlet Mapping
This web.xml snippet maps the servlet both on the directory '/libs' and the file extension '*.do':
<servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/libs/*</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
Path Methods
When using wildcards like this, there are a number of methods in HttpServletRequest to find out the request path:
- getRequestURI - the complete path, starting at the server's root
- getContextPath - the context root of the servlet (empty for context root "/")
- getServletPath - for directory patterns: the mapped directory; for extension patterns: path relative to context root
- getPathInfo - for directory patterns: path relative to servlet path; for extension patterns: always null
URL Examples
Assuming the servlet mapped above has the context root 'myapp', here a few example URLs and their resulting paths:
| URL | getRequestURI | getContextPath | getServletPath | getPathInfo |
|---|---|---|---|---|
| http://localhost/myapp/lib/x/y/a.htm | /myapp/lib/x/y/a.htm | /myapp | /lib | /x/y/a.htm |
| http://localhost/myapp/lib/abc/ | /myapp/lib/abc/ | /myapp | /lib | /abc/ |
| http://localhost/myapp/help.do | /myapp/help.do | /myapp | /myapp/help.do | null |
| http://localhost/myapp/abc/run.do | /myapp/abc/run.do | /myapp | /myapp/abc/run.do | null |
Root Pattern
You can also set the <url-pattern> to "/". The servlet will then handle all paths, and the path methods return the same values as they do for mapped extensions.

