Tuesday 15 July 2014

service (ServletRequest req, ServletResponse res)

public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException
Servlet calls the service method to process client requests. Whenever a request for a servlet comes, the server spawns a new thread and calls service method of the servlet. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Servlet Service</title>
    </head>
    <body>
        <form method="get" action="/servlet/ServletService">
            <input type="submit" value="Click Me">
        </form>
    </body>
</html>

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletService extends HttpServlet {

  @Override
  public void init(){
     System.out.println("I am in init method"); 
  }
  
  @Override
  public void destroy(){
      System.out.println("I am in destroy");
  }
          
  @Override
  public void service(ServletRequest req, ServletResponse res){
      System.out.println("I am in service method");
  }
  
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp){
      System.out.println("I am in do Get method");
  }
         
}
 
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>ServletService</servlet-name>
        <servlet-class>ServletService</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletService</servlet-name>
        <url-pattern>/ServletService</url-pattern>
    </servlet-mapping>
</web-app>

wait for some time to print the message 'I am in destroy'. Since the destroy method called after a timeout period has passed.

Output
I am in init method
I am in service method
I am in destroy




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment