Monday, February 8, 2010

Creating a simple Servlet

The following link provides a good basic tutorial for making a servlet: A Hello World Servlet

When making the servlet in MyEclipse, start a new web project (I called mine ServletExample), then create the package: test, add the HelloServlet class to this package, and change the web.xml as required. Then it should work just fine.

For reference, the HelloServlet class is as follows:

package test;

import java.io.*;

import javax.servlet.http.*;
import javax.servlet.*;

public class HelloServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();

out.println("Hello, world!");
out.close();
}
}



The XML file is as follows:
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>test.HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

To run the servlet in MyEclipse, right click on the project and select Run-As MyEclipse Server Application.

You can then access the servlet by entering the following in the command line:
http://localhost:8080/ServletExample/hello

No comments:

Post a Comment

Solidworks macros eith ChatGPT

 Record a simple using thr Solidworks macro recorder, upload it to ChatGPT, and explain to ChatGPT how you want it changed:  https://youtu.b...