- Chapter 3: Using Servlet Functionality with JSP
- Looking at an Example Servlet
- The End of the Beginning
Looking at an Example Servlet
Servlets are conceptually simple. You configure your Web server to map a certain URL path to a Java class (different servers do this differently). The Java class needs to extend HttpServlet and handle one of several methods: doGet, doPost, doPut, or doDelete. (doGet or doPost are used most commonly.)
These messages reflect the various ways that servlets are invoked by a GET, POST, PUT, or DELETE HTTP request from a client (although DELETE is rare). The servlet is responsible for setting the mime type, error code, cookies, and other status information about the request, as well as returning the content.
Let's say that the path /baseballstats has been mapped to the class BaseBallStatServlet. This is a class that knows about the current batting averages of major league baseball players. To use it, you send a URL like this:
http://www.baseballstats.com/baseballstats?player=Nomar Garciapara
Listing 3.1 is a simple implementation of that servlet.
Listing 3.1 BaseBallStatServlet.ava
import javax.servlet.*; import javax.servlet.http.*; public class BaseBallStatServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws java.io.IOException { resp.setContentType("text/html"); java.io.PrintWriter html = resp.getWriter(); String player = (String) req.getParameter("player"); html.println("<HTML><HEAD><TITLE>MLB Player Stats</TITLE></HEAD>"); html.println("<BODY>"); if ((player == null) || (player.length() == 0)) { html.println("<H1>No Player Requested</H1>"); } else { if (player.equals("Nomar Garciapara")) { html.println("<H1>Nomar is batting .932</H1>"); } else { html.println("<H1>" + player + " is batting .234</H1>"); } } html.println("</BODY></HTML>"); } }
Ignoring for the moment the bias toward a certain Boston slugger, you can see that all the basic elements of a servlet are in place.
The doGet method is handed the request and response objects. The request has all the parameters handed in to the Web request, including cookies, form submissions, and header data. The response is used to formulate a reply to request.
To create the reply, the first thing you need to do is to set the content type of the reply. In most cases, that will be text/html, although you might be generating other types of replies, such as XML.
Next, you need to get a handle on the output stream so that you can start generating HTML. In cases in which you are writing text data (as opposed to binary data, such as if you were programmatically generating a JPG file), you want to get a PrintWriter, which you can find by calling getWriter on the response object.
Next you use getParameter on the request to get the form or URL submitted player name. You need to make sure to check for blank or null values for this parameter, or an exception might occur later.
Output the boilerplate HTML header for the document, then compare the name of the player against your primitive database, close the HTML forms, and you're finished with the request.
JSP: Servlets, Only Better!
Although we'll spend the rest of the chapter discussing the servlet objects because JSP uses them heavily, I'm going to say right here and now that using servlets themselves is not something I'd recommend.
This is because they obscure the functionality of the site and require ugly embedding of HTML inside Java. One of the features of JSP is that the formatting (HTML) has been largely segregated from the coding (Java). When you start using pure servlets, you have to put HTML code right in the middle of the Java.
As a result, you need to recompile the class every time you change a minor page format feature. This gets very exhausting very quickly during development, and it is worse in a deployed site.
Also, because of the indirection between the URL and the class name, you can have a difficult time trying to find the actual code behind a servlet request. It usually involves looking at the server configuration file, which can be confusing.
More to the point, everything that a servlet does can be done with a JSP page. Listings 3.2 and 3.3 show a JSP page and a Bean that do the same thing. Notice how much more clearly JSP does it in Listing 3.2.
Listing 3.2 BaseBallStats.jsp
<jsp:useBean id="statEngine" scope="session" class="com.mlb.stats.statBean" /> <HTML><HEAD><TITLE>MLB Player Stats</TITLE></HEAD> <BODY> <H1><%= statEngine.processRequest(request, response) %> </H1> </BODY> </HTML>
Listing 3.3 statBean.java
package com.mlb.stats; import javax.servlet.*; import javax.servlet.http.*; public class statBean { public String processRequest(HttpServletRequest req, HttpServletResponse resp) { String player = (String) req.getParameter("player"); if ((player == null) || (player.length() == 0)) { return("No Player Requested"); } else { if (player.equals("Nomar Garciapara")) { return("Nomar is batting .932"); } else { return(player + " is batting .234"); } } } }
This is a much more desirable division of labor, with the JSP handling the HTML formatting and the back-end Java Bean handling the business logic. A third way (and the official JSP way) to write this is using jsp:setProperties to handle the form submit instead of letting the Bean decode the form arguments.
Servlet Functionality Inside JSP
If servlet programming is yesterday's news, why is a chapter devoted to it? The reason is that there's a lot of useful functionality in the Servlet API to take advantage of.
The previous code highlights one examplesometimes you want to explicitly handle a form submission rather than use the Bean property-setting mechanisms. This might be because you want to do a certain type of error checking (more on this in Chapter 8, "Retrieving, Storing, and Verifying User Input") or because you want to set values in a manner that's more complicated than the useProperty mechanism allows.
Beyond the getParameter functionality, there are a lot of other things that the various servlet classes can tell you. Let's break them down class by class.
HttpServletRequest
The HttpServletRequest object, which is available as request in a JSP page, contains all the information that is passed from the browser to the server during a Web transaction. The following code highlights a few of the things that can be extracted.
First, you'll extend the user object with another property:
protected String userName; public String getUserName() { return userName; } public void setUserName(String uname) { userName = uname; }
Listing 3.4 gives the actual JSP code.
Listing 3.4 HttpObjectDemo.jsp
<jsp:useBean id="user" scope="session" class="com.cartapp.user.User" /> <jsp:setProperty name="user" property="*" /> <HTML> <HEAD> <TITLE>HttpRequest/HttpResponse Demo</TITLE> </HEAD> <BODY> <% Cookie [] cookies = request.getCookies(); boolean found_cookie = false; if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("cartAppUserName")) { user.setUserName(cookies[i].getValue()); found_cookie = true; } } } if (!found_cookie) { if (user.getUserName() != null) { Cookie setCookie = new Cookie("cartAppUserName", user.getUserName()); setCookie.setMaxAge(3600 * 24 * 265); // Expire in one year response.addCookie(setCookie); found_cookie = true; } } if (!found_cookie) { %> <FORM METHOD="POST"> Please Enter Your User Name: <INPUT TYPE="TEXT" NAME="userName"><BR> <INPUT TYPE="SUBMIT"> </FORM> <% } else { %> <H1>Hello <%= user.getUserName() %></H1> <% if (request.getAuthType() != null) { %> You don't need to use a secure connection.<p> <% } %> For your information, your session id is <%= request.getRequestedSessionId() %><p> You accessed this page using a <%= request.getMethod() %><p> <% if (request.isRequestedSessionIdFromURL()) { %> You know, using URL rewriting is ugly, turn on cookie support.<p> <% } else { %> Good, you support cookies, nice choice.<p> <% } } %> </BODY> </HTML>
The first time you run this code, you'll see the page shown in Figure 3.1.
Figure 3.1 Running the servlet example for the first time.If you fill in a value for the username and hit submit, you'll see the page shown in Figure 3.2.
Figure 3.2 Running the servlet example for the second time.Let's go through the code and see what's going on. The first two lines of JSP should look familiar. They do the same importation and property setting of the User class as you've done before. When you first access the page, there are no parameters passed in, so the setProperty does nothing.
Next, the request object is queried for a list of all the cookies handed in with the request. When you request a Web page, the browser checks to see if any of the cookies that it has stored locally are applicable to the Web site being accessed. Usually, the cookie is stored so that any Web site under the top-level domain will be sent the cookiewhich means, for example, that www1.mysite.com and www2.mysite.com can both see the cookie (assuming that you own a domain called mysite.com to begin with).
The code then iterates over the array of cookies looking for the cookie that holds the username of the user. If the code finds a match, it writes it into the Bean and sets a flag. In a real application, you probably also would make a database call to load all sorts of user information, as you'll see in Chapter 8.
If the code didn't find the cookie, it checks to see if the Bean's username is set. If it is, it means that the form has been submitted and that a username now resides inside the user object. If that is the case, the code adds a new cookie to the response object to set the username cookie to the submitted value with a one-year expiration.
If the cookie wasn't found, and it wasn't being written for the first time because of a form submit, it displays a form to let the user input one from a form. When the user hits Submit, he is brought back around to this page, but now setProperty places the submitted username into the user Bean. This means that when the code comes along that checks if there's a username present in the Bean, it will be true and the cookie will be set.
If a cookie was found, a check is made to see if a secure SSL request was used, which would be overkill for this application. Next, the user is shown his session ID, which is a unique ID code generated for each session to distinguish incoming requests. Then the user is told whether a GET, POST, or PUT was used to access this page.
The session ID is usually stored as a transient cookie (one with a MaxAge of -1, which means that it goes away when the browser is closed). If the user has disabled cookies, the session ID is passed around using URL rewriting. If that's happening, the user is sent a message telling him to be less paranoid and to turn cookies back on.
What you've just seen is essentially the code that every site that implements "remembering" your username goes through. Consider it your first peek at the process of making a customer-friendly Web site work.
The HttpServletResponse Object
You saw one thing that you can do with the response object in the last sectionuse it to set a cookie.
Listing 3.5 is a simple JSP page that demonstrates a number of neat things that you can do with the response object.
Listing 3.5 HttpResponseDemo.jsp
<% String arg = "default"; if (request.getParameter("arg") != null) { arg = request.getParameter("arg"); } if (arg.equals("redirect")) { response.sendRedirect("http://www.cnn.com/"); } else if (arg.equals("xml")) { response.setContentType("text/xml"); %> <Vegetable> <Name>Carrot</Name> <Color>Orange</Color> <Consumer>Bugs Bunny</Consumer> </Vegetable> <% } else { response.sendError(HttpServletResponse.SC_NOT_FOUND, "There's No Such Page!"); } %>
If you request the page with no arguments in the URL, you get an error message (see Figure 3.3).
This is an example of using the sendError method of the response object, which lets you generate an arbitrary status response for the request. In this case, we're generating a 404, file not found, although with a customized message rather than the generic Tomcat error message for a 404.
If you pass in arg=redirect on the URL, you get redirected to the CNN Web page. There are some specific restrictions on using redirect. The main restriction is that you have to make sure that the redirect is requested before any content is sent to the browser; otherwise, the redirect string shows up as text in the Web page.
If you use arg=xml, you're sent back some XML content. This demonstrates an important pointJSP and Java servlets can return more than just HTML content. By using the setContentType message, you can generate a response of any content type you want. For example, you could generate a JPG image using one of the Java image-manipulation libraries and send it back by setting the content type to image/jpeg (see Figure 3.4).
Figure 3.3 Using the sendError method.Figure 3.4 Sending XML by setting the content type.