Servlets in Java

Servlets are java programs that run on web or application servers, servlets are also called server side programs i.e the code of the program executes at server side, acting as a middle layer between request coming from Web browsers or other HTTP clients and databases or applications on the HTTP server. A servlet container uses a Java Virtual Machine to run servlet code as requested by a web server. A servlet dynamically loaded module that services requests from Web server. It runs entirely inside the Java Virtual Machine.

Servlets are not tied to specific client server protocol but they are most commonly used with HTTP. Since servlets run inside the web server they do not display a graphical user interface

APPLICATION OF JAVA SERVLETS

Servlets can be used for the following applications:

  • Servlets are used for developing online shopping store web page. When servlet receives the posted data, it will process it and fullfils the client request
  • Servelets are usefuls for developing distributed applications.

ADVANTAGES OF SERVLETS

Java Servlets are efficient, portable, robust, extensible and secure

Servlets efficiency

A Servlet code is loaded into memory once. After the servlet is loaded, handling new request is only matter of calling a service method. In a CGI, if there are N requests to the same CGI program, the code for the CGI program is loaded into memory N times. While in case of servlets there are N thread, but only a single copy the servlet would be loaded. Loading a new executable for every request is expensive technique. The java servlet provides an is efficient technique to it

Servlets PORTABLE

Servlets are java program, hence the servlet code is independent of machine architecture. They can be moved to any machine or any operating system

ROBUST

Servlets are developed with access to entire JDK, servlet support several capabilities they are very powerful. It has garbage collector to prevent problems with memory leaks. Servlets can also maintain information from request to request, simplifying techniques like session tracking and caching of previous computations

EXTENSIBLE

Servlets are developed using java they can be extended into new objects that are better than the previous one. You can implement a base servlet that builds and initializes the search tool and then extend it to display transaction – specific response.

SECURE

Servlets run on server side they are secure. They inherits the security provided by
the Web Server.

The CGI programs are often executed by general – purpose operating shells. So, the CGI programmer must be careful to filterout characters such as backquotes and semicolons that are treated specially by the shell

SERVLET ARCHITECTURE

A servlet is a java program. Servlets are created by extending GenericServlet or HttpServlet class which are available in package javax.servlet. and javax.servlet.htpp respectively. Every time a server receives a request that points to a servlet, it callsservlet’s service method. Hence service method be defined to to provide customized functionality. The other two methods are init () and destroy (), the init () method is called only once when servlet is loaded in the memory, while destroy () method is executed only once when servlet is unloaded from the memory

What is GenericServlet ?

GenericServlet is the core class in javax.servlet package. Generic servlet may be used to create servlets by extending it. GenericServlet provides methods init() and destroy() and the methods in ServletConfig interface

What is HttpServlet ?

HttpServlet inherits basic Servlet functionality by extending GenericServlet.HttpServlet must override methods such as service(), doGet(), doPost(). Its service method receive two parameters they are HttpServletRequest and HttpServletResponse. The doGet() method is called in response to an HTTP GET request, used to send client data. The doPost() is called in response to an HTTP POST request from HTML form.

public class ServletDemo extends HttpServlet
{
public void init()
{
/* used to initialize resources */

}
public void service()
{
/* used to fulfill client request */
}
public void destroy()
{
/* Release the resources */
}
}

Structure of servlet program

import java.io.*;
import javax.servlet.*;
public class HelloWorld extends GenericServlet
{
public void service(ServletRequest request, 
ServletResponse response )
throws IOException
{
response.setContentType("text/html"); 
PrintWriter pw = response.getWriter();
pw.println("<B> Hello World <B>");
pw.close();
}
}

The service method throws IOException. The statement response.setContent(“text/html”) is used to set the MIME type for HTTP header it specify the response type of document displayed at the client browser. PrintWriter is a class is used to send content back to the browser, and println method is used to print content to the browser with the help of handle created with PrintWriter class

COMPILING AND RUNNING SERVLET PROGRAM

Compiling and running a servlet program requires a Web Server to be installed on your computer. The Web Server contains the necessary classes required to create a servlet program. The following example illustrate the compilation of java servlet program with the help of Java Servlet Development Kit 2.0

  • After creating the above program save program with name HelloWorld.java and move to the MS-DOS prompt
  • Move to the foldder where you have java servlet program
  • At the MS-DOS prompt type the path and classpath of java servlet
  • path = G:\Program Files\Java\jdk1.6.0_01\bin
  • set classpath=G:\JSDK2.0\lib\jsdk.jar
  • compile java program as : javac HelloWorld.java
  • copy HelloWorld.class file and paste it to the example folder of JSDK2.0
  • open servlet.properties files in notepad and type mapping to the servlet as: servlet.code.Hello=HelloWorld
  • move to the bin folder of JSDK2.0 start servletrunner program by double clicking it.
  • Start the web browser by double clicking it, and at its address bar type : http://localhost:8080/servlet/HelloWorld

DEPLOYING WEB APPLICATION USING TOMCAT

  • Create a sub directory under the \install_directory\webapps move your application to this directory. A context with the directory name will be created automatically
  • Create a directory WEB-INF under subdirectory created in step 1. The WEB-INF stores files such web.xml which is used to keep application configurations.
  • Create classes subdirectory under the WEB-INF. The classes directory is used to store the java servlets class files.
  • Create a subdirectory lib under WEB-INF. This is used to store the jar files and native libraries.
  • Create web.xml file under the WEB-INF folder and add following mapping to it.

web.xml

<web-app>
 <servlet>
 <servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>HelloServlet</servlet-name>
 <url-pattern>/*</url-pattern>
 </servlet-mapping>
</web-app>
  • Start Tomcat Web Server
  • Type url at address bar http://localhost:8080/servlet/HelloServlet
  • create a different context workshop i.e directory under webapps directory of Tomact directory structure.

LIFE CYCLE OF JAVA SERVLET

The servlet cycle has three methods these init () for initialization of the resources, service() handles zero or more requests and the destroy() method is invoked at end of servlet life it releases all resources which were allocated previously.

init()

The init() method is where the servlets life begins. It is called by the server immediately after the servlet is instantiated. The database connection, opening a file, or a network connection may be established through it. The init method is not called again for each request. The servlet is normally created when a user first invokes a URL corresponding to servlet.

public void init (ServletConfig config) throws ServletException

The following are the task performed while implementing init() method

  • Reading initializing parameters using ServletConfig object
  • Initializing a database driver
  • Opening a database connection
  • Initialization of objects

service()

The service method handles all requests sent by a client. Each time the server receive a request for a servlet, the server spawns a new thread and calls service method. The service method checks the request type GET, POST, PUT, DELETE etc. For, every request to the servlet, its service method is called. Two objects ServletRequest and ServletResponse are passed as argument to it

public void service(ServletRequest request, ServletResponse response ) throws
ServletException, IOException

destroy()

This method signifies the end of a servlet life. The resources that are previously allocated are destroyed. The method is invoked by server administrator or programmatically by servlet itself.

  • A server loads and initializes the servlet
  • The servlet handles zero or more client request
  • The server removes the servlet

READING HTML FORM PARAMETERS

Reading parameter requires a html form with some text fields which are used to input values. The HTML form reads the values and send it to the servlet by using the action URL. The input values are read by the java servlet program and send back to browser for the display.

Two.html

<html>
<head>
<title> Reading Parameters </title>
<body bgcolor="#FDF5E6">
<h1 align ="center"> Reading Parameters </h1>
<form action ="http://localhost:8080/servlet/Two">
First Parameter : <input type = "text" name = "param1"><br>
Second Parameter: <input type = "text" name = "param2"><br>
<center> <input type = "submit"></center>
</form>
</body>
</html>

Two.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Two extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res )
throws ServletException, IOException
{
 res.setContentType("text/html");
 PrintWriter pw = res.getWriter();
 pw.println(req.getParameter("param1"));
 pw.println(req.getParameter("param2"));
 
}
}

Leave a Comment