Skip to main content.

Goals

To prepare you for Lab 3, at the completion of this in-class work, you should be able to

Objective: Set Up

Objective: Installing Tomcat

For this objective, we will install a Web application server, specifically Tomcat.

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

  1. Copy /csdept/courses/cs335/handouts/apache-tomcat-8.*.tar.gz OR go to the Apache Tomcat homepage, click on the link for Tomcat 8 under the Download sidebar.
    Scroll down to 8.5.*, 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. Extract the downloaded file using the command
    tar xfz apache-tomcat-8.*.tar.gz
    If you list the contents of your directory, you will see a directory named apache-tomcat-8.*
  4. 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/.

    You should see an Apache Tomcat welcome page. This page is named index.jsp and is located in apache-tomcat-8.*/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 (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 v8.5 Server, then click "Next".
  3. Browse for the Tomcat installation directory (which should be /home/students/yourusername/cs335/apache-tomcat-8.*).
  4. Click "Finish".

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

Objective: Setting Up a New Dynamic Web Project

  1. Under File → New → Dynamic Web Project.
  2. Name the project: FirstServlets
  3. Make sure the Target Runtime is "Apache Tomcat v8.5".
  4. Click "Finish".

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

The content of the project is:

Objective: Create an HTML File in Eclipse

Create an index.html file for this web application.

  1. Right click on "FirstServlets" and select New → HTML File.
  2. This file should be in the FirstServlets/WebContent 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 WebContent 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 will 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 "FirstServlets" and select "Run As" then "Run on Server".
  2. Select the "Tomcat v8.5" from list.
  3. Click Next.
  4. Make sure FirstServlets 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.

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/FirstServlets

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

  1. Select New → Other → Web → CSS.
  2. Name the style sheet first.css, put it in FirstServlets/WebContent 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 HTML page named form.html, with the same format as before.
  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 FirstServlets, and select New → Servlet.
  2. The project should should be filled in as "FirstServlets"
  3. The source folder shoul be filled in as "/FirstServlets/src"
  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 "javax.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.)

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 javax.* 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 8.5.
  1. Reload your FirstServlets index page in your browser. You should now see the updated text.
  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.

What happened? The default implementation that Eclipse gives the doPost method is to call the doGet method.

In your servlet's doPost method, replace the call to do get 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.


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 the pet.html document from your index.html page.
  6. Test the SurveyServlet using the pet.html form.
  7. If you get a 404 error message, you may need to restart your server.

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

  8. Now, modify SurveyServlet so that the table has column headings for Animal Name, % of Responses, and Number of Responses

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. Copy this file in your FirstServlets/WebContent directory.
  2. Create a link to for_params.html on your index.html page.
  3. Next, create a new servlet in the servlets package with the name ParametersServlet.
  4. Start filling in the doGet method with some of the code, as appropriate, from the SimpleServlet to generate an HTML document
  5. Add code to print out 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.

  6. 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.

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.

Then, modify for_params.html to perform a POST request instead of a GET request. Test that the servlet's behavior is the same.

You are now ready to begin Lab 3!