36
J2EE SERVLET 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.

J2ee servlet

Embed Size (px)

Citation preview

Page 1: J2ee servlet

J2EESERVLET

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.

Page 2: J2ee servlet

WHAT IS A SERVLET?

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.

Page 3: J2ee servlet
Page 4: J2ee servlet

WHAT IS WEB APPLICATION?

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.

Page 5: J2ee servlet

CGI(COMMMON GATEWAY INTERFACE)

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.

Page 6: J2ee servlet
Page 7: J2ee servlet

ADVANTAGE OF SERVLET

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..

Page 8: J2ee servlet
Page 9: J2ee servlet

LIFE CYCLE OF A SERVLET (SERVLET LIFE CYCLE)

Servlet class is loaded. Servlet instance is created. init method is invoked. service method is invoked. destroy method is invoked.

Page 10: J2ee servlet
Page 11: J2ee servlet

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 ServletException  

Page 12: J2ee servlet

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, ServletResponse 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()  

Page 13: J2ee servlet

STEPS TO CREATE A SERVLET EXAMPLE

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.

Page 14: J2ee servlet

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

Page 15: J2ee servlet

CREATE A DIRECTORY STRUCTURES

Page 16: J2ee servlet

CREATE A SERVLETThere 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.

Page 17: J2ee servlet

DEMOSERVLET.JAVA import javax.servlet.http.*;   import javax.servlet.*;   import java.io.*;   public class DemoServlet extends HttpServlet{   public void doGet(HttpServletRequest req,HttpServletResponse r

es)   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   }}  

Page 18: J2ee servlet

COMPILE THE SERVLET

Page 19: J2ee servlet

CREATE THE DEPLOYMENT DESCRIPTOR (WEB.XML FILE)

Page 20: J2ee servlet

SERVLET OUTPUT

Page 21: J2ee servlet

CREATING SERVLET EXAMPLE IN ECLIPSE

Page 22: J2ee servlet
Page 23: J2ee servlet

CREATE THE SERVLET IN ECLIPSE IDE:

Page 24: J2ee servlet
Page 25: J2ee servlet

REQUESTDISPATCHER INTERFACE 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.

Page 26: J2ee servlet

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);

Page 27: J2ee servlet

SENDREDIRECT IN SERVLET sendRedirect() is the method of

HttpServletResponse interface which is used to redirect response to another resource.

Syntax: response. sendRedirect(relative url);

Page 28: J2ee servlet

DIFFERENCE BETWEEN SENDREDIRECT AND REQUESTDISPATCHER

Page 29: J2ee servlet

SERVLET HELLO WORLD EXAMPLE USING ANNOTATION.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(); }}

Page 30: J2ee servlet

COOKIE IN SERVLETCookie: 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.

Page 31: J2ee servlet

TYPES OF COOKIES: 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.

Page 32: J2ee servlet

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

Page 33: J2ee servlet
Page 34: J2ee servlet
Page 35: J2ee servlet

HIDDEN FIELD IN SERVLETHidden 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.

Page 36: J2ee servlet

THANK U