February 19, 2011

Servlets - Hello World Example

Create a HelloServlet.java source file in the src folder,

HelloServlet.java

package info.icontraining.servlets;

import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;

public class HelloServlet extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
      PrintWriter out = response.getWriter();
      out.println("Hello World");
      out.close();
   }
}

In the WebContent/WEB-INF/web.xml configuration file, add the following configuration,

web.xml

<servlet>
   <servlet-name>helloServlet</servlet-name>
   <servlet-class>info.icontraining.servlets.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
   <servlet-name>helloServlet</servlet-name>
   <url-pattern>/hello</url-pattern>
</servlet-mapping>


Now access the servlet from a browser, typing the following URL,

http://localhost:8080/WebAppName/hello

No comments:

Post a Comment