Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for accessing Generic Servlet
Previous Home Next

This Generic Servlet program, counts number of time Generic Servlet is accessed.

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
		http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <servlet>
     <servlet-name>firstServlet</servlet-name>
     <servlet-class>r4r.GenericServlet.firstServlet</servlet-class>
  </servlet>
  <servlet-mapping>
     <servlet-name>firstServlet</servlet-name>
     <url-pattern>/firstServlet</url-pattern>
  </servlet-mapping>
  <session-config>
     <session-timeout>
            30
     </session-timeout>
  </session-config>
</web-app>

index.jsp

<%-- 
    Document: index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
  <head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
   <title>r4r.co.in-GenericServlet</title>
  </head>
  <body>
   <form>
    <h1>Access GenericServlet by servlet's Name!</h1>
    <a href="firstServlet">firstServlet</a>
    </form>
  </body>
</html>

Servlet Program

/*
 * Save as a firstServlet.java
*/
package r4r.GenericServlet;
import java.io.IOException;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
*
* @author R4R
*/
public class firstServlet extends GenericServlet {
  private int count;
  @Override
  public void init() throws ServletException {
  count = 0;
  }
  @Override
  public void init(ServletConfig config) throws ServletException
  {
  super.init(config);
  getServletContext().log("init() method call/initialize"); 
					//print msg over server console
  }
  @Override
  public void service(ServletRequest req,
	  ServletResponse res)throws ServletException,IOException
  {
      res.setContentType("text/html;charset=UTF-8");
      try
      {
	  }
      catch ()
      {
      }
	  {
      getServletContext().log("service() method call/initialize");
      res.getWriter().println(getServletInfo());
      res.getWriter().println
	("<BR>Every refresh of web page counter should be increament by 1: Count = "
						+ (++count));
      } 
	  finally 
	  {
         res.getWriter().close(); // free resource
      }
    }
	@Override
    public void destroy() {
        count = 0;      //reset count value as 0
        getServletContext().log("destroy() method call/initialize");
    }

    @Override
    public String getServletInfo() {
        return "r4r.co.in-firstServlet";
    }
}
Output of Program
Previous Home Next