More Advanced Stuff
In the previous part of tutorial, we developed our first servlet. Today, we will go deeper into servlet details and what other things they can be used for. Specifically, we'll work on processing request parameters and attributes, and handle forwarding and redirection.
Request Parameters and Attributes
Request parameters are a part of request URL that represents data to be transferred to servlet. This data is used for request processing by the servlet. Consider the following URL:
http://www.domain.com/myservlet?param1=value1¶m2=value2
Part of URL after “?” is called query string and contains request parameters. Each parameter is represented as name-value pair (param1=value1). Parameters are separated by “&” character.
The following code snippet shows how request parameters can be processed in servlet:
// get value of 'name' parameter
String param = req.getParameter("name");
// print HTML content
resp.getWriter().print("<h1>Hello, Servlet!!</h1>");
// use parameter in page
if(param != null){
resp.getWriter().print("<h2>Your name is " + param + "</h2>");
}
// set content type to HTML
resp.setContentType("text/html");
resp.setStatus(HttpServletResponse.SC_OK);
resp.flushBuffer();
In order to view the results, enter the following URL in your browser:
http://localhost:8080/samplewebapp/helloservlet?name=yourname

Forwarding and Redirecting
Servlet API allows redirecting and forwarding requests to another location. The main difference between the two is that, with redirect, browser is actually sent to another location, while with forward, browser uses the same request/response pair, but it can be processed with multiple servlets.
We will demonstrate the redirect first. In order to do it, we'll create two additional servlets: one to do the redirect, and the other that will be the redirect target. Code snippets bellow show these two servlets:
public class RedirServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("targetservlet");
}
}
public class TargetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.getWriter().print("<h1>Target servlet</h1>");
resp.setStatus(HttpServletResponse.SC_OK);
resp.flushBuffer();
}
}
These two servlets will have the following configuration in web.xml:
<servlet-name>redirServlet</servlet-name>
<servlet-class>com.beyondrelational.RedirServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>targetServlet</servlet-name>
<servlet-class>com.beyondrelational.TargetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>redirServlet</servlet-name>
<url-pattern>/redirservlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>targetServlet</servlet-name>
<url-pattern>/targetservlet</url-pattern>
</servlet-mapping>
Now, when you run the application, and enter http://localhost:8080/redirservlet in your browser, you'll get the following result:

Note the change in address bar. The browser was redirected to target servlet, which is reflected in address bar.
In RedirServlet, if you replace redirect call with forward, like this:
req.getRequestDispatcher("targetservlet").forward(req, resp);
Now, if you run the app, you get the following result:

As you can see, this is the same result, but the address bar is unchanged. Forwarding can be used as a way to chain servlets, meaning that one servlet can do part of the processing, pass it to the next, then to the next, until processing is complete.
Request Attributes
The final part of this chapter is about request attributes. They are similar to request parameters, in that they also consist of key-value pair. However, they are not a part of request URL, and are not passed back to client.
Request attributes are arbitrary objects that can be attached to a request during processing. For example, result of servlet processing can be stored as request attribute, and then request is forwarded to another servlet. This server can access the result of previous servlet as a request attribute.
Setting request attributes is pretty simple. Here's the modified redirect servlet:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// store some request attribute
req.setAttribute("attribute", "value");
req.getRequestDispatcher("targetservlet").forward(req, resp);
}
Then, ini target servlet, we write attribute value:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.getWriter().print("<h1>Target servlet</h1>");
// write request attribute value
resp.getWriter().write("<h2>Request attribute: " + req.getAttribute("attribute") + "</h2>");
resp.setStatus(HttpServletResponse.SC_OK);
resp.flushBuffer();
}
As you can see, using request attributes is extremely easy, and they are a powerful tool to enhance servlet functionality and share data between requests.
Find the sample web application here.