Skip to main content.

Intro to Tomcat, Eclipse Web Tools Platform and Servlets

Goals

At the completion of this in-class work, you should be able to

Objective: Set Up

Objective: Installing Tomcat

We will install a Web application server, specifically Tomcat, on your computer.

Tomcat is updated frequently, so I'm just going to use * for the minor version number.

  1. Go to the Apache Tomcat homepage, click on the link for Tomcat 10 under the Download sidebar.
    Scroll down to 10.*, get the Binary Distribution for Core with the extension tar.gz. Put it into your cs335 directory.
  2. Move the tar.gz file into your cs335 directory, if you didn't in the last step.
  3. In your cs335 directory, extract the downloaded file using the command, e.g.,
    tar xfz apache-tomcat-10.*.tar.gz
    If you list the contents of your directory, you will see a directory named apache-tomcat-10.*
  4. You can delete apache-tomcat-*.tar.gz after it was extracted.

Objective: Running Tomcat

  1. Go into your Apache Tomcat directory.
  2. To start the web server (by default listening to port 8080), run the command
    bin/startup.sh
  3. Open another browser tab or window and enter the URL http://localhost:8080/. localhost is the standard host name provided to the address of the local computer, i.e., it's a hostname that refers to the current device.

    You should see an Apache Tomcat welcome page. This page is named index.jsp and is located in apache-tomcat-10.*/webapps/ROOT/

  4. To shutdown the web server, run the command
    bin/shutdown.sh
  5. If you reload the URL http://localhost:8080/, you should get an "Unable to Connect" error or a blank page.

Objective: Setting Up Tomcat for Use in Eclipse

Eclipse has development tools for web applications.

Start Eclipse (e.g., type eclipse in a terminal) and create a new workspace (perhaps in your cs335 directory, in a new directory called workspace). You should create a new workspace so that any configuration changes we make for this class do not affect your work in other workspaces.

Create a new Server to run your projects on.

  1. Under File → New → Other. Then, select Server, then Server.
    Click Next.

    In the wizard, you should now see a list of different types of servers.

  2. Select Apache → Tomcat v10.1 Server, then click "Next".
  3. Browse for the Tomcat installation directory (wherever you extracted Tomcat apache-tomcat-10.*).
  4. Click "Finish".

You should now have a "Servers" folder in the Project Explorer.

Objective: Setting Up a New Dynamic Web Project

There are slight variations in how this will be set up depending on your version of Eclipse. We will attempt to keep everyone's set up consistent.

  1. Under File → New → Dynamic Web Project.
  2. Name the project: First
  3. Make sure the Target Runtime is "Apache Tomcat v10.1".
  4. Make sure that the Dynamic web module version is 6.0
  5. Click "Next" and confirm that the source folder on the build path is src/main/java. If the source folder is src, "Remove" that folder and "Add Folder:" src/main/java
  6. Click "Next". For the Web Module, the Context root should be fine with the default, but the Content directory: should be src/main/webapp
  7. Click "Finish".

You should now have a new project folder called "First" in your Project Explorer window.

The content of the project will vary slightly depending on which version of Eclipse you use, but the content of the project should be something like:

Objective: Create an HTML File in Eclipse

Create an index.html file for this web application.

  1. Right click on "First" and select New → HTML File.
  2. This file should be in the src/main/webapp directory.
  3. Name the file index.html.
  4. Select "Finish". (If you pick "Next >" before clicking "Finish", it's to choose what version of HTML you'd like to use. The default should be html 5, so you can skip this step.

index.html should have opened in the editing window. index.html should also be in your src/main/webapp directory in the Project Explorer.

Now, spiffy up the index.html file:

  1. Modify the title to be "My First Servlets"
  2. Add the heading "My First Servlets" into the body of the page.
    Notice the auto-complete of the closing tag. This can be a little annoying at first until you get used to it, and then you'll be thankful that you don't need to remember to close tags.

Objective: Run Application on Tomcat

  1. Right-click on "First" and select "Run As" then "Run on Server".
  2. Select the "Tomcat v10.1" server from the list.
  3. Click Next.
  4. Make sure First is on the right side, meaning that the server will be configured to deploy it.
  5. Click "Finish".

You'll see things happening in the background and a new tab will pop up in Eclipse and maybe in Firefox. The tab should be your newly created index.html page (although the word index.html may not show up in the URL).

If you get an error message about ports being in use, make sure that you shut down your server through the command-line.

Depending on how Eclipse is set up, it may just open its browser. Eclipse's web browser is fairly simple. Instead, you should typically look at the web page within Firefox or Chrome by looking at the URL:
http://localhost:8080/First

Now, modify your index.html page to include a stylesheet:

  1. Select New → CSS File
  2. Name the style sheet first.css, put it in First/src/main/webapp and select "Finish".
  3. Add the style:
    body {
          font-family: sans-serif;
          font-size: 10pt;
          color: fuchsia;
    }
  4. Save the stylesheet.
  5. Modify your index.html page to use the stylesheet:
    <link rel="stylesheet" type="text/css" href="first.css"/>
    inside the <head> tag
  6. Reload your web page in your browser. Hopefully, your style changes will be reflected in the browser (a pinky-purple sans-serif font). If not, wait until you've added more content to the page.

Warning: If you are running Tomcat and Eclipse quits on you and you have trouble running an application on Tomcat after you restart Eclipse, shutdown Tomcat manually using the bin/shutdown.sh command we used earlier.

Objective: Creating a Form

  1. Create a new HTML5 page named form.html.
  2. Fill in a title and heading for the form.
  3. Add the following form to your page.
        <form action="SimpleServlet" method="get">
          <p>This submits a simple GET request to the server: 
          <input type="submit" value="Submit" />
          </p>
        </form>
    
  4. Add a link to this form from your index.html page
      <h2>Forms</h2>
    
      <ul>
        <li><a href="form.html">First Form</a></li>
      </ul>
    

Objective: Creating Your First Servlet

First, create the servlet file.

  1. Right click on First, and select New → Servlet.
  2. The project should should be filled in as First
  3. The Source folder should be filled in as /First/src/main/java
  4. The Java package should be named servlets (you don't want Java code to be in the default package)
  5. The Class name should be SimpleServlet
  6. The Superclass name should already be filled in as jakarta.servlet.http.HttpServlet
  7. Select Next a few times to see what some of your options are for in the future and finally select Finish. (If you click Next, there are some things you can configure, but we can use the defaults.)
  8. Next, fill in the code for the doGet method of the servlet from this file.

You may need to fix some compiler errors, such as importing the java.io.* classes. Follow Eclipse's recommendations.

If you have a bunch of compiler errors about the jakarta.* files, then make sure that the Server Runtime is in your class path. If not, configure the build path to add the Library, Server Runtime, Apache Tomcat 10.1.
  1. Reload your First index page in your browser. You should now see the link to the form.
  2. Click on the "Form" link
  3. Click on the button in your form.
  4. You should now see the response from your first servlet!
If you get a 404 error, restart your server by clicking on the server and hitting the play button.

Note: At this point, we're not worrying too much about how the response displays. We can add style sheets later.

Objective: Creating a Post Form

You just generated a GET request using a form. Now, generate a POST request with a form.

  1. In form.html, copy the form above, but modify the second form to use a POST method.
  2. Update other text to reflect that this form generates a POST request
  3. Bring up your index.html page in your browser.
  4. Click on the form link.
  5. Press the post button on the form.
  6. What happened? The default implementation that Eclipse gives the doPost method is to call the doGet method.

  7. In your servlet's doPost method, replace the call to doGet with the following
    response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Sorry, silly!");
    

What kind of response page do you get back?

You can send back different error messages by using fields defined in the HttpServletResponse interface--don't forget the inheritance rules!

PAUSE FOR LECTURE

Objective: Creating a Survey Servlet

The purpose of this servlet is to keep track of survey results in a file and display the results to a user after they've taken the survey. This servlet's behavior changes depending on the user's input.

  1. Create a new servlet named SurveyServlet in the servlets package.
  2. Then, replace the servlet's code with the code from this servlet.
  3. Examine the code to make sure you understand how it works.
  4. Create a new HTML file called pet.html (note: where should it be saved?) and copy this file's content into your file.
  5. Add a link to pet.html on your index.html page.
  6. Test the SurveyServlet using the pet.html form.
    • If you get a 404 error message, you may need to restart your server.

      Click on the Servers tab, click on the server, then press the play button to restart.

    • If you get an Access Denied error, it's probably because the default path for files in Java is not writeable by you. Instead of defining the file using the relative path, enter the full (absolute) path of where you want this file to go, e.g., save the file in your Eclipse project location.
  7. Now, modify SurveyServlet so that the table has column headings for Animal Name, % of Responses, and Number of Responses
  8. Finally, modify SurveyServlet so that the URL pattern survey maps to the SurveyServlet. Fix any compiler issues, as Eclipse suggests. If you make that change, how does pet.html need to change?

Demonstrate to me that your servlet is working before moving on.

Objective: Creating a Servlet that Displays Request Parameters

Next, you're going to create a servlet that prints out the data that it receives.

  1. Create a new HTML file named for_params.html.
  2. Copy the content of this file into your file.
  3. Create a link to for_params.html on your index.html page.
  4. Next, create a new servlet in the servlets package with the name ParametersServlet.
  5. Start filling in the doGet method with some of the code, as appropriate, from the SimpleServlet to generate an HTML document.
  6. Add code to print out all the data passed in, in the format:
    parametername: values

    For example, the output might look something like

    entree: crabcakes
    genre: action romance
    comments:
    member: yes

    Use appropriate methods from the HttpServletRequest class. (Recall that functionality can be inherited from the parent.)

  7. Test your servlet using the for_params.html form. Test it multiple times, ensuring that the output is what you expect. View the HTML source too, to see if it's what you thought.

    For example, what happens when you don't select any films? What happens if you select a bunch?

Demonstrate that your servlet is working to me before moving on.

  1. To make the servlet behave the same way to both post and get requests, modify the doPost method to call the doGet method with the appropriate arguments. (This was the default, but you might have made changes.)
  2. Then, modify for_params.html to perform a POST request instead of a GET request. Test that the servlet's behavior is the same, but note that the parameters are not in the URL.

You are now ready to begin Lab 4!