Unit III Servlets Dr. Vasanti Dutta
Servlet • Servlet technology is used to create a web application (resides at server side and generates a dynamic web page). • Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. However, there were many disadvantages to this technology. • There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc. Class notes for Servlet by Dr. V. Dutta 2
Servlet Features • Servlet is a technology which is used to create a web application. • Servlet is an API that provides many interfaces and classes including documentation. • Servlet is an interface that must be implemented for creating any Servlet. • Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests. • Servlet is a web component that is deployed on the server to create a dynamic web page. Class notes for Servlet by Dr. V. Dutta 3
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 elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request. • The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative, distributed, hypermedia information systems. It is the data communication protocol used to establish communication between client and server. • HTTP is TCP/IP based communication protocol, which is used to deliver the data like image files, query results, HTML files etc on the World Wide Web (WWW) with the default port is TCP 80. It provides the standardized way for computers to communicate with each other. Class notes for Servlet by Dr. V. Dutta 4
Basic architecture of web application and depicts where HTTP stands. Class notes for Servlet by Dr. V. Dutta 5
HTTP • HTTP is media independent: It specifies that any type of media content can be sent by HTTP as long as both the server and the client can handle the data content. • HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a browser initiates the HTTP request and after the request is sent the client disconnects from server and waits for the response. • HTTP is stateless: The client and server are aware of each other during a current request only. Afterwards, both of them forget each other. Due to the stateless nature of protocol, neither the client nor the server can retain the information about different request across the web pages. Class notes for Servlet by Dr. V. Dutta 6
Website: static vs dynamic It is a collection of related web pages that may contain text, images, audio and video. HTTP It is the data communication protocol used to establish communication between client and server. HTTP Requests It is the request send by the computer to a web server that contains all sorts of potentially interesting information. Get vs Post It gives the difference between GET and POST request. Container It is used in java for dynamically generating the web pages on the server side. Server: Web vs Application It is used to manage the network resources and for running the program or software that provides services. Content Type It is HTTP header that provides the description about what are you sending to the browser.Class notes for Servlet by Dr. V. Dutta 7
Static Website Dynamic Website Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly. It uses the HTML code for developing a website. It uses the server side languages such as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website. It sends exactly the same response for every request. It may generate different HTML for each of the request. The content is only changed when someone publishes and updates the file (sends it to the web server). The page contains "server-side" code which allows the server to generate the unique content when the page is loaded. Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage of dynamic website. Class notes for Servlet by Dr. V. Dutta 8
HTTP is request/response protocol which is based on client/server based architecture. In this protocol, web browser, search engines, etc. behave as HTTP clients and the Web server like Servlet behaves as a server Class notes for Servlet by Dr. V. Dutta 9
The HTTP client sends the request to the server in the form of request message which includes following information: • The Request-line • The analysis of source IP address, proxy and port • The analysis of destination IP address, protocol, port and host • The Requested URI (Uniform Resource Identifier) • The Request method and Content • The User-Agent header • The Connection control header • The Cache control header The HTTP request method indicates the method to be performed on the resource identified by the Requested URI (Uniform Resource Identifier). Class notes for Servlet by Dr. V. Dutta 10
HTTP Request Description GET Asks to get the resource at the requested URL. POST Asks the server to accept the body info attached. It is like GET request with extra info sent with the request. HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body. TRACE Asks for the loopback of the request message, for testing or troubleshooting. PUT Says to put the enclosed info (the body) at the requested URL. DELETE Says to delete the resource at the requested URL. OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond Class notes for Servlet by Dr. V. Dutta 11
GET POST 1) In case of Get request, only limited amount of data can be sent because data is sent in header. In case of post request, large amount of data can be sent because data is sent in body. 2) Get request is not secured because data is exposed in URL bar. Post request is secured because data is not exposed in URL bar. 3) Get request can be bookmarked. Post request cannot be bookmarked. 4) Get request is idempotent. i.e second request will be ignored until response of first request is delivered Post request is non- idempotent. 5) Get request is more efficient and used more than Post. Post request is less efficient and used less than get.Class notes for Servlet by Dr. V. Dutta 12
Class notes for Servlet by Dr. V. Dutta 13
CGI • CGI (Common 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. There are many problems in CGI technology (Disadvantages): • If the number of clients increases, it takes more time for sending the response. • For each request, it starts a process, and the web server is limited to start processes. • It uses platform dependent language e.g. C, C++, perl. Class notes for Servlet by Dr. V. Dutta 14
Advantages 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 many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet are as follows: • Better performance: because it creates a thread for each request, not process. • Portability: because it uses Java language. • Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc. • Secure: because it uses java language. Class notes for Servlet by Dr. V. Dutta 15
Class notes for Servlet by Dr. V. Dutta 16
Class notes for Servlet by Dr. V. Dutta 17
Servlet Container • It provides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java. • The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: Class notes for Servlet by Dr. V. Dutta 18
• The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: • Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself • In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss. • Out-of-process: The web server and servlet container are different programs which are run in a different process. For performing the communications between them, web server uses the plug-in provided by the servlet container. Class notes for Servlet by Dr. V. Dutta 19
Servlet Container functions • Life Cycle Management • Multithreaded support • Object Pooling • Security etc. Class notes for Servlet by Dr. V. Dutta 20
Server • Server is a device or a computer program that accepts and responds to the request made by other program, known as client. It is used to manage the network resources and for running the program or software that provides services. There are two types of servers: • Web Server (Apache Tomcat and Resin etc). : It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB. • Application Server: It contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture. Examples : Jboss, Glassfish, Weblogic, Websphere. Class notes for Servlet by Dr. V. Dutta 21
Servlet API • The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. • The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. • The javax.servlet.http package contains interfaces and classes that are responsible for http requests only. Class notes for Servlet by Dr. V. Dutta 22
Interfaces and Classes in javax.servlet package • Servlet • ServletRequest • ServletResponse • RequestDispatcher • ServletConfig • ServletContext • SingleThreadModel • Filter • FilterConfig • FilterChain • ServletRequestListener • ServletRequestAttributeListener • ServletContextListener • ServletContextAttributeListener GenericServlet ServletInputStream ServletOutputStream ServletRequestWrapper ServletResponseWrapper ServletRequestEvent ServletContextEvent ServletRequestAttributeEvent ServletContextAttributeEvent ServletException UnavailableException Class notes for Servlet by Dr. V. Dutta 23
Interfaces and Classes in javax.servlet.http package • HttpServletRequest • HttpServletResponse • HttpSession • HttpSessionListener • HttpSessionAttributeListener • HttpSessionBindingListener • HttpSessionActivationListener • HttpSessionContext (deprecated now) HttpServlet Cookie HttpServletRequestWrapper HttpServletResponseWrapper HttpSessionEvent HttpSessionBindingEvent HttpUtils (deprecated now) Class notes for Servlet by Dr. V. Dutta 24
Class notes for Servlet by Dr. V. Dutta 25
Methods of Servlet Interface public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container. public void destroy() is invoked only once and indicates that servlet is being destroyed. public ServletConfig getServletConfig() returns the object of ServletConfig. public String getServletInfo() returns information about servlet such as writer, copyright, version etc. Class notes for Servlet by Dr. V. Dutta 26
Functions of Web-Container • loads the servlet class. • instantiates the servlet class. • calls the init method passing the ServletConfig object else • calls the service method passing request and response objects • The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project. Class notes for Servlet by Dr. V. Dutta 27
Steps : Web container handling the request  maps the request with the servlet in the web.xml file.  creates request and response objects for this request  calls the service method on the thread  The public service method internally calls the protected service method  The protected service method calls the doGet method depending on the type of request.  The doGet method generates the response and it is passed to the client.  After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation. Class notes for Servlet by Dr. V. Dutta 28
Class notes for Servlet by Dr. V. Dutta 29 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 }}
Steps for creating Servlet in Eclipse 1) For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic web project -> write your project name e.g. first -> Finish. 2) For creating a servlet, explore the project by clicking the + icon -> explore the Java Resources -> right click on src -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish. 3) add jar file in eclipse IDE: For adding a jar file, right click on your project -> Build Path -> Configure Build Path -> click on Libraries tab in Java Build Path -> click on Add External JARs button -> select the servlet-api.jar file under tomcat/lib -> ok. 4) Start the server and deploy the project: For starting the server and deploying the project in one step, Right click on your project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish. 5) Now tomcat server has been started and project is deployed. To access the servlet write the url pattern name in the URL bar of the browser. In this case Hello then enter. Class notes for Servlet by Dr. V. Dutta 30
ServletRequest Interface An object of ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header information, attributes etc. Its methods are: public String getParameter(String name): is used to obtain the value of a parameter by name. public String[] getParameterValues(String name): returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box. java.util.Enumeration getParameterNames():returns an enumeration of all of the request parameter names. public int getContentLength():Returns the size of the request entity data, or -1 if not known. public String getCharacterEncoding():Returns the character set encoding for the input of this request. public String getContentType():Returns the Internet Media Type of the request entity data, or null if not known. public ServletInputStream getInputStream() throws IOException: Returns an input stream for reading binary data in the request body. public abstract String getServerName() :Returns the host name of the server that received the request. public int getServerPort(): Returns the port number on which this request was received. Class notes for Servlet by Dr. V. Dutta 31
Example of ServletRequest to display the name of the user 1) index.html <form action="welcome" method="get"> Enter your name<input type="text" name="name"><br> <input type="submit" value="login"> </form> Class notes for Servlet by Dr. V. Dutta 32 import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class DemoServ extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); String name=req.getParameter("name");//will return value pw.println("Welcome "+name); pw.close(); }}
RequestDispatcher interface The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration. There are two methods defined in the RequestDispatcher interface. • public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. • public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP page, or HTML file) in the response. Class notes for Servlet by Dr. V. Dutta 33
Class notes for Servlet by Dr. V. Dutta 34
The getRequestDispatcher() method The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax : public RequestDispatcher getRequestDispatcher(String resource) ; RequestDispatcher rd=request.getRequestDispatcher("servlet 2"); //servlet2 is the url-pattern of the second servlet rd.forward(request, response); //method may be include or forward • Class notes for Servlet by Dr. V. Dutta 35
Example of RequestDispatcher interface • index.html file: for getting input from the user. • Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet. • WelcomeServlet.java file: a servlet class for displaying the welcome message. • web.xml file: a deployment descriptor file that contains the information about the servlet. Class notes for Servlet by Dr. V. Dutta 36
Class notes for Servlet by Dr. V. Dutta 37
Class notes for Servlet by Dr. V. Dutta 38 index.html <form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPass"/><br/> <input type="submit" value="login"/> </form> // WelcomeServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); } }
Class notes for Servlet by Dr. V. Dutta 39 //Login.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet"){ RequestDispatcher rd=request.getRequestDispatcher("servlet2"); rd.forward(request, response); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=request.getRequestDispatcher("/index.html"); rd.include(request, response); } } }
Class notes for Servlet by Dr. V. Dutta 40 web.xml <web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> </servlet> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
Session Tracking • Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time. Sessions are shared among the servlets accessed by a client. • The HttpSession object is used for session management. A session contains information specific to a particular user across the whole application. When a user enters into a website (or an online application) for the first time HttpSession is obtained via request.getSession(), the user is given a unique ID to identify his session. This unique ID can be stored into a cookie or in a request parameter. • The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t specify the value in tag. This means that when the user doesn’t visit web application time specified, the session is destroyed by servlet container. The subsequent request will not be served from this session anymore, the servlet container will create a new session.Class notes for Servlet by Dr. V. Dutta 41
Class notes for Servlet by Dr. V. Dutta 42 Cookies :A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. This may not be an effective way because many time browser does not support a cookie, so not recommended to use this procedure to maintain the sessions.
Class notes for Servlet by Dr. V. Dutta 43 Few methods of HttpSession public void setAttribute(String name, Object value): Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. If an attribute already exists, then this method replaces the existing attributes. public Object getAttribute(String name): Returns the String object specified in the parameter, from the session object. If no object is found for the specified attribute, then the getAttribute() method returns null. public Enumeration getAttributeNames(): Returns an Enumeration that contains the name of all the objects that are bound as attributes to the session object. public void removeAttribute(String name): Removes the given attribute from session. setMaxInactiveInterval(int interval): Sets the session inactivity time in seconds. This is the time in seconds that specifies how long a sessions remains active since last request received from client.
MyServlet2.java and index.html Class notes for Servlet by Dr. V. Dutta 44 index.html <form action="login"> User Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPassword"/><br/> <input type="submit" value="submit"/> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); HttpSession session=request.getSession(false); String myName=(String)session.getAttribute("uname"); String myPass=(String)session.getAttribute("upass"); pwriter.print("Name: "+myName+" Pass: "+myPass); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } }}
MyServlet1.java Class notes for Servlet by Dr. V. Dutta 45 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); String name = request.getParameter("userName"); String password = request.getParameter("userPassword"); pwriter.print("Hello "+name); pwriter.print("Your Password is: "+password); HttpSession session=request.getSession(); session.setAttribute("uname",name); session.setAttribute("upass",password); pwriter.print("<a href='welcome'>view details</a>"); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } }}
web.xml Class notes for Servlet by Dr. V. Dutta 46 <web-app> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app>

Servlet classnotes

  • 1.
  • 2.
    Servlet • Servlet technologyis used to create a web application (resides at server side and generates a dynamic web page). • Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. However, there were many disadvantages to this technology. • There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc. Class notes for Servlet by Dr. V. Dutta 2
  • 3.
    Servlet Features • Servletis a technology which is used to create a web application. • Servlet is an API that provides many interfaces and classes including documentation. • Servlet is an interface that must be implemented for creating any Servlet. • Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests. • Servlet is a web component that is deployed on the server to create a dynamic web page. Class notes for Servlet by Dr. V. Dutta 3
  • 4.
    Web Application • Aweb application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server and respond to the HTTP request. • The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative, distributed, hypermedia information systems. It is the data communication protocol used to establish communication between client and server. • HTTP is TCP/IP based communication protocol, which is used to deliver the data like image files, query results, HTML files etc on the World Wide Web (WWW) with the default port is TCP 80. It provides the standardized way for computers to communicate with each other. Class notes for Servlet by Dr. V. Dutta 4
  • 5.
    Basic architecture ofweb application and depicts where HTTP stands. Class notes for Servlet by Dr. V. Dutta 5
  • 6.
    HTTP • HTTP ismedia independent: It specifies that any type of media content can be sent by HTTP as long as both the server and the client can handle the data content. • HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a browser initiates the HTTP request and after the request is sent the client disconnects from server and waits for the response. • HTTP is stateless: The client and server are aware of each other during a current request only. Afterwards, both of them forget each other. Due to the stateless nature of protocol, neither the client nor the server can retain the information about different request across the web pages. Class notes for Servlet by Dr. V. Dutta 6
  • 7.
    Website: static vs dynamic Itis a collection of related web pages that may contain text, images, audio and video. HTTP It is the data communication protocol used to establish communication between client and server. HTTP Requests It is the request send by the computer to a web server that contains all sorts of potentially interesting information. Get vs Post It gives the difference between GET and POST request. Container It is used in java for dynamically generating the web pages on the server side. Server: Web vs Application It is used to manage the network resources and for running the program or software that provides services. Content Type It is HTTP header that provides the description about what are you sending to the browser.Class notes for Servlet by Dr. V. Dutta 7
  • 8.
    Static Website DynamicWebsite Prebuilt content is same every time the page is loaded. Content is generated quickly and changes regularly. It uses the HTML code for developing a website. It uses the server side languages such as PHP,SERVLET, JSP, and ASP.NET etc. for developing a website. It sends exactly the same response for every request. It may generate different HTML for each of the request. The content is only changed when someone publishes and updates the file (sends it to the web server). The page contains "server-side" code which allows the server to generate the unique content when the page is loaded. Flexibility is the main advantage of static website. Content Management System (CMS) is the main advantage of dynamic website. Class notes for Servlet by Dr. V. Dutta 8
  • 9.
    HTTP is request/responseprotocol which is based on client/server based architecture. In this protocol, web browser, search engines, etc. behave as HTTP clients and the Web server like Servlet behaves as a server Class notes for Servlet by Dr. V. Dutta 9
  • 10.
    The HTTP clientsends the request to the server in the form of request message which includes following information: • The Request-line • The analysis of source IP address, proxy and port • The analysis of destination IP address, protocol, port and host • The Requested URI (Uniform Resource Identifier) • The Request method and Content • The User-Agent header • The Connection control header • The Cache control header The HTTP request method indicates the method to be performed on the resource identified by the Requested URI (Uniform Resource Identifier). Class notes for Servlet by Dr. V. Dutta 10
  • 11.
    HTTP Request Description GET Asks toget the resource at the requested URL. POST Asks the server to accept the body info attached. It is like GET request with extra info sent with the request. HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no body. TRACE Asks for the loopback of the request message, for testing or troubleshooting. PUT Says to put the enclosed info (the body) at the requested URL. DELETE Says to delete the resource at the requested URL. OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can respond Class notes for Servlet by Dr. V. Dutta 11
  • 12.
    GET POST 1) Incase of Get request, only limited amount of data can be sent because data is sent in header. In case of post request, large amount of data can be sent because data is sent in body. 2) Get request is not secured because data is exposed in URL bar. Post request is secured because data is not exposed in URL bar. 3) Get request can be bookmarked. Post request cannot be bookmarked. 4) Get request is idempotent. i.e second request will be ignored until response of first request is delivered Post request is non- idempotent. 5) Get request is more efficient and used more than Post. Post request is less efficient and used less than get.Class notes for Servlet by Dr. V. Dutta 12
  • 13.
    Class notes forServlet by Dr. V. Dutta 13
  • 14.
    CGI • CGI (CommonGateway 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. There are many problems in CGI technology (Disadvantages): • If the number of clients increases, it takes more time for sending the response. • For each request, it starts a process, and the web server is limited to start processes. • It uses platform dependent language e.g. C, C++, perl. Class notes for Servlet by Dr. V. Dutta 14
  • 15.
    Advantages 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 many benefits over the Processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet are as follows: • Better performance: because it creates a thread for each request, not process. • Portability: because it uses Java language. • Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc. • Secure: because it uses java language. Class notes for Servlet by Dr. V. Dutta 15
  • 16.
    Class notes forServlet by Dr. V. Dutta 16
  • 17.
    Class notes forServlet by Dr. V. Dutta 17
  • 18.
    Servlet Container • Itprovides the runtime environment for JavaEE (j2ee) applications. The client/user can request only a static WebPages from the server. If the user wants to read the web pages as per input then the servlet container is used in java. • The servlet container is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: Class notes for Servlet by Dr. V. Dutta 18
  • 19.
    • The servletcontainer is the part of web server which can be run in a separate process. We can classify the servlet container states in three types: • Standalone: It is typical Java-based servers in which the servlet container and the web servers are the integral part of a single program. For example:- Tomcat running by itself • In-process: It is separated from the web server, because a different program runs within the address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss. • Out-of-process: The web server and servlet container are different programs which are run in a different process. For performing the communications between them, web server uses the plug-in provided by the servlet container. Class notes for Servlet by Dr. V. Dutta 19
  • 20.
    Servlet Container functions •Life Cycle Management • Multithreaded support • Object Pooling • Security etc. Class notes for Servlet by Dr. V. Dutta 20
  • 21.
    Server • Server isa device or a computer program that accepts and responds to the request made by other program, known as client. It is used to manage the network resources and for running the program or software that provides services. There are two types of servers: • Web Server (Apache Tomcat and Resin etc). : It can be used for servlet, jsp, struts, jsf etc. It can't be used for EJB. • Application Server: It contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a server centric architecture. Examples : Jboss, Glassfish, Weblogic, Websphere. Class notes for Servlet by Dr. V. Dutta 21
  • 22.
    Servlet API • Thejavax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. • The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not specific to any protocol. • The javax.servlet.http package contains interfaces and classes that are responsible for http requests only. Class notes for Servlet by Dr. V. Dutta 22
  • 23.
    Interfaces and Classesin javax.servlet package • Servlet • ServletRequest • ServletResponse • RequestDispatcher • ServletConfig • ServletContext • SingleThreadModel • Filter • FilterConfig • FilterChain • ServletRequestListener • ServletRequestAttributeListener • ServletContextListener • ServletContextAttributeListener GenericServlet ServletInputStream ServletOutputStream ServletRequestWrapper ServletResponseWrapper ServletRequestEvent ServletContextEvent ServletRequestAttributeEvent ServletContextAttributeEvent ServletException UnavailableException Class notes for Servlet by Dr. V. Dutta 23
  • 24.
    Interfaces and Classesin javax.servlet.http package • HttpServletRequest • HttpServletResponse • HttpSession • HttpSessionListener • HttpSessionAttributeListener • HttpSessionBindingListener • HttpSessionActivationListener • HttpSessionContext (deprecated now) HttpServlet Cookie HttpServletRequestWrapper HttpServletResponseWrapper HttpSessionEvent HttpSessionBindingEvent HttpUtils (deprecated now) Class notes for Servlet by Dr. V. Dutta 24
  • 25.
    Class notes forServlet by Dr. V. Dutta 25
  • 26.
    Methods of ServletInterface public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container. public void destroy() is invoked only once and indicates that servlet is being destroyed. public ServletConfig getServletConfig() returns the object of ServletConfig. public String getServletInfo() returns information about servlet such as writer, copyright, version etc. Class notes for Servlet by Dr. V. Dutta 26
  • 27.
    Functions of Web-Container •loads the servlet class. • instantiates the servlet class. • calls the init method passing the ServletConfig object else • calls the service method passing request and response objects • The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project. Class notes for Servlet by Dr. V. Dutta 27
  • 28.
    Steps : Webcontainer handling the request  maps the request with the servlet in the web.xml file.  creates request and response objects for this request  calls the service method on the thread  The public service method internally calls the protected service method  The protected service method calls the doGet method depending on the type of request.  The doGet method generates the response and it is passed to the client.  After sending the response, the web container deletes the request and response objects. The thread is contained in the thread pool or deleted depends on the server implementation. Class notes for Servlet by Dr. V. Dutta 28
  • 29.
    Class notes forServlet by Dr. V. Dutta 29 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 }}
  • 30.
    Steps for creatingServlet in Eclipse 1) For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic web project -> write your project name e.g. first -> Finish. 2) For creating a servlet, explore the project by clicking the + icon -> explore the Java Resources -> right click on src -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish. 3) add jar file in eclipse IDE: For adding a jar file, right click on your project -> Build Path -> Configure Build Path -> click on Libraries tab in Java Build Path -> click on Add External JARs button -> select the servlet-api.jar file under tomcat/lib -> ok. 4) Start the server and deploy the project: For starting the server and deploying the project in one step, Right click on your project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll -> finish. 5) Now tomcat server has been started and project is deployed. To access the servlet write the url pattern name in the URL bar of the browser. In this case Hello then enter. Class notes for Servlet by Dr. V. Dutta 30
  • 31.
    ServletRequest Interface An objectof ServletRequest is used to provide the client request information to a servlet such as content type, content length, parameter names and values, header information, attributes etc. Its methods are: public String getParameter(String name): is used to obtain the value of a parameter by name. public String[] getParameterValues(String name): returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box. java.util.Enumeration getParameterNames():returns an enumeration of all of the request parameter names. public int getContentLength():Returns the size of the request entity data, or -1 if not known. public String getCharacterEncoding():Returns the character set encoding for the input of this request. public String getContentType():Returns the Internet Media Type of the request entity data, or null if not known. public ServletInputStream getInputStream() throws IOException: Returns an input stream for reading binary data in the request body. public abstract String getServerName() :Returns the host name of the server that received the request. public int getServerPort(): Returns the port number on which this request was received. Class notes for Servlet by Dr. V. Dutta 31
  • 32.
    Example of ServletRequestto display the name of the user 1) index.html <form action="welcome" method="get"> Enter your name<input type="text" name="name"><br> <input type="submit" value="login"> </form> Class notes for Servlet by Dr. V. Dutta 32 import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class DemoServ extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); String name=req.getParameter("name");//will return value pw.println("Welcome "+name); pw.close(); }}
  • 33.
    RequestDispatcher interface The RequestDispatcherinterface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration. There are two methods defined in the RequestDispatcher interface. • public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. • public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException: Includes the content of a resource (servlet, JSP page, or HTML file) in the response. Class notes for Servlet by Dr. V. Dutta 33
  • 34.
    Class notes forServlet by Dr. V. Dutta 34
  • 35.
    The getRequestDispatcher() method ThegetRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax : public RequestDispatcher getRequestDispatcher(String resource) ; RequestDispatcher rd=request.getRequestDispatcher("servlet 2"); //servlet2 is the url-pattern of the second servlet rd.forward(request, response); //method may be include or forward • Class notes for Servlet by Dr. V. Dutta 35
  • 36.
    Example of RequestDispatcherinterface • index.html file: for getting input from the user. • Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet. • WelcomeServlet.java file: a servlet class for displaying the welcome message. • web.xml file: a deployment descriptor file that contains the information about the servlet. Class notes for Servlet by Dr. V. Dutta 36
  • 37.
    Class notes forServlet by Dr. V. Dutta 37
  • 38.
    Class notes forServlet by Dr. V. Dutta 38 index.html <form action="servlet1" method="post"> Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPass"/><br/> <input type="submit" value="login"/> </form> // WelcomeServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); } }
  • 39.
    Class notes forServlet by Dr. V. Dutta 39 //Login.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet"){ RequestDispatcher rd=request.getRequestDispatcher("servlet2"); rd.forward(request, response); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=request.getRequestDispatcher("/index.html"); rd.include(request, response); } } }
  • 40.
    Class notes forServlet by Dr. V. Dutta 40 web.xml <web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> </servlet> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/servlet2</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
  • 41.
    Session Tracking • Sessiontracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time. Sessions are shared among the servlets accessed by a client. • The HttpSession object is used for session management. A session contains information specific to a particular user across the whole application. When a user enters into a website (or an online application) for the first time HttpSession is obtained via request.getSession(), the user is given a unique ID to identify his session. This unique ID can be stored into a cookie or in a request parameter. • The HttpSession stays alive until it has not been used for more than the timeout value specified in tag in deployment descriptor file( web.xml). The default timeout value is 30 minutes, this is used if you don’t specify the value in tag. This means that when the user doesn’t visit web application time specified, the session is destroyed by servlet container. The subsequent request will not be served from this session anymore, the servlet container will create a new session.Class notes for Servlet by Dr. V. Dutta 41
  • 42.
    Class notes forServlet by Dr. V. Dutta 42 Cookies :A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. This may not be an effective way because many time browser does not support a cookie, so not recommended to use this procedure to maintain the sessions.
  • 43.
    Class notes forServlet by Dr. V. Dutta 43 Few methods of HttpSession public void setAttribute(String name, Object value): Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. If an attribute already exists, then this method replaces the existing attributes. public Object getAttribute(String name): Returns the String object specified in the parameter, from the session object. If no object is found for the specified attribute, then the getAttribute() method returns null. public Enumeration getAttributeNames(): Returns an Enumeration that contains the name of all the objects that are bound as attributes to the session object. public void removeAttribute(String name): Removes the given attribute from session. setMaxInactiveInterval(int interval): Sets the session inactivity time in seconds. This is the time in seconds that specifies how long a sessions remains active since last request received from client.
  • 44.
    MyServlet2.java and index.html Class notesfor Servlet by Dr. V. Dutta 44 index.html <form action="login"> User Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPassword"/><br/> <input type="submit" value="submit"/> import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); HttpSession session=request.getSession(false); String myName=(String)session.getAttribute("uname"); String myPass=(String)session.getAttribute("upass"); pwriter.print("Name: "+myName+" Pass: "+myPass); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } }}
  • 45.
    MyServlet1.java Class notes forServlet by Dr. V. Dutta 45 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter pwriter = response.getWriter(); String name = request.getParameter("userName"); String password = request.getParameter("userPassword"); pwriter.print("Hello "+name); pwriter.print("Your Password is: "+password); HttpSession session=request.getSession(); session.setAttribute("uname",name); session.setAttribute("upass",password); pwriter.print("<a href='welcome'>view details</a>"); pwriter.close(); }catch(Exception exp){ System.out.println(exp); } }}
  • 46.
    web.xml Class notes forServlet by Dr. V. Dutta 46 <web-app> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>MyServlet1</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>Servlet2</servlet-name> <servlet-class>MyServlet2</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet2</servlet-name> <url-pattern>/welcome</url-pattern> </servlet-mapping> </web-app>