HttpServlet
GenericServlet is truly generic because it is applicable to any chat-type protocol; however, web development is mostly about the HTTP protocol. To chat in HTTP, javax.Servlet.http.HttpServlet is best to extend. HttpServlet is a subclass of GenericServlet. Therefore, the init, service, and destroy methods from GenericServlet are available when extending HttpServlet.
HttpServlet defines a method for each of the HTTP methods. These methods are doGet, doPost, doPut, doOptions, doDelete, and doTrace. When Tomcat receives a client request of the GET type, the requested Servlet's doGet() method is invoked to reply to that client. Additionally, HttpServlet has an HTTP-specific version of the service method. The only change in the HttpServlet service method over the GenericServlet's version is that HTTP-specific request and response objects are the parameters (javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponse).
To write a Servlet by subclassing HttpServlet, implement each HTTP method desired (such as doGet or doPost), or define the service method. The HttpServlet class also has a getlastModified method that you may override if you wish to return a value (milliseconds since the 1970 epoch) representing the last time the Servlet or related data was updated. This information is used by caches.
HttpServlet Methods
Table 12.2 includes all of the methods for the javax.servlet.http. HttpServlet class, and example usage in Jython. Those methods that are overridden have a def statement in Jython, and those methods invoked on the superclass begin with self. Java signatures in Table 12.2 do not include return values or permission modifiers. For permissions, all methods are protected except for service(ServletRequest req, ServletResponse res), it has no permissions modifier (package private). All return values are void except for getLastModified, which returns a long type representing milliseconds since the epoch.
Table 12.2 HttpServlet Methods
Java Signature |
Usage in Jython Subclass |
doDelete(HttpServletRequest req, HttpServletResponse resp) |
def doDelete(self, req, res): |
doGet(HttpServletRequest req, HttpServletResponse resp) |
def doGet(self, req, res): |
doHead(HttpServletRequest req, HttpServletResponse resp) |
def doHead(self, req, res): |
doOptions(HttpServletRequest req, HttpServletResponse resp) |
def doOptions(self, req, res): |
doPost(HttpServletRequest req, HttpServletResponse resp) |
def doPost(self, req, res): |
doPut(HttpServletRequest req, HttpServletResponse resp) |
def doPut(self, req, res): |
doTrace(HttpServletRequest req, HttpServletResponse resp) |
def doTrace(self, req, res): |
getLastModified(HttpServletRequest req) |
def getLastModified(self, req): |
service(HttpServletRequest req, HttpServletResponse resp) |
def service(self, req, res): |
service(ServletRequest req, ServletResponse res) |
def service(self, req, res): |
The service method that accepts HTTP-specific request and response object redispatches those request to the appropriate do* method (if it isn't overridden). The service method that accepts a generic Servlet request and response object redispatches the request to the HTTP-specific service method. The redispatching makes the service methods valuable when implementing Servlet mappings.
HttpServlet Example
Listing 12.4 demonstrates a Servlet that subclasses javax.servlet.http. HttpServlet. The example implements both the doGet and doPost methods to demonstrate how those methods are called depending on the type of request received from the client. A web client should not allow a POST operation to be repeated without confirmation. Because of this, database updates, order commits, and so on should be in a doPost method, whereas the forms to do so can reside safely in a doGet.
The get_post.py file in Listing 12.4 shows how to get parameter names and values by using the HttpServletRequest's (req) getParameterNames and getParameterValues. The list returned from getParameterNames is a java.util.Enumeration, which the doPost method uses to display the request's parameters. Jython lets you use the for x in list: syntax with the enumeration returned from getParameternames. Note that the getParameterValues() method is plural. Parameters can have multiple values as demonstrated in the hidden form fields. To prevent redundancy in the doGet and doPost methods of the Servlet, Listing 12.4 adds a _params method. This method is not defined anywhere in HttpServlet or its bases, and because no Java class calls it, no @sig string is required. The purpose of the method is merely to keep similar operations in only one place.
Listing 12.4 Implementing a Servlet with HttpServlet
#file get_post.py from time import time, ctime from javax import servlet from javax.servlet import http class get_post(http.HttpServlet): head = "<head><title>Jython Servlets</title></head>" title = "<center><H2>%s</H2></center>" def doGet(self,req, res): res.setContentType("text/html") out = res.getWriter() out.println('<html>') out.println(self.head) out.println('<body>') out.println(self.title % req.method) out.println("This is a response to a %s request" % (req.getMethod(),)) out.println("<P>In this GET request, we see the following " + "header variables.</P>") out.println("<UL>") for name in req.headerNames: out.println(name + " : " + req.getHeader(name) + "<br>") out.println("</UL>") out.println(self._params(req)) out.println(""" <P>The submit button below is part of a form that uses the "POST" method. Click on this button to do a POST request. </P>""") out.println('<br><form action="get_post" method="POST">' + '<INPUT type="hidden" name="variable1" value="one">' + '<INPUT type="hidden" name="variable1" value="two">' + '<INPUT type="hidden" name="variable2" value="three">' + '<INPUT type="submit" name="button" value="submit">') out.println('<br><font size="-2">time accessed: %s</font>' % ctime(time())) out.println('</body></html>') def doPost(self, req, res): res.setContentType("text/html"); out = res.getWriter() out.println('<html>') out.println(self.head) out.println('<body>') out.println(self.title % req.method) out.println("This was a %s<br><br>" % (req.getMethod(),)) out.println(self._params(req)) out.println('<br> back to <a href="get_post">GET</a>') out.println('<br><font size="-2">time accessed: %s</font>' % ctime(time())) out.println('</body></html>') def _params(self, req): params = "Here are the parameters sent with this request:<UL>" names = req.getParameterNames() if not names.hasMoreElements(): params += "None<br>" for name in names: value = req.getParameterValues(name) params += "%s : %r<br>" % (name, tuple(value)) params += "</UL>" return params
After placing the get_post.py file in the $TOMCAT_HOME/webapps/jython/WEB-INF/classes directory, compile it with the following:
jythonc w . deep get_post.py
To test it, point your browser at http://localhost:8080/jython/servlet/get_post. You should see a browser window similar to that in Figure 12.1.
Figure 12.1. The GET view from get_post.py.
The parameters for the GET operation are None in this example, but test other parameters in the doGet method by adding some to the end of the URL(such as http://localhost:8080/servlet/get_post?variable1=1&variable2=2).
Because the Submit button on the bottom of the first view is part of a form implemented as a POST, clicking on the Submit button executes the doPost method of the same Servlet. The results of the doPost method should match what is shown in Figure 12.2.
Figure 12.2. The POST view from get_post.py.
HttpServletRequest and HttpServletResponse
Communication with client connections happens through the HttpServletRequest and HttpServletResponse object. These are abstractions of the literal request stream received from and sent to the client. Each of these objects adds higher-level, HTTP-specific methods to ease working with requests and responses.
Table 12.3 is a list of the methods within the HttpServletRequest object. A great majority of the methods are bean property accessors, which means that you can reference them with Jython's automatic bean properties. This may not be as great of an advantage here as it is for GUI programming because there is no opportunity to leverage this facility in method keyword arguments. Table 12.3 shows the methods and bean property names from the HttpServletRequest object.
Table 12.3 HttpServletRequest Methods and Properties
Method and Property |
Description |
Method: getAuthType() |
Returns a string (PyString) describing the name of the authentication type. The value is None if the user is notauthenticated. |
Method: getContextPath() |
Returns a string (PyString) describing the path information that identifies the context requested. |
Method: getCookies() |
Returns all cookies sent with the client's request as an array of j avax.servlet.http.Cookie objects. |
Method: getDateHeader(name) |
Retrieves the value of the specified header as a long type. |
Method: getHeader(name) |
Returns the value of the specified header as string (PyString). |
Method: getHeaderNames() |
Returns all the header names contained within the request as an Enumeration. |
Method: getHeaders(name) |
Returns all the values of the specified header name as an Enumeration. |
Method: getIntHeader(name) |
Retrieves the specified header value as a Java int, which Jython converts to a PyInteger. |
Method: getMethod() |
Returns the type of request made a string. |
Method: getPathInfo() |
All extra path information sent by the client. |
Method: getPathTranslated() |
Returns the real path derived from extra path information in the client's request. |
Method: getQueryString() |
Returns the query string from the client's request (the string after the path). |
Method: getRemoteUser() |
Returns the login name of the client. None if the client is not authenticated. |
Method: getRequestedSessionId() Property name: requestedSessionId |
Returns the clients session ID. |
Method: getRequestURI() |
Returns that segment of the between the protocol name and the query string. |
Method: getServletPath() |
Returns the portion of the URL that designates the current Servlet. |
Method: getSession() |
Returns the current session, or creates on if needed. A session is an instance of javax.servlet.http.HttpSession. |
Method: getSession(create) |
Returns the current session if one exists. If not, a new session is created if the create value is true. |
Method: getUserPrincipal() |
Returns a java.security.Principal object with the current authentication information userPrincipal |
Method: isRequestedSessionIdFromCookie() |
Returns 1 or 0 depending on whether the current session ID was from a cookie. |
Method: isRequestedSessionIdFromURL() |
Returns 1 or 0 depending on whether the current session ID was from the requested URL string. |
Method: isRequestedSessionIdValid() |
Returns 1 or 0 depending on whether the requested session ID is still valid. |
Method: isUserInRole(role) |
Returns 1 or 0 indicating whether the user is listed in the specified role. |
The HttpServletResponse object is used to send the mime-encoded stream back to the client. HttpServletResponse defines additional HTTP-specific methods that do not exist in a generic ServletResponse object. The methods within the HttpServletResponse object appear in Table 12.4. Whereas Jython adds numerous automatic bean properties to the HttpServletRequest object, the HttpServletResponse object only has one: status.
Table 12.4 HttpServletResponse Methods and Properties
Method and Property |
Description |
addCookie(cookie) |
Add a cookie to the response. |
addDateHeader(headerName, date) |
Adds a header name with a date (long) value. |
addHeader(headerName, value) |
Adds a header name and value. |
addIntHeader(headerName, value) |
Adds a header name with an integer value. |
containsHeader(headerName) |
Returns a 1 or 0 depending whether the specified header. |
encodeRedirectUrl(url) |
Encodes a URL for the sendRedirect method. For version 2.1 and greater, use encodeRedirectURL instead. |
encodeRedirectURL(url) |
Encodes a URL for the sendRedirect method. |
encodeURL(url) |
Encodes a URL by including the session ID in it. |
sendError(sc) |
Sends an error using the status code. |
sendError(sc, msg) |
Sends an error using the specified status code and message. |
sendRedirect(location) |
Sends a temporary redirect to the specified location. |
setDateHeader(headerName, date) |
Sets a header name to the specified date (long) value. |
setHeader(headerName, value) |
Sets a header name to the specified value. |
setIntHeader(headerName, value) |
Sets a header name to the specified integer value. |
setStatus(statusCode) status |
Sets the response status code. |
The HttpServletResponse class also contains fields that correspond to the standard HTTP response codes. You can use these with sendError(int) and setStatus(int). Table 12.5 lists the number and error code for these status codes.
Table 12.5 HttpServletResponse Status CodesError
Code |
Status |
100 |
SC_CONTINUE |
101 |
SC_SWITCHING_PROTOCOLS |
200 |
SC_OK |
201 |
SC_CONTINUE |
202 |
SC_ACCEPTED |
203 |
SC_NON_AUTHORITATIVE_INFORMATION |
204 |
SC_NO_CONTENT |
205 |
SC_RESET_CONTENT |
206 |
SC_PARTIAL_CONTENT |
300 |
SC_MULTIPLE_CHOICES |
301 |
SC_MOVED_PERMANENTLY |
302 |
SC_MOVED_TEMPORARILY |
303 |
SC_SEE_OTHER |
304 |
SC_NOT_MODIFIED |
305 |
SC_USE_PROXY |
400 |
SC_BAD_REQUEST |
401 |
SC_UNAUTHORIZED |
402 |
SC_PAYMENT_REQUIRED |
403 |
SC_FORBIDDEN |
404 |
SC_NOT_FOUND |
405 |
SC_METHOD_NOT_ALLOWED |
406 |
SC_NOT_ACCEPTABLE |
407 |
SC_PROXY_AUTHENTICATION_REQUIRED |
408 |
SC_REQUEST_TIMEOUT |
409 |
SC_CONFLICT |
410 |
SC_GONE |
411 |
SC_LENGTH_REQUIRED |
412 |
SC_PRECONDITION_FAILED |
413 |
SC_REQUEST_ENTITY_TOO_LARGE |
414 |
SC_REQUEST_URI_TOO_LONG |
415 |
SC_UNSUPPORTED_MEDIA_TYPE |
500 |
SC_INTERNAL_SERVER_ERROR |
501 |
SC_NOT_IMPLEMENTED |
502 |
SC_BAD_GATEWAY |
503 |
SC_SERVICE_UNAVAILABLE |
504 |
SC_GATEWAY_TIMEOUT |
505 |
SC_HTTP_VERSION_NOT_SUPPORTED |