Home > Articles > Programming > Python

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book


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):
*in J2EE version 1.3

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):
    out = res.getWriter()

    out.println(self.title % req.method)

    out.println("This is a response to a %s request" %
    out.println("<P>In this GET request, we see the following " +
          "header variables.</P>")

    for name in req.headerNames:
      out.println(name + " : " + req.getHeader(name) + "<br>")

      <P>The submit button below is part of a form that uses the
        "POST" method. Click on this button to do a POST request.

    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()))
  def doPost(self, req, res):
    out = res.getWriter()

    out.println(self.title % req.method)

    out.println("This was a %s<br><br>" % (req.getMethod(),))
    out.println('<br> back to <a href="get_post">GET</a>')
    out.println('<br><font size="-2">time accessed: %s</font>'
          % ctime(time()))

  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


Method: getAuthType()
Property name: AuthType

Returns a string (PyString) describing the name of the authentication type. The value is None if the user is notauthenticated.

Method: getContextPath()
Property name: contextPath

Returns a string (PyString) describing the path information that identifies the context requested.

Method: getCookies()
Property name: cookies()

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()
Property name: headerNames

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()
Property name: method

Returns the type of request made a string.

Method: getPathInfo()
Property name: pathInfo

All extra path information sent by the client.

Method: getPathTranslated()
Property name: pathTranslated

Returns the real path derived from extra path information in the client's request.

Method: getQueryString()
Property name: queryString

Returns the query string from the client's request (the string after the path).

Method: getRemoteUser()
Property name: remoteUser

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()
Property name: requestURI

Returns that segment of the between the protocol name and the query string.

Method: getServletPath()
Property name: servletPath

Returns the portion of the URL that designates the current Servlet.

Method: getSession()
Property name: session

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()
Property name: userPrincipal

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



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.


Returns a 1 or 0 depending whether the specified header.


Encodes a URL for the sendRedirect method. For version 2.1 and greater, use encodeRedirectURL instead.


Encodes a URL for the sendRedirect method.


Encodes a URL by including the session ID in it.


Sends an error using the status code.

sendError(sc, msg)

Sends an error using the specified status code and message.


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













































































  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020