Create and Compile the Servlet Source Code
To begin, create a file named HelloServlet.java that contains the following program:
public class HelloServlet extend GenericServlet
public void service(ServletRequest request.
throws Servletexception IOException
response setContent Type(“text/html)
Printwriter pw = response.getwriter
First, note that this program imports the [avax.servlet package, which contains the classes and interfaces required. to build servlets, You will learn more about these classes and interfaces later in this chapter. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses. Inside HelloServlet, the service) method (which is inherited from Genericservlet) is overridden.This method~ handles requests from a client. Notice that the first argument is a ScrvletRcqucst objcct. This enables a servlet to read data that Is provided via the client request. Ute second argument is an ServletResponse object. This enables a servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html, which indicates that the browser should interpret the content as HTML source code.
Next, the gctWritcr() method obtains a printWriter. Anything written to this stream is sent to the client as part of the H1TP response. Then, println( ) is used to . write some simple HTML source code as the HTTP response Compile this source code and place cloSer vlct.class file in the directory named sdk2.0 examples. This ensures that it can be located by the servletrunner utility.