Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 559825
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T12:16:43+00:00 2026-05-13T12:16:43+00:00

After several hours of working on porting this program over, it appears to finally

  • 0

After several hours of working on porting this program over, it appears to finally be in a working state. However, I was wondering if anyone knew of a better way or more complete way of porting Java servlets over into Python. The beginning of the Python script contains a lot of support code to make it easier to port the program line-by-line directly into Python. Does anyone know of a better way to go about this?


Java

// --------------------------------------------------------
// File: Hello.java
// Description: A simple "Hello World" servlet
// --------------------------------------------------------

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import sun.servlet.http.HttpServer;

public class Hello extends HttpServlet {

  int count;

  public void service(HttpServletRequest request, 
         HttpServletResponse response) throws ServletException, IOException {

    // setup response

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    // send response

    out.println("<html><body>");
    out.println("<h5>Stephen Paul Chappell (SPC)</h5>");
    out.println("<h5>:) (ZTD) Zero The Dragon :(</h5>");
    String name = request.getParameter("NAME");
    if (name != null && !name.equals("")) {
      out.println("<h2>Hello, " + name + "</h2>");
    } else {
      out.println();
      if (name != null && name.equals("")) {
        out.println("  <h2>You didn't enter your name. Please enter your name. </h2>");
      } else {
        out.println("  <h2>What's your name? </h2>");
      }
      out.println("  <hr>");
      out.println("  <form action=\"http://127.0.0.1:8080/servlet/Hello\">");
      out.println();
      out.println("    Enter your name: <input type=\"text\" name=\"NAME\" value=\"Fred\"><br>");
      out.println("    <input type=\"submit\" value=\"Click for greeting\">");
      out.println();
      out.println("  </form>");
    }
    String color = request.getParameter("FAVCOLOR");
    if (color != null) {
      out.println("<h2>Why, " + color + " is my favorite color too!</h2>");
    }

    count++;
    out.println("This page has been hit " + count + " time(s).");

    out.print("</body></html>");
  }

  // start web server
  public static void main(String[] args) throws Exception {
    HttpServer.main(args);
  }
}

Python

import urllib.parse
import http.server
import cgitb
import sys
import io

################################################################################

class HttpServlet(http.server.BaseHTTPRequestHandler):

    __debug = False

    @staticmethod
    def debug(value):
        HttpServlet.__debug = value

    def do_GET(self):
        if self.path == '/favicon.ico':
            self.send_error(404)
            return
        request = HttpServletRequest(self.path)
        response = HttpServletResponse()
        try:
            self.service(request, response)
        except Exception:
            if HttpServlet.__debug:
                self.send_response(500)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                klass, value, trace = sys.exc_info()
                html = cgitb.html((klass, value, trace.tb_next))
                self.wfile.write(html.encode())
            else:
                self.send_error(500)
        else:
            self.send_response(200)
            self.send_header('Content-type', response._type)
            self.end_headers()
            self.wfile.write(response._value)

    def service(self, request, response):
        raise NotImplementedError()

################################################################################

class HttpServletRequest:

    def __init__(self, path):
        query = urllib.parse.urlparse(path).query
        self.__dict = urllib.parse.parse_qs(query, True)

    def getParameter(self, name):
        return self.__dict.get(name, [None])[0]

################################################################################

class HttpServletResponse:

    def __init__(self):
        self.__content_type = 'text/plain'
        self.__print_writer = PrintWriter()

    def setContentType(self, content_type):
        self.__content_type = content_type

    def getWriter(self):
        return self.__print_writer

    @property
    def _type(self):
        return self.__content_type

    @property
    def _value(self):
        return self.__print_writer.getvalue().encode()

################################################################################

class PrintWriter(io.StringIO):

    print = io.StringIO.write

    def println(self, string):
        self.write(string + '\r\n')

################################################################################

class HttpServer(http.server.HTTPServer):

    @staticmethod
    def main(RequestHandlerClass, port=80):
        server = HttpServer(('', port), RequestHandlerClass)
        socket = server.socket.getsockname()
        print('Serving HTTP on', socket[0], 'port', socket[1], '...')
        try:
            server.serve_forever()
        except KeyboardInterrupt:
            print('Keyboard interrupt received: EXITING')
            server.server_close()

################################################################################
################################################################################

## ---------------------------------------------------------
## File: Hello.py
## Description: A simple "Hello World" servlet
## ---------------------------------------------------------

class Hello(HttpServlet):

    count = 0

    def service(self, request, response):

        # Setup for a response.
        response.setContentType('text/html')
        out = response.getWriter()

        # Send an appropriate response.
        out.println('''\
<html>
    <head>
        <title>Java to Python servlet</title>
    </head>
    <body>
        <h5>Stephen Paul Chappell (SPC)</h5>
        <h5>:) (ZTD) Zero The Dragon :(</h5>''')
        name = request.getParameter('NAME')
        if name:
            out.println('''\
        <h2>Hello, {}!</h2>'''.format(name))
        else:
            if name == '':
                out.println('''\
        <h2>You did not enter your name.</h2>
        <h3>Please enter your name.</h3>''')
            else:
                out.println('''\
        <h2>What is your name?</h2>''')
            out.println('''\
        <form>
            <fieldset>
                <legend>About Yourself</legend>
                <label for='NAME'>Enter your name:</label>
                <input id='NAME' name='NAME' type='text' value='John Doe' />
                <br />
                <input type='submit' value='Click me!' />
            </fieldset>
        </form>''')
        color = request.getParameter('FAVCOLOR')
        if color:
            out.println('''\
        <h2>Why, {} is my favorite color too!</h2>'''.format(color))

        Hello.count += 1
        out.println('''\
        This page has been hit {} times.'''.format(Hello.count))

        out.print('''\
    </body>
</html>''')

# Start the web server.
def main():
    HttpServlet.debug(True)
    HttpServer.main(Hello)

################################################################################

if __name__ == '__main__':
    main()

In case anyone is wondering what the purpose of this project is, the original Java program was given as an introductory exercise in freshman-level computer-science course. Since then, it has been about six years since I have worked with Java and am going through the old programs, porting them over to Python for the challenge and learning experience. Porting the servlets are presenting extra difficulties.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T12:16:44+00:00Added an answer on May 13, 2026 at 12:16 pm

    Not a direct answer but, any good reason to not use something like Webware which offers, among other features (see the Overview):

    • Servlets. Similar to Java servlets, they provide a familiar basis for construction web applications.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This should be relatively easy to do, but after several hours straight programming my
After several hours of frustration I finally turned to the internet for the answer.
So, after several hours of reading the Apple walkthrough I finally managed to deploy
After several hours of tinkering I cannot seem to figure this out. I have
coming back to postgresql after several years of oracle ... what are the state-of-the
I'm working with someone who's looking to get back into programming after several years
I am so frustrated right now after several hours trying to find where shared_ptr
I'm running a java program on many computers that interact between them. After several
I'm trying to write some custom Facelets 2.0 tags, after several hours work, I
After several hours test, in iOS 4.0 and above I found if I draw

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.