Beginning Servlets :

Servlets are an underlying technology behind JavaServer Pages. Because of the close relationship, it's useful to learn something about servlets. Understanding servlets will help you in your study of JSPs by helping you understand what is going on under the hood. Even if you do most of your work with JSPs, you will be more effective at writing JSPs and debugging problems if you can understand the servlet code. In addition, JSPs and servlets have distinct and complementing roles in Web applications. More often than not, you will find yourself using a combination.

Servlets allow the programmer to work directly with requests made to a Web server and to form responses that include content that is returned to a client. Unlike JSPs, which are oriented toward presentation, with their combination of HTML and scriptlets or other elements, servlets are composed entirely with Java. As you might expect, servlets are great for performing lower-level functions that work with data or implement business models

Listing 2.1 Source Code for HelloWorldServlet.java

package examples;

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class HelloWorldServlet extends HttpServlet

{

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws IOException

{

// Tell the Web server that the response is HTML.

response.setContentType("text/html");

// Get the PrintWriter for writing out the response.

PrintWriter out = response.getWriter();

// Write the HTML back to the browser.

out.println("<html>");

out.println("<body>");

out.println("<h1>Hello World!</h1>");

out.println("</body>");

out.println("</html>");

}

}

compile the servlet class at your project classes directory and the add the following codes to the web.xml file.

My project classes directory is:

C:\Program Files\Apache Software Foundation\Tomcat 5.0\server\webapps\Hello\WEB-INF\classes

Hello is my project directory name.

My web.xml resides on:

C:\Program Files\Apache Software Foundation\Tomcat 5.0\server\webapps\Hello\WEB-INF

The web.xml file contains these codes.

<web-app>

<servlet>

<servlet-name>ShowParameters</servlet-name>

<servlet-class>ShowParameters</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ShowParameters</servlet-name>

<url-pattern>/show</url-pattern>

</servlet-mapping>

</web-app>

Now run the servlet using the url:

http://localhost:8080/Hello/show