Servlet technology is used to create web application (resides at server side and generates dynamic web page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a server- side programming language. But there was many disadvantages of this technology. We have discussed these disadvantages below. There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.
 Servlet is a technology i.e. used to create web application.  Servlet is an API that provides many interfaces and classes including documentations.  Servlet is an interface that must be implemented for creating any servlet.  Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.  Servlet is a web component that is deployed on the server to create dynamic web page.
 A web application is an application accessible from the web.  A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML.  The web components typically execute in Web Server and respond to HTTP request.
 CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process. Disadvantages of CGI  There are many problems in CGI technology:  If number of clients increases, it takes more time for sending response.  For each request, it starts a process and Web server is limited to start processes.  It uses platform dependent language e.g. C, C++, perl.
 There are many advantages of servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:  better performance: because it creates a thread for each request not process.  Portability: because it uses java language.  Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc.  Secure: because it uses java language..
 Servlet class is loaded.  Servlet instance is created.  init method is invoked.  service method is invoked.  destroy method is invoked.
1) Servlet class is loaded  The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created  The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked  The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:  public void init(ServletConfig config) throws ServletE xception
4) service method is invoked  The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:  public void service(ServletRequest request, ServletRe sponse response) throws ServletException, IOException 5) destroy method is invoked  The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below:  public void destroy()
The servlet example can be created by three ways:  By implementing Servlet interface,  By inheriting GenericServlet class, (or)  By inheriting HttpServlet class  The mostly used approach is by extending HttpServlet because it provides http request specific method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:  Create a directory structure  Create a Servlet  Compile the Servlet  Create a deployment descriptor  Start the server and deploy the project  Access the servlet
There are three ways to create the servlet:-  By implementing the Servlet interface  By inheriting the GenericServlet class  By inheriting the HttpServlet class  The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc.In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the default request.
 import javax.servlet.http.*;  import javax.servlet.*;  import java.io.*;  public class DemoServlet extends HttpServlet{  public void doGet(HttpServletRequest req,HttpServletResponse res)  throws ServletException,IOException  {  res.setContentType("text/html");//setting the content type  PrintWriter pw=res.getWriter();//get the stream to write the data  //writing html in the stream  pw.println("<html><body>");  pw.println("Welcome to servlet");  pw.println("</body></html>");   pw.close();//closing the stream  }}
 RequestDispacher is an interface that provides the facility to forward a request to another resource or include the content of another resource. RequestDispacher provides a way to call another resource from a servlet. Another resource can be servlet, jsp or html.
Methods of RequestDispacher interface:  1. forward(ServletRequest request,ServletResponse response): This method forwards a request from a servlet to another resource on the server.  Syntax:public void forward(ServletRequest request,ServletResponse response)throws ServletException, IOException  2. include(ServletRequest request,ServletResponse response): This method includes the content of a resource in the response.  Syntax: public void include(ServletRequest request,ServletResponse response)throws ServletException, IOException How to get an object of RequestDispacher.  RequestDispacher object can be gets from HttpServletRequest object.ServletRequest’s getRequestDispatcher()method is used to get RequestDispatcher object.  RequestDispatcher requestDispatcher = request.getRequestDispatcher(“/another resource”);  After creating RequestDispatcher object you call forword or include method as per your requirement.  requestDispatcher.forward(request, response); or  requestDispatcher.include(request, response);
 sendRedirect() is the method of HttpServletResponse interface which is used to redirect response to another resource.  Syntax: response. sendRedirect(relative url);
ServletAnnotationExample: @WebServlet("/HelloWorld") public class ServletAnnotationExample extends HttpServlet { private static final long serialVersionUID = 1L; //no-argument constructor public ServletAnnotationExample() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<h1>Hello World example using annotations.</h1>"); out.close(); } }
Cookie:  A cookie is a small piece of information as a text file stored on client’s machine by a web application. How cookie works?  As HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every new request.  In case of cookie a text file with small piece of information is added to the response of first request.  They are stored on client’s machine. Now when a new request comes cookie is by default added with the request. With this information we can identify that it is a new user or a previous user.
 1. Session cookies/Non-persistent cookies: These types of cookies are session dependent i.e. they are accessible as long as session is open and they are lost when session is closed by exiting from the web application.  2. Permanent cookies/Persistent cookies: These types of cookies are session independent i.e. they are not lost when session is closed by exiting from the web application. They are lost when they expire.
Advantages of cookies:  1. They are stored on client side so don’t need any server resource.  2. and easy technique for session management. Disadvantages of cookies:  1. Cookies can be disabled from the browser.  2. Security risk is there because cookies exist as a text file so any one can open and read user’s information
Hidden field:  Hidden field is an input text with hidden type. This field will not be visible to the user.  Syntax:<input name=”fieldName” value=”fieldValue” type=”hidden”/> How to get hidden field value in servlet?  HttpServletRequest interface’s getParameter() method is used to get hidden field value in servlet.  Syntax: String value = request.getParameter(“fieldName”);  Note: Hidden field only works in case of form submission so they will not work in case of anchor tag as no form submission is there. Advantages of hidden field:  1. All browsers support hidden fields. 2. Simple to use. Disadvantages of hidden fields:  1. Not secure. 2. Only work in case of form submission.
J2ee servlet

J2ee servlet

  • 1.
    Servlet technology isused to create web application (resides at server side and generates dynamic web page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a server- side programming language. But there was many disadvantages of this technology. We have discussed these disadvantages below. There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse etc.
  • 2.
     Servlet isa technology i.e. used to create web application.  Servlet is an API that provides many interfaces and classes including documentations.  Servlet is an interface that must be implemented for creating any servlet.  Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.  Servlet is a web component that is deployed on the server to create dynamic web page.
  • 4.
     A webapplication is an application accessible from the web.  A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML.  The web components typically execute in Web Server and respond to HTTP request.
  • 5.
     CGI technologyenables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process. Disadvantages of CGI  There are many problems in CGI technology:  If number of clients increases, it takes more time for sending response.  For each request, it starts a process and Web server is limited to start processes.  It uses platform dependent language e.g. C, C++, perl.
  • 7.
     There aremany advantages of servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of servlet are as follows:  better performance: because it creates a thread for each request not process.  Portability: because it uses java language.  Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc.  Secure: because it uses java language..
  • 9.
     Servlet classis loaded.  Servlet instance is created.  init method is invoked.  service method is invoked.  destroy method is invoked.
  • 11.
    1) Servlet classis loaded  The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container. 2) Servlet instance is created  The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked  The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:  public void init(ServletConfig config) throws ServletE xception
  • 12.
    4) service methodis invoked  The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:  public void service(ServletRequest request, ServletRe sponse response) throws ServletException, IOException 5) destroy method is invoked  The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below:  public void destroy()
  • 13.
    The servlet examplecan be created by three ways:  By implementing Servlet interface,  By inheriting GenericServlet class, (or)  By inheriting HttpServlet class  The mostly used approach is by extending HttpServlet because it provides http request specific method such as doGet(), doPost(), doHead() etc.
  • 14.
    Here, we aregoing to use apache tomcat server in this example. The steps are as follows:  Create a directory structure  Create a Servlet  Compile the Servlet  Create a deployment descriptor  Start the server and deploy the project  Access the servlet
  • 16.
    There are threeways to create the servlet:-  By implementing the Servlet interface  By inheriting the GenericServlet class  By inheriting the HttpServlet class  The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as doGet(), doPost, doHead() etc.In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the default request.
  • 17.
     import javax.servlet.http.*; import javax.servlet.*;  import java.io.*;  public class DemoServlet extends HttpServlet{  public void doGet(HttpServletRequest req,HttpServletResponse res)  throws ServletException,IOException  {  res.setContentType("text/html");//setting the content type  PrintWriter pw=res.getWriter();//get the stream to write the data  //writing html in the stream  pw.println("<html><body>");  pw.println("Welcome to servlet");  pw.println("</body></html>");   pw.close();//closing the stream  }}
  • 25.
     RequestDispacher isan interface that provides the facility to forward a request to another resource or include the content of another resource. RequestDispacher provides a way to call another resource from a servlet. Another resource can be servlet, jsp or html.
  • 26.
    Methods of RequestDispacherinterface:  1. forward(ServletRequest request,ServletResponse response): This method forwards a request from a servlet to another resource on the server.  Syntax:public void forward(ServletRequest request,ServletResponse response)throws ServletException, IOException  2. include(ServletRequest request,ServletResponse response): This method includes the content of a resource in the response.  Syntax: public void include(ServletRequest request,ServletResponse response)throws ServletException, IOException How to get an object of RequestDispacher.  RequestDispacher object can be gets from HttpServletRequest object.ServletRequest’s getRequestDispatcher()method is used to get RequestDispatcher object.  RequestDispatcher requestDispatcher = request.getRequestDispatcher(“/another resource”);  After creating RequestDispatcher object you call forword or include method as per your requirement.  requestDispatcher.forward(request, response); or  requestDispatcher.include(request, response);
  • 27.
     sendRedirect() isthe method of HttpServletResponse interface which is used to redirect response to another resource.  Syntax: response. sendRedirect(relative url);
  • 29.
    ServletAnnotationExample: @WebServlet("/HelloWorld") public class ServletAnnotationExampleextends HttpServlet { private static final long serialVersionUID = 1L; //no-argument constructor public ServletAnnotationExample() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("<h1>Hello World example using annotations.</h1>"); out.close(); } }
  • 30.
    Cookie:  A cookieis a small piece of information as a text file stored on client’s machine by a web application. How cookie works?  As HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every new request.  In case of cookie a text file with small piece of information is added to the response of first request.  They are stored on client’s machine. Now when a new request comes cookie is by default added with the request. With this information we can identify that it is a new user or a previous user.
  • 31.
     1. Sessioncookies/Non-persistent cookies: These types of cookies are session dependent i.e. they are accessible as long as session is open and they are lost when session is closed by exiting from the web application.  2. Permanent cookies/Persistent cookies: These types of cookies are session independent i.e. they are not lost when session is closed by exiting from the web application. They are lost when they expire.
  • 32.
    Advantages of cookies: 1. They are stored on client side so don’t need any server resource.  2. and easy technique for session management. Disadvantages of cookies:  1. Cookies can be disabled from the browser.  2. Security risk is there because cookies exist as a text file so any one can open and read user’s information
  • 35.
    Hidden field:  Hiddenfield is an input text with hidden type. This field will not be visible to the user.  Syntax:<input name=”fieldName” value=”fieldValue” type=”hidden”/> How to get hidden field value in servlet?  HttpServletRequest interface’s getParameter() method is used to get hidden field value in servlet.  Syntax: String value = request.getParameter(“fieldName”);  Note: Hidden field only works in case of form submission so they will not work in case of anchor tag as no form submission is there. Advantages of hidden field:  1. All browsers support hidden fields. 2. Simple to use. Disadvantages of hidden fields:  1. Not secure. 2. Only work in case of form submission.