| |
 |
Figure 3: Your source and output configuration should look like this.
|
Creating a Servlet
Now to learn how to use the plugin, you'll create a simple "Hello World!" Servlet and deploy it to JBoss.
Put your source code (.java files) in a source folder and your compiled classes (.class files) in an output folder. Follow these steps to configure your source and output folders (Figure 3).
- Right-click on your project in the Package Explorer.
- Go to Properties—>Java Build Path.
- Click on the Source tab.
- Click on Add Folder.
- Click on Create New Folder.
- Set the folder name to "src".
- Select Yes when it asks you to remove the project as a source folder and to create a "bin" folder.
Next, you need to set your CLASSPATHby defining the libraries (JAR files) that Eclipse should use to compile your code. You also need to add a JAR file that will allow you to compile a Servlet. Luckily, Eclipse comes equipped with a Tomcat plugin, which contains the library you will need you to compile a servlet.
| |
 |
Figure 4: This is how your libraries (CLASSPATH) should appear after adding the servlet.jar.
|
Follow these steps (see Figure 4):
- Click on the Libraries Tab (while still under Properties—>Java Build Path).
- Click Add Variable.
- Select ECLIPSE_HOME and click Extend.
- Navigate to the plugins/org.eclipse.tomcat.4.1.x directory.
- Select servlet.jar and click OK.
- Click OK to exit the properties dialog.
Now, create a class called HelloWorldSerlvet in the com.devx.examplepackage, using the following code in your servlet:
package com.devx.example;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet
{
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ServletOutputStream out = response.getOutputStream();
out.println("<html><body><h1>Hello World!</h1></body></html>");
}
}
| |
 |
Figure 5: This is how the project structure looks after creating all the necessary files.
|
Next, you need a deployment descriptor so that JBoss will know how to access your Servlet. The deployment descriptor (web.xml) goes under a folder called WEB-INF in the .war file. Create a folder under src called WEB-INF. Then, create a file called web.xmlin that folder, using the following source.
<!DOCTYPE web-app PUBLIC
'-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN'
'http://java.sun.com/j2ee/dtds/web-app_2.2.dtd'>
<web-app>
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>com.devx.example.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>
After all is said and done, your project structure should look like Figure 5.