Servlet: What is it

What is Servlet? The Servlet is a class that is written in Java programming language and is used to provide a mechanism for developing server side programs. It interacts with clients via request-response programming model. Servlet enhance the web servers by extending the applications hosted by it. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

Servlet: What is it


What is Servlet? The Servlet is a class that is written in Java programming language and is used to provide a mechanism for developing server side programs. It interacts with clients via request-response programming model. Servlet enhance the web servers by extending the applications hosted by it. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

A web container, which is a component of a web server, is used to interact with servlet. It is also manages the lifecycle of servlets and maps a URL to a particular servlet.

Servlet invokes a single thread for each user request rather than creating a new process every time.

Servlet is highly portable, is platform independent, is highly secure and has Java database connectivity.

What does Servlet do?

A servlet is a class, which responds to HTTP request. It receives a HTTP request from a client and reverts back the text data. Using servlet, programmer can store data that was submitted from an HTML form. Servlet is also used to add dynamic content for example showcasing the results of a database query.

Servlets are quick as they are pure java classes. Servlet embeds HTML inside Java code. A Servlet generates a response according to the request it receives.

Latest version of servlet is 3.0 (till date). Earlier version of Servlet are:

Following is the example of Servlet:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></title>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}

To run Servlet before the version 3.0, it requires xml mapping. Advanced Servlet version does not require much mapping because of the introduction of annotation.

web.xml file for the above program:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

</web-app>