advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Reviews : Java Books : Jython for Java Programmers :

Buy this book
Title: Jython for Java Programmers
ISBN: 0735711119
US Price: 49.99
© NewRiders Publishing

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.

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Microsoft Visual Studio 2010 Showcase
 Avaya Developer Showcase
 MSDN Spotlight
 PHP for Windows Showcase
XML error: undefined entity at line 39
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Windows 7: From Beta to Final Code in One Year
Google Shows Off Chrome OS, Releases Source
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?
Fedora 12 Takes Aim at Linux Networking
Top Supercomputer Nearly Doubles in Speed
Fedora 12 Linux Tackles Virtualization
Apple Gives iPhone Developers App Status Tracker
Novell Sets OpenSUSE 11.2 Free

Creating Custom Export Filters for StarOffice with XSLT
WPF Wonders: Using DataTemplates
Crystal Reports Family Offers Options for Developers
Avaya Aura Session Manager video
Avaya Aura Overview video
Exploring HTML 5's Audio/Video Multimedia Support
Overriding Virtual Functions? Use C++0x Attributes to Avoid Bugs.
Understanding the Cloud Computing Security Vulnerabilities
Cisco and IBM Target a Greener World
Upgrade to Visual Studio 2010 with the Ultimate Offer

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs