Servlet

Servlet is java server side technology, which processes the request from the client. To create a servlet we have to either extend Generic Servlet and override its service method or extend HttpServlet if its is web application and override doPost or doGet Methods.

When a request from the client maps the servlet url , the container checks whether the servlet instance is already created. If not, it loads the servlet and creates the object, instantiates it by calling init method. Then calls the service method. Between each request it calls the service method. when the application is closed, container calls destroy methodThere are listeners such as web context , session etc that monitor the life cycle of the servlet and react by calling a method of listener object when an event occurs. The container responds to the servlet exceptions by generating a default page showing Servlet Exception occurred.  But we can specify the error page.

An example of servlet which extends HttpServlet
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Hello World");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Comments

Popular posts from this blog

Transform values with a stream

Collections Framework

Inspect a collection