Your First Web Project with Eclipse & Tomcat

Requirements:

Following the “For Newbies” line I will explain in this short post a quick way to create your first Java Web Project using Eclipse as IDE and Tomcat as web server. In this case we will not use one of those “Super Wizards” that automatically by “magic” creates everything we need.

1. First we have to create our Java Project

File → New → Java Project

2.Now let's create a simple class that will be invoked in our JSP code.

Right click on “src” folder ->New → class

  1. package newbie;
  2.  
  3. public class HolaMundo {
  4.  
  5. public static getHola() {
  6. return "Hola From Costa Rica, Pura Vida!!!";
  7. }
  8. }

3. It's time to create the WebContent folder structure. For this simple case we will create this structure:

HolaMundo
+WebContent
++ pages
++ WEB-INF

4. Inside WEB-INF we will add a file named “web.xml”. By the moment we will leave it very simple but in the future, as project grows, it will be used to add more settings to web project.

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<!--> More Settings Here <-->

</web-app>

5.Inside pages folder we will add a JSP file named “HolaMundo.jsp”:

<%@ page import="newbie.HolaMundo" %>
<%
String message = HolaMundo.getHola();
%>
<h1><%=message%></h1>

The JSP code basically includes our Java class and displays the “getHola()” returned String.

6. Before setting our Tomcat we need to configure our build path. By default Eclipse sets the output folder (where “*.class” for each “*.java” are stored) in “<project_name>/bin”. Since our project is web based, we need to move the path to:

“HolaMundo/WebContent/WEB-INF/classes”

Right Click on Project ->Build Path-> Configure Build Path... → Source Tab

7.The last step is to configure out Tomcat. The easiest way is to simple open “server.xml” file located at:

<Tomcat Installation>\conf\server.xml

and add the following line between “<Host> </Host>” tags:

<Context path="/HolaMundo" reloadable="false" docBase="E:\HolaMundo\WebContent" />

The “path” attribute is a virtual path that points to our project indicated in “docBase” attribute.

If everything was done correctly we just need to start our Tomcat. It is recommended to install a Tomcat Launcher Plugin to our Eclipse to facilitate this common task.

Normally Tomcat runs on port 8080:

Attachment Size
56.66 KB
51.33 KB
34.55 KB