Servlets


What are Servlets?

The following are the basic steps of using servlets:

•    The client makes a request.
•    The Web server forwards the request to the servlet after receiving it from the client.
•    Some kind of process is done by the servlet after receiving the HTTP request.
•    A response is returned back to the web server from the servlet.
•    The web server will forward the response to the client.

Why use servlets Instead of CGI?

CGI makes separate process for each request but servlet can't make separate process.

• What are the requirements for writing Servlets?

Install JavaSoft’s Java Servlet Development Kit (JSDK). Set the environment variable CLASSPATH, to the required location so that your servlets can find the servlet packages.

The following setting has to be made for Windows 95 and NT systems, with the JSDK installed in the default location:
set CLASSPATH=%CLASSPATH%;C:\Program Files\JSDK\lib\Classes.zip

To run Servlets you need a Web server that supports the Servlet API. The following steps are required to run any servlet:
•    If your Web server is not running, start it.
•    Configure the Web server to install the servlet.
•    Run your Web browser.
•    Direct the browser to the particular URL that refers to the new servlet.

For example, a URL that refers to the servlet is of the form:

http://host-name:port/servlet/servlet-name?request-query-string

The Java Web Server

The Java Web Server known as Jeeves is JavaSoft’s Web server, which supports the use of servlets.  This Web Server is written in the Java language and it is not a part of JDK distribution.

•   Configuring Java Web Server for Servlets

The administration tool is invoked by accessing the administration port of the server with a Java enabled Web browser. The Java Web Server administration tool is installed on port 9090. In order to invoke this tool, you can use the following URL: http://localhost:9090/index.html

The following fields are displayed on the servlet-loading view, which are used for configuring:

Name: This is the name assigned to the server. It need not be the name of the servlet class.

Description: It describes the servlet in brief. It is only used from within the Web service.

Class Name: It defines the Java class name for the servlet, including the package name.

Arguments: It defines the list of arguments to be passed to the servlet.

The arguments should be given in the following format:  key=value
Load at Startup: This indicates whether the servlet should be loaded automatically when the server starts.

Loaded Now: This indicates whether the servlet is currently loaded. This field can be used to load and unload the servlet.

Load Remotely: This indicates whether the Web service should load the servlet from a remote location.

Class File URL: This indicates the URL of the remote servlet class.

The other way of configuring the Java Web Server for servlets is by changing the properties defined in the configuration file called servlets.properties available in the admin\properties\process\javawebserve \adminservice directory.

To define a servlet in this file, use the following form:

servletname.code=classname

The default code base of a servlet is the servlets directory but it can be overridden by an entry in the following form:

servletname.codebase=URL

The arguments to the servlets can be specified by an entry in the following form:

servletname.initArgs=comm_separated_list

To configure the servlets.properties file for running a servlet named TestServlet defined in a class called Test, you have to  enter the following lines in the file servlets.properties:

TestServlet.code=Test
TestServer.codebase=http://localhost:8080/servlet
TestServer.initArgs=one=Hello,two=World

•    Create your .java file i.e. SimpleServlet.java
•    Place in your directory e.g. C:\MyServlets
•    Set classpath as set classpath=c:\jsdk2.0\lib\JSKD.jar this instruct a compiler that all class file which is imported is located in jsdk2.0\lib directory and the file is jsdk.jar
•    Compile your SimpleServlet.java file, you will get SimpleServlet.class.
•    Open another command window
•    Change your directory c:\jsdk2.0\bin
•    Start servletrunner and use –d option to specify where your class file is located in our case it is MyServlets i.e. c:\jsdk2.0\bin\servletrunner –d c:\MyServlet
•    Open a browser and give address as http://localhost:8080/servlet/SimpleServlet This means that servlet is present in your local machine and port address is 8080. The name of the servlet is SimpleServlet.

The Servlet API

The package javax.servlet defines all the classes and interfaces associated with the Servlet API. This package includes four Java interfaces and three classes. The interfaces are:

•    ServletContext
•    ServletRequest
•    ServletResponse
•    ServletStub

And the classes are:

•    Servlet
•    ServletInputStream
•    ServletOutputStream

Basic Servlet classes and methods

The Servlet class allows the developer to create servlets by providing the necessary functions. This class includes the methods listed in Table below:

Servlet Class Methods

Public void service( ServletRequest req, ServletResponse res) : This method is used to service a single request from a client. The main purpose of the parameters is to access the input and output streams that are connected to the client browser.   

Public void init() : This method is called by the system when the servlet is first loaded. It is basically used for general initialization of the servlet. The init () method might be called to reset the servlet after it has been used. Therefore, you have to be careful that only initialization is performed in this init () method.   

ServletContext getServletContext(): This method gets a servletContext object that is associated with information about the environment in which the servlet is running.

void log( String mesg ): This method is used to log a message to the servlet log. Logs are generally written into a directory called log under the server’s home directory. These log entries depict the accesses the Web server receives.

String getServletInfo(): This method returns the information about the servlet, as a string.   

public void destroy(): This method is used to release the servlet.

Methods to get Information about the Request - The ServletRequest Interface

int getContentLength():This method is used to return the size of the input data to be supplied (in bytes). It returns -1 if the size is unknown.

String getContentType():This method is used to return a string that is associated with the MIME content type for the data that is to be sent to the servlet from the client browser. This method returns null if the client has not specified the content type. The Content type depends on the browser. For instance, some browsers specify content types of text / plain to indicate that the data is of no special type. Some use content / unknown, and some use application / octet-stream.

String getProtocol():This method is used to return the protocol and version of a Web browser client. The returned string is of the form.

String getParameter( String parameter-name): This method is used to return the value of the parameter (Query string defined in the URL) associated with the name of the parameter passed as an argument to this method. For example, if an URL is given as : http://localhost:8080/servlets/Myservlet>mesg=Hello, the method call getParameter(“mesg”) would return the string value Hello.

Enumeration getParameterNames():This method is used to return an enumeration of strings representing the names of the parameters defined in the URL. This method does not return the values associated with the parameters. To obtain the associated values, call the getParameter() method.

InetAddress getRemoteAddr(): This method is used to return the IP address of the client who sent the request.

String getRemoteHost():This method is used to return the name of the host who made the request.

String getQueryString(): This method is used to return a string that represents only the query string part of the Servlet URL.

String getServerName(): This method is used to return a string that represents the host name of the server.

Int getServerPort(): This method is used to return an integer that represents the port number through which the request is received.

String getPathTranslated():This method is used to return the path information that describes the path on the server machine from which the servlet was loaded.

String getHeader( String header_field): This method is used to return the header information associated with the header_field. To obtain the header_field use the method getParameterNames().

ServletInputStream getInputStream():This method returns the input stream for reading the request data.

Methods to send Information to the client’s browser - The ServletResponse Interface

The response status can be set through a list of static integer variables defined by the ServletResponse interface. The following are the variables:
•    SC_OK
•    SC_CREATED
•    SC_NO_CONTENT
•    SC_MOVED_PERMANENTLY
•    SC_MOVED_TEMPORARILY
•    SC_BAD_REQUEST
•    SC_UNAUTHORIZED
•    SC_FORBIDDEN
•    SC_NOT_FOUND

ServletResponse Interface

ServletOutputStream getOutputStream():This method is used to return the output stream for writing responses to the client browser.

void setContentLength(int length): This method is used to set the content length of the response.

void setContentType( String type ): This method is used to set the content type for the response. The content types are the MIME types discussed earlier. (Refer note for more details about MIME).

void writeHeaders():This method is used to write the status and message headers for the response to the output stream.

void setStatus( int status ): This method is used to set the status code and a default message for the response.

void setHeader( String header_field, String header_value): This method is used to set the value of a header field.

Methods to get Information regarding the servlet context - The ServletContext Interface

The ServletContext interface allows you to find out information about the environment in which the servlet is running.

ServletContext Interface

String getServerInfo():
This method is used to return a string that represents the name and the version of the server running.

String getServlet():This method is used to return a string that represents the name of the servlet.   
Enumeration getServlets():This method is used to return an enumeration of all the available servlets in this context.

The basic steps required for writing servlets are as follows:

•    Step 1 : Extend the Servlet class.
•    Step 2 : Override the service() method.
•    Step 3 : Get the output stream from the ServletResponse object and create a PrintStream object with it.
•    Step 4 : Set the response status to OK using the static variable SC_OK.
•    Step 5 : Set the content type of the response to the appropriate MIME type.
•    Step 6 : Finally, print the request string to the PrintStream.

Let us write a simple servlet program with the help of the above methods. This servlet will respond to the client with the server’s information.

listing1


The output produced by the above program is in plain text, as follows:

Listing2op

Listing2

Listing2op

Listing 3:The following program displays the responses given by the servlet. This program demonstrates some methods of the ServletRequest interface:

listing3

listing3op

Listing 4 : The following program responds to the client with     an image :

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class SimpleImg extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res) throws
IOException
{
res.setContentType("image/jpeg");
File f = new File("servlets/","veli.jpg");
int size = (int)f.length();
res.setContentLength(size);
byte [] buffer = new byte[size];
FileInputStream in = new FileInputStream(f);
in.read(buffer);
res.getOutputStream().write(buffer);
res.getOutputStream().close();
}
}

This is the output produced by this servlet program.

listing4op

Server-Side Includes

The following steps illustrates the basic flow of Server-Side Includes:

  • The mapping table is checked by the Web server for any prefix or suffix matches. In this case, the .shtml file matches a suffix mapping which instructs the Web server to invoke the Server Side Include servlet.
  • If necessary, the Server Side Servlet is loaded and invoked. The Servlet tags are searched only after the Servlet Side Include servlet has parsed the data stream that was read by the File servlet.
  • The servlets corresponding to all the servlet tags found will be invoked and the output fron the servlets merged with the data stream at the point of inclusion of the servlet tags.
  • Finally, the assembled HTML page will be sent to the client.

 


Like it on Facebook, Tweet it or share this article on other bookmarking websites.

No comments