Lab Setting Up a Servlet Project with Apache Tomcat OCT 18
This starter level lab simplifies the process by:
Removing the use of Maven, which can be complex for beginners.
Providing a simpler project structure.
Including "Quick Check" steps after each major action to give immediate feedback.
Simplifying the deployment process by directly copying files to Tomcat's webapps directory.
HAND IN: A word Document with all code and screen shots demonstrating the successfuly operation of this illustration of how Java Sockets work, uploaded to the Moodle Assigment Page.
Due December 15.
Lab: Setting Up a Servlet Project with Apache Tomcat (Simplified for New Learners)
## Preamble: What You'll Achieve
Before we dive into the step-by-step process, let's take a moment to understand what you'll accomplish by the end of this lab.
**Your Goal:**
You're going to create a simple web application using Java servlets and Apache Tomcat. Here's what the finished product will look like:
1. **Project Structure:**
You'll have a project folder named `MyServletProject` with the following structure:
```
MyServletProject/
├── WEB-INF/
│ ├── classes/
│ │ └── HelloServlet.class
│ └── web.xml
└── HelloServlet.java
```
2. **Functionality:**
Your application will have a single servlet that responds to web requests.
When you navigate to the servlet's URL in a web browser, you'll see a webpage that says "Hello from my first servlet!"
3. **How It Runs:**
- You'll start the Tomcat server on your local machine.
- Then, you'll open a web browser and go to `http://localhost:8080/MyServletProject/hello`.
- The browser will display a simple HTML page with the message "Hello from my first servlet!"
4. **Behind the Scenes:**
- Your Java code (HelloServlet.java) will be compiled into a class file.
- Tomcat will use this class file to create a servlet.
- When you access the URL, Tomcat will execute your servlet code and send the result back to the requesting browser.
By completing this lab, you'll have taken your first steps into the world of Java web development.
You'll understand:
- the basics of how servlets work,
how to set up a simple web application, and
how to use Tomcat to run your application.
Now, let's get started on building this application step by step!
Lab: Setting Up a Servlet Project with Apache Tomcat (Simplified for New Learners)
## Objective
By the end of this lab, you will have set up a basic servlet project using Apache Tomcat and created a simple servlet that responds to HTTP requests.
You'll get quick feedback at each step to ensure you're on the right track.
## Prerequisites
- Java Development Kit (JDK) 8 or later installed
- Basic understanding of Java programming
## Steps
1. Install Apache Tomcat
1. Visit the Apache Tomcat website: https://tomcat.apache.org/
2. Download Tomcat 9.x for your operating system.
3. Extract the downloaded archive to a directory of your choice (e.g., `C:\tomcat` on Windows or `/opt/tomcat` on Linux/macOS).
**Quick Check:** Open a command prompt/terminal and navigate to your Tomcat's `bin` directory.
Run `catalina.bat version` (Windows) or `./catalina.sh version` (Linux/macOS). You should see Tomcat's version information.
Based on the search results, here are the key points about setting the CATALINA_HOME environment variable correctly:
1. CATALINA_HOME should be set to the root directory of your Tomcat installation[1][3]. For example:
2. The CATALINA_HOME directory should contain subdirectories like bin, webapps, lib, etc.[1]
3. Setting CATALINA_HOME is required for Tomcat to run properly. Many Tomcat files and configurations reference this variable[4].
4. To set CATALINA_HOME permanently on Windows:
- Open Control Panel > System > Advanced > Environment Variables[6]
- Add a new system variable named CATALINA_HOME
- Set its value to your Tomcat installation directory
5. Alternatively, you can set it temporarily in a command prompt before running Tomcat[4]:
```
set CATALINA_HOME=C:\path\to\tomcat
```
6. Make sure the path does not contain spaces or use quotes if it does[1].
7. After setting CATALINA_HOME, you can start Tomcat using:
```
%CATALINA_HOME%\bin\startup.bat
```
8. If you still get an error about CATALINA_HOME not being set, double check that:
- The environment variable is spelled correctly
- The path actually exists and contains the Tomcat files
- You've restarted your command prompt after setting the variable
By properly setting CATALINA_HOME to point to your Tomcat installation directory, you should resolve the error and be able to run Tomcat successfully.
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Hello Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello from my first servlet!</h1>");
out.println("</body>");
out.println("</html>");
}
}
}
```
**Quick Check:**
If you've created the file successfully, you should be able to open and view its contents in a text editor.
4. Compile the Servlet
jar = java archive resource file (zip file format)
1. Open a command prompt/terminal in your `MyServletProject` directory.
2. Set the `CLASSPATH` to include Tomcat's servlet-api.jar:
- Windows: `set CLASSPATH=C:\path\to\tomcat\lib\servlet-api.jar;.`
- Linux/macOS: `export CLASSPATH=/path/to/tomcat/lib/servlet-api.jar:.`
set CLASSPATH=C:\apache-tomcat\lib\servlet-api.jar
You could also use the -cp flag and point to your class path directory
-cp C:\apache-tomcat\lib
3. Compile the servlet:
The `-d` flag in the `javac` command specifies the destination directory for the compiled class files.
In the command `javac -d WEB-INF/classes HelloServlet.java`:
- `-d` is the flag that tells the Java compiler where to put the output files
- `WEB-INF/classes` is the destination directory where the compiled `.class` files will be placed
- `HelloServlet.java` is the source file to be compiled
This command will compile the `HelloServlet.java` file and place the resulting `HelloServlet.class` file in the `WEB-INF/classes` directory.
This is particularly important in web application development because the `WEB-INF/classes` directory is a standard location where servlet containers like Tomcat look for compiled Java classes.
It's a good practice to always compile your servlet classes into this directory to ensure that your web application follows the expected structure and that the servlet container can find and load your classes correctly.
Would you like me to provide more information about the Java compilation process or the structure of Java web applications?
javac -d WEB-INF/classes HelloServlet.java
```
Quick Check: If compilation is successful, you should see no errors, and a `HelloServlet.class` file should appear in the `WEB-INF/classes` directory.
5. Configure the Web Application
1. In the `WEB-INF` directory, create a file named `web.xml` with the following content:
**Quick Check:** Verify that the `web.xml` file is in the correct location and contains the content above.
6. Deploy the Application to Tomcat
1. Copy your entire `MyServletProject` directory to the `webapps` directory in your Tomcat installation.
**Quick Check:** You should now have a directory structure like this in your Tomcat installation:
```
tomcat/
└── webapps/
└── MyServletProject/
├── WEB-INF/
│ ├── classes/
│ │ └── HelloServlet.class
│ └── web.xml
└── HelloServlet.java
```
7. Start Tomcat and Test the Servlet
1. Start Tomcat:
- Windows: Run `C:\path\to\tomcat\bin\startup.bat`
- Linux/macOS: Run `/path/to/tomcat/bin/startup.sh`
2. Open a web browser and navigate to `http://localhost:8080/MyServletProject/hello`
**Quick Check:** You should see the message "Hello from my first servlet!" displayed in your browser. If you see this, congratulations! Your servlet is working correctly.
Conclusion
Congratulations! You have successfully set up a basic servlet project using Apache Tomcat.
This lab has covered the essential steps of
creating a servlet,
configuring the web application,
and deploying it to Tomcat,
with quick checks at each stage to ensure you're on the right track.
## Further Exploration
- Try modifying the `HelloServlet.java` file to display a different message, then recompile and refresh your browser to see the changes.
Lab Part 2: Create a simple HTML form that submits data to your servlet and modify the servlet to display the submitted data.
Adding Form Handling to Your Servlet
## Step 1: Create an HTML Form
1. In your `MyServletProject` directory, create a new file named `index.html` with the following content:
public class HelloServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Hello Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello from my first servlet!</h1>");
out.println("<p>Use the form in index.html to submit your name.</p>");
out.println("</body>");
out.println("</html>");
}
}
This configuration sets `index.html` as the welcome file, which means it will be displayed when accessing the root of your application.
## Step 5: Deploy and Test
5. If you haven't already, copy your entire `MyServletProject` directory to Tomcat's `webapps` directory.
6. Start (or restart) Tomcat.
7. Open a web browser and go to `http://localhost:8080/MyServletProject/`
8. You should see the form asking for your name. Enter a name and submit the form.
9. The servlet should respond with a personalized greeting using the name you entered.
## Explanation
- The HTML form sends a POST request to the "/hello" URL when submitted.
- The `doPost` method in the servlet handles this POST request.
- `request.getParameter("username")` retrieves the value entered in the form field named "username".
- The servlet then generates an HTML response that includes the submitted name.
This example demonstrates how servlets can handle form submissions and generate dynamic responses based on user input.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (