Intro to Tomcat, Eclipse Web Tools Platform and Servlets
Goals
At the completion of this in-class work, you should be able to
- Install and run Tomcat
- Set up Tomcat for use within Eclipse
- Use Eclipse to develop basic server-side web applications
- Create basic servlets, deploy them in Tomcat, and access them from a web browser.
Objective: Set Up
- On a lab machine, run the command labhelp so that you can request help without raising your hand.
- On your own machine OR the lab machine, if you haven't already, create a
cs335
directory to organize your code for this class (not your public_html directory). - If you haven't already, install Java on your machine. Get the JDK 21 LTS version.
- If you haven't already, install the Enterprise version of Eclipse on your machine. First download/install the Eclipse installer. When you run the installer, select the Eclipse IDE for Enterprise Java and Web Developers version of Eclipse.
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.
- 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 yourcs335
directory. - Move the
tar.gz
file into yourcs335
directory, if you didn't in the last step. - 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 namedapache-tomcat-10.*
- You can delete apache-tomcat-*.tar.gz after it was extracted.
Objective: Running Tomcat
- Go into your Apache Tomcat directory.
- To start the web server (by default listening to port 8080), run
the command
bin/startup.sh - 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 inapache-tomcat-10.*/webapps/ROOT/
- To shutdown the web server, run the command
bin/shutdown.sh - 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.
- 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.
- Select Apache → Tomcat v10.1 Server, then click "Next".
- Browse for the Tomcat installation directory (wherever you
extracted Tomcat
apache-tomcat-10.*
). - 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.
- Under File → New → Dynamic Web Project.
- Name the project: First
- Make sure the Target Runtime is "Apache Tomcat v10.1".
- Make sure that the Dynamic web module version is 6.0
- Click "Next" and confirm that the source folder on the build
path is
src/main/java
. If the source folder issrc
, "Remove
" that folder and "Add Folder:
" src/main/java - Click "Next". For the Web Module, the Context root should be
fine with the default, but the
Content directory:
should be src/main/webapp - 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:
Deployment Descriptor
- configuration for your web applicationJAX-WS Web Services
- for use with XML Web ServicesJava Resources
- where the Java source code can be viewed, organized into packagessrc
- withinsrc
ismain
. Withinmain
is/will be:java
- contains the source directory for your Java code. This is just another view into the Java source code, through files -- where the packages just look like folders. You'll view the Java code through Java Resources more often.webapp
- contains the web application's HTML and CSS files and information about the web application in the META-INF and WEB-INF directories.
Depending on how old your Eclipse is (the difference could just be a couple months), this might not be how your project is set up. Instead, you could have a
WebContent
or similar directory.Also, note that you may have two views into the Java code -- as Java code from the Source Folder (where code will be organized into packages) vs as files (so the packages will just look like folders).
build
- where the generated class files are stored
Objective: Create an HTML File in Eclipse
Create an index.html
file for this web
application.
- Right click on "First" and select New → HTML File.
- This file should be in the
src/main/webapp
directory. - Name the file
index.html
. - 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:
- Modify the title to be "My First Servlets"
- 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
- Right-click on "First" and select "Run As" then "Run on Server".
- Select the "Tomcat v10.1" server from the list.
- Click Next.
- Make sure
First
is on the right side, meaning that the server will be configured to deploy it. - 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).
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:
- Select New → CSS File
- Name the style sheet
first.css
, put it inFirst/src/main/webapp
and select "Finish". - Add the style:
body { font-family: sans-serif; font-size: 10pt; color: fuchsia; }
- Save the stylesheet.
- Modify your
index.html
page to use the stylesheet:<link rel="stylesheet" type="text/css" href="first.css"/>
inside the<head>
tag - 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.
bin/shutdown.sh
command we used earlier.
Objective: Creating a Form
- Create a new HTML5 page named
form.html
. - Fill in a title and heading for the form.
- 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>
- 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.
- Right click on First, and select New → Servlet.
- The project should should be filled in as
First
- The
Source folder
should be filled in as/First/src/main/java
- The
Java package
should be named servlets (you don't want Java code to be in the default package) - The
Class name
should be SimpleServlet - The Superclass name should already be filled in as
jakarta.servlet.http.HttpServlet
- Select
Next
a few times to see what some of your options are for in the future and finally selectFinish
. (If you clickNext
, 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.
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.
- Reload your First index page in your browser. You should now see the link to the form.
- Click on the "Form" link
- Click on the button in your form.
- You should now see the response from your first servlet!
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.
- In
form.html
, copy the form above, but modify the second form to use aPOST
method. - Update other text to reflect that this form generates a POST request
- Bring up your index.html page in your browser.
- Click on the form link.
- Press the post button on the form.
- In your servlet's
doPost
method, replace the call todoGet
with the followingresponse.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Sorry, silly!");
What happened? The default implementation that
Eclipse gives the doPost
method is to call
the doGet
method.
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.
- Create a new servlet named
SurveyServlet
in theservlets
package. - Then, replace the servlet's code with the code from this servlet.
- Examine the code to make sure you understand how it works.
- Create a new HTML file called
pet.html
(note: where should it be saved?) and copy this file's content into your file. - Add a link to
pet.html
on yourindex.html
page. - Test the
SurveyServlet
using thepet.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.
- Now, modify
SurveyServlet
so that the table has column headings for Animal Name, % of Responses, and Number of Responses - Finally, modify
SurveyServlet
so that the URL patternsurvey
maps to theSurveyServlet
. Fix any compiler issues, as Eclipse suggests. If you make that change, how doespet.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.
- Create a new HTML file named
for_params.html
. - Copy the content of this file into your file.
- Create a link to
for_params.html
on yourindex.html
page. - Next, create a new servlet in the
servlets
package with the nameParametersServlet
. - Start filling in the
doGet
method with some of the code, as appropriate, from theSimpleServlet
to generate an HTML document. - Add code to print out all the data passed in, in the format:
parametername: valuesFor example, the output might look something like
entree: crabcakes
genre: action romance
comments:
member: yesUse appropriate methods from the HttpServletRequest class. (Recall that functionality can be inherited from the parent.)
- 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 thedoGet
method with the appropriate arguments. (This was the default, but you might have made changes.) - 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!