by November 10, 2000 1 comment

Java is a platform-independent language, that is the sameJava code can run on Windows, Linux, Mac, or any other platform withoutmodifications. You can use Java in a variety of ways–to build applets orfull-blown applications, or to create what are called servlets. Whereas Javaapplets are interpreted and executed on a client machine running a Java-enabledWeb browser, servlets run on the Web server.

Servlets provide the same functionality as CGI (CommonGateway Interface), ASP (Active Server Pages), server-side JavaScript, PHP, etc,and have the added benefit of being platform independent. These are normallyused when a Web request has to be processed at the Web server end. for example,when the contents of a submitted form have to be put into a database or file, orin case of search engines, where the search hits are calculated and displayed ina new HTML page.

Most popular Web servers like Apache, Netscape Enterprise Webservers, etc, have Java servlet support, either built-in or using third partyadd-ons. Also, servlets are not tied to a specific Web server, like ASP (ActiveServer Pages) for Internet Information Server and server-side JavaScript forNetscape’s Web server.

Servlets have advantages over CGI scripting too. CGI scriptsare generally implemented in Perl and C. A new process is created for eachrequest for the script’s execution, which has associated overheads, likeinitializing a new process space. A servlet, on the other hand, is initializedonly once, and each request corresponds to calling a service method and notcreating a new process. Servlets are a boon for Java programmers, as they don’thave to learn a new language like Perl or C for server-side scripting.

Here, we’ll take you through writing servlets to create adynamic HTML page, and a dynamic WML page.

Servlet starters

To start off, all you need is JDK 1.1 or above; Java ServletDevelopment Kit (JSDK) 2.1 ; and optionally, a Web Server with servlet supportto get a real taste of things. If you don’t have a Web server, theservletrunner program provided with JSDK is sufficient to test your servlets.Since this article was written before the release of JSDK 2.1, you’ll have tocheck the documentation to find out how to test the programs given here.

To start off, you have to set the classpath in autoexec.batto point to your JDK class files as well as JSDK class files in jsdk2.0\lib\jsdk.jar(you’ll find JSDK 2.0 on the PCQ May 2000 CD) as:

set classpath=;c:\jsdk2.0\lib\jsdk.jar

We’ve given a simple servlet program calledFirstServlet.java on this month’s CD in \cdrom\sorc_cod directory. We’llexplain this program here. Open it in a text editor, and you will be ready tostart.

Creating a dynamic HTML page

FirstServlet.java simply creates a dynamic HTML page thatdisplays "Hi, I’m your first JAVA SERVLET"

Let’s parse through the program to understand it better.Three packages are imported–javax.servlet, javax.servlet. http, and java.io.The first two are servlet packages and the third package, java.io is a set ofclasses which provide input/output methods. As you’ll see in the code, theFirstServlet class is extended to HttpServlet class–an abstract class–whichprovides the framework to handle HTTP requests.

A servlet initializes and starts with init( ) method. Thismethod takes a parameter, a ServletConfig object, and passes it to the superclass. This helps to save the object, so that it can be called by a child classlater. The line that does this is:

super.init(config);

Following init( ) are two methods–doGet( ) and doPost( ).If the servlet is called using a GET method, like by typing the URL of theservlet in the browser, the doGet( ) method is called. If the servlet is calledusing a POST method, like in the case of HTML forms, the doPost() method iscalled. In case of GET method, the key-value pair called query string is sentalong with the URL. In case of POST method, the key-value pair is a part of therequest body and is not appended along with the URL. To explain this in simpleterms, when you enter a query in a search engine, you’ll notice that yoursearch string is appended to the URL with a question mark–?–separator. Thisis an example of the Get method. The Post method is generally used when you’recreating an HTML form for submitting data to a database or a file. We’ll beusing both these methods to invoke the FirstServlet.

Both these methods accept two parameters–anHttpServletRequest object and an HttpServletResponse object. TheHttpServletRequest object encapsulates the information sent to the servlet bythe client (the browser) like content-type or key-value pairs, while theHttpServletResponse contains the information–generally a new HTML page–sentback to the client. In our case, we’ll generate an HTML page with a message.To do this, we must first set the content type as:

response.setContentType("text/html");

Then, we obtain a PrintWriter object from theHttpServletResponse object. This helps to deliver the dynamic HTML page to thebrowser. This is done as:

PrintWriter out = response.getWriter( );

After that, we send the required HTML tags using thePrintWriter object:

out.println("<html>");

out.println("<head>");

out.println("<title>My First Servlet</title>");

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

out.println("<body>");

out.println("<b>Hi, I’m your first JAVA SERVLET</b>");

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

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

Finally, close the stream as:

out.close();

You’ll also notice in the code that the init( ), doGet( ),and doPost( ) methods throw the ServletException. The doGet( ) and doPost( )throw the IOException. These are used in cases where an error occurs.

To run the servlet FirstServlet, first compileFirstServlet.java as:

javac FirstServlet.java

Place the class file FirstServlet.class in jsdk2.0\examples.

Now, change to jsdk2.0\bin directory and run servletrunnerprogram as:

start servletrunner

The servletrunner, by default, listens to port 8080.

Now, fire up your browser and enter the URL:

http://localhost:8080/servlet/[name of the class file]

In our case, this is:

http://localhost:8080/servlet/FirstServlet

This will call the doGet( ) method of the servlet and deliverthe HTML page to the browser. If you want to call the doPost( ) method, make anHTML file as follows:

<html>

<head>

<title>Testing doPost() method
</title>

</head>

<body>

<form action=http://localhost:8080/servlet/firstservletmethod=post>

<input type="submit">

</form>

</body>

</html>

Load this file in your browser and click the Submit button.You’ll see the same output as before, but this time you’ve invoked thedoPost( ) method. You can see this for yourself by adding a line:

out.println("<br><b>doPost( ) methodinvoked</b>");

before the line out.println("</body>"); inthe doPost( ) method. This will show you an additional line saying:

doPost( ) method invoked

Giving an alias to the servlet

You can also give a second name to your servlet–forexample, if it has a long name, you can give it a second, shorter one, to help you in your coding.

Edit the file servlet.properties (with a text editor) found in the directory jsdk2.0\examples to add a line:

servlet.fs.code=FirstServlet

This line is in the form:

servlet.[any name of servlet].code=[name of class file]

Here, you’re giving an alias (a second name)–fs in ourcase–to your servlet–FirstServlet.

Now fire up your browser and enter the URL:

http://localhost:8080/servlet/fs

where fs is the name given by you to the servlet in the servlet.properties file.

Creating a dynamic WML page

Java servlets can be used to create dynamic WML pages. The only important change is to set the content type as text/vnd.wap.wml, indicating that the delivered content is WML. This is done as follows:

response.set ContentType(“text/vnd. wap.wml”);

The code for this is in a file called FirstWmlServlet.java,which you’ll find on this month’s CD. Place the class file FirstWmlServlet.class in jsdk2.0\ examples. You can also give an alias to this servlet as described above.

To test this servlet, run the servletrunner program. You also need to have a WAP Phone simulator, which you can download from www.phone.com,www. nokia. com, or www.ericsson.com. In the simulator enter the URL:

http://localhost:8080/servlet/FirstWmlServlet

You’ll see a message “This is a servlet generated WMLpage” on the simulator’s display. Here, you’ve called the servlet’sdoGet( ) method. To see the doPost( ) method in action, in your text editorwrite a WML page as:

Press Enter to see the doPost() method in action

Now, load the WML page in the simulator from the local filesystem. This is generally done as:

file://[path to the wml file]

When you press Enter, you’ll see the message again.

You can tinker with the properties of servletrunner, like making it listen to a different port, making it look for the properties file (servlet.properties) in a different directory, etc. Refer to the servlet_ tutorial.html in the jsdk2.0\doc directory.

Next month, we’ll take you through database interfacing using JDBC (Java DataBase Connectivity) and session tracking using Java servlets.

Shekhar Govindarajan

1 Comment so far

Jump into a conversation
  1. wd
    #1 wd 4 November, 2016, 10:58

    hi there,
    unfortunately, my cd may-2000 issue of pcquest
    is damaged. how can I get it back? I want a
    horoscope program developed by dr. k. chaudhary
    in the indian section, dk chaudhary directory.
    Can you help me getting this program back?
    its a little program, if you would send me on
    my email mentioned then I will be obliged.
    thankyou.

    Reply this comment

Your data will be safe!Your e-mail address will not be published. Also other data will not be shared with third person.