javax.servlet.http.HttpServlet
. servlet.jar
(or servlet-api.jar
). service ()
method, it is independent, whereas Http Servlet extends the generic servlet and supports the HTTP
methods such as doGet (), doPost (), doHead (), doTrace ()
, etc. Init ()
method, used to initialize the servlet is invoked.public void Init ()
public void service ()
destroy ()
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);
public void forward(ServletRequest request, ServletResponse response)
public void include(ServletRequest request, ServletResponse response)
main()
method, unlike a regular Java program, and just like an applet. It has some methods of a servlet that are called upon by the server for the purpose of handling requests. It invokes the servlet’s service()
method, every time the server sends a request to a servlet.service()
method. The service()
method allows 2 parameters : these are the request object and the response object. service()
method. However, it actually overrides the doGet()
to handle the GET requests and the doPost()
to handle POST requests. Depending on the type of requests it needs to handle, an HTTP servlet can override either or both of these methods.<SERVLET>
tag is also returned. The <SERVLET>
tag is then substituted by the corresponding servlet code.public class CatalogServlet extends HttpServlet {
private ArticleDBAO articleDB;
public void init() throws ServletException {
articleDB = (ArticleDBAO)getServletContext().
getAttribute("articleDB");
if (articleDB == null) throw new
UnavailableException("Database not loaded");
}
}
public void destroy() {
bookDB = null;
}
javax.servlet.ServletConfig
is used to pass configuration information to Servlet. Every servlet has it’s own ServletConfig
object and servlet container is responsible for instantiating this object. We can provide servlet init parameters in web.xml file or through use of WebInitParam annotation. We can use getServletConfig()
method to get the ServletConfig object of the servlet. javax.servlet.ServletContext
interface provides access to web application parameters to the servlet. The ServletContext
is unique object and available to all the servlets in the web application. When we want some init parameters to be available to multiple or all of the servlets in the web application, we can use ServletContext object and define parameters in web.xml
using <context-param>
element. We can get the ServletContext object via the getServletContext()
method of ServletConfig. Servlet containers may also provide context objects that are unique to a group of servlets and which is tied to a specific portion of the URL path namespace of the host.ServletContext
is enhanced in Servlet Specs 3 to introduce methods through which we can programmatically add Listeners and Filters and Servlet to the application. It also provides some utility methods such as getMimeType(), getResourceAsStream() etc
.ServletConfig
is a unique object per servlet whereas ServletContext
is a unique object for complete application.ServletConfig
is used to provide init parameters to the servlet whereas ServletContext
is used to provide application level init parameters that all other servlets can use.ServletConfig
object whereas we can set attributes in ServletContext
that other servlets can use in their implementation.Get ()
method is preferred over the Post()
method are given below.Get()
method, data is not secured as it is exposed in the URL bar to the user.Get ()
method can be bookmarked.get ()
method is more effective and used over the post ()
method.Post ()
method is sent through the body, it is secured.Post ()
method cannot be bookmarked.Post ()
method is less effective and is not often used.Redirect ()
method which works at the client side is used to redirect the response to another resource like Servlet, JSP, HTML.void send Redirect(URL);
response.sendredirect(“http://www.google.com”);
HttpServlet
overrides the service()
method to handle HTTP requests and dispatch them to one of the doXXX() handler methods depending on the Http request type (GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE).service()
method.doGet()
: Handles Http GET requestsdoPost()
: Handles Http POST requestsdoPut()
: Handles Http PUT requestsdoDelete()
: Handles Http DELETE requestsdoHead()
: Handles Http HEAD requestsdoOptions()
: Handles Http OPTIONS requestsdoTrace()
: Handles Http TRACE requestsservice()
method of the servlet to process, via a separate thread for each request. Hence the service()
method and the servlet has to be designed to be thread safe for concurrent processing with multiple threads. HttpServletRequest
defines following methods for handling Multipart data.ServletRequest
interface defines the following methods to get more information about the client or the last proxy that send the request.HttpServletRequest
interface that extends from ServletRequest interface inherits above methods.ServletRequest
interface defined in Servlet API provides the following methods for authentication.getUserPrincipal(), getRemoteUser()
, and getAuthType()
is called on the request. getMimeType()
method. It comes in handy while downloading a file through servlets from a server.forward()
to forward the request processing to a different servlet. If you want to add another servlet output to a response, you can use the RequestDispatcher include()
method. jar -cvf abc.war *
abc.war
file.doPost()
method inside doGet()
method, or by calling a doGet()
method inside doPost()
method will successfully create a deadlock situation for a servlet. import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
performTask(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
performTask(request, response);
}
private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/html");
response.addHeader("Refresh", "5");
PrintWriter out = response.getWriter();
out.println("TestServlet says hi at " + new Date());
}
}
service()
method is actually the main method that is expected to perform the actual task. The servlet container calls the service()
method to handle requests coming from the client/browsers and to provide the response back to the client.service()
method checks the HTTP request type and calls the respective methods as required.public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException{
}
The container calls the service()
method and service method invokes doGet(), doPost(), doPut(), doDelete()
, methods as needed. So you have nothing to do with service()
method but you override either doGet()
or doPost()
depending on the request you receive from the client-end.
SingleThreadModel
interface was provided for thread safety and it guarantees that no two threads will execute concurrently in the servlet’s service method. However, SingleThreadModel
does not solve all thread-safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used. Also, it takes out all the benefits of multithreading support of servlets, that’s why this interface is Deprecated in Servlet 2.4. ServletRequest
, HttpSession
, and ServletContext
interfaces provide methods to get/set/remove
attributes from request, session and application scope respectively.web.xml
for ServletConfig or ServletContext. init()
method. If we override init(ServletConfig config)
method, then the first statement should be super(config)
to make sure superclass init(ServletConfig config) method is invoked first. That’s why GenericServlet provides another helper init()
method without argument that get’s called at the end of init(ServletConfig config)
method. We should always utilize this method for overriding init()
method to avoid any issues as we may forget to add super()
call in overriding init method with ServletConfig argument. WEB.XML
is said to be the deployment descriptor in a servlet.javax.servlet.http.HttpSessionBindingListener
interface. This interface defines two callback methods – valueBound()
and valueUnbound(
) that we can define to implement processing logic when the object is added as attribute to the session and when session is destroyed. ServletContext
, we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in the deployment descriptor (web.xml
). What if our application is database-oriented and we want to set an attribute in ServletContext
for Database Connection.getRemoteAddr()
and getRemoteHost()
to retrieve the IP address and hostname of the client machine, respectively :public String ServletRequest.getRemoteAddr()
public String ServletRequest.getRemoteHost()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FTL extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +"Transitional//EN\">n" +"<HTML>n" +"<HEAD><TITLE>FTL</TITLE></HEAD>n" + "<BODY>n" + " <H1>FREE TIME LEARNING</H1> n" + "</BODY></HTML>");
}
}