Chapter 6 Servlet (1) PDF
Document Details
Uploaded by Deleted User
Biradar R.Y.
Tags
Summary
This document is a presentation, or lecture notes, about Java servlets. It discusses servlets, their objectives, how they relate to web applications, and comparisons to CGI. It covers core concepts of servlets, including the life cycle (init, service, and destroy methods) and various aspects of handling requests and responses. There are also sections on cookies and session tracking. The document is targeted towards students or professionals learning about Java servlets.
Full Transcript
Servlets Marks:14 Prepared by Biradar R.Y. Specific Objectives: To write web based applications using servlets To write servlet for cookies and session tracking. What is a Servlet? Servlet is a technology i.e. used to create web application. (reside...
Servlets Marks:14 Prepared by Biradar R.Y. Specific Objectives: To write web based applications using servlets To write servlet for cookies and session tracking. What is a Servlet? Servlet is a technology i.e. used to create web application. (resides at server side and generates dynamic web page). Servlet technology is robust and scalable. 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. Servlet technology is used to create web application 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. CGI(Commmon Gateway Interface) Before Servlet, CGI (Common Gateway Interface) scripting language was common as a server-side programming language. 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. httpd is the Apache HyperText Transfer Protocol (HTTP) server program. Disadvantages of CGI 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. Advantage of Servlet 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. Faster: because it creates a thread Platform independent. Advantage of Servlet SERVLET CGI(COMMON GATEWAY INTERFACE) Servlets are portable and CGI is not portable efficient. In Servlets, sharing of data is In CGI, sharing of data is not possible. possible. Servlets can directly CGI cannot directly communicate with the web communicate with the web server. server. Servlets are less expensive CGI are more expensive than than CGI. Servlets. Servlets can handle the CGI cannot handle the cookies. cookies. Life Cycle of a Servlet Servlet life cycle contains five steps: 1) Loading of Servlet 2) Creating instance of Servlet 3) Invoke init() once 4) Invoke service() repeatedly for each client request 5) Invoke destroy() Life cycle of servlet the entire life cycle of a Servlet is managed by the Servlet container/Web Container init() method A servlet’s life begins here. called only once to load the servlet. This method receives only one parameter i.e ServletConfig object. Can throw the ServletException. Once the servlet is initialized, it is ready to handle the client request. Syntax: public void init(ServletConfig con)throws ServletException { ----- } service() method The web server calls the service() method to handle requests coming from the client( web browsers) and to send response back to the client. This method determines the type of Http request (GET, POST, PUT, DELETE, etc.). This method also calls various other methods such as doGet(), doPost(), doPut(), doDelete(), etc. as required. Syntax: public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { ----- } destroy() method called only once. It is called at the end of the life cycle of the servlet. performs various tasks such as closing connection with the database, releasing memory allocated to the servlet, releasing resources that are allocated to the servlet and other cleanup activities. When this method is called, the garbage collector comes into action. Syntax public void destroy() { // Finalization code... } Servlet API Servlet use classes and interfaces from 2 packages 1) javax.servlet ◦It contains classes to support generic protocol 2) javax.servlet.http ◦ It extends classes in servlet package to add HTTP specific functionality. Interfaces in javax.servlet package Servlet It provides 3 life cycle methods. ServletConfig Allows Servlets to get initialization parameters ServletContext Enables Servlets to access information about their environment. ServletRequest Used to read data from a client request. ServletRespons Used to write data to a client response. e Classes in javax.servlet package GenericServlet Implements Servlet, ServletConfig and Serializable interfaces ServletInputStream Provides an input stream for reading requests from client. ServletOutputStream Provides an output stream for writing responses to a client. ServletException Indicates a Servlet error occurred. UnavailableException Indicates a Servlet is unavailable. Interfaces in javax.servlet.http package HttpServletRequest Enables Servlet to read data from HTTP request HttpServletResponse Enables Servlet to write data to HTTP response. HttpSession Allows session data to be read and written HttpSessionListener Interface for receiving notification events about HttpSession lifecycle changes. HttpSessionBindingListener Informs an object that is bound to or unbound from a session. Classes in javax.servlet.http package HttpServlet Provides methods to handle HTTP requests and responses. Cookie Allows state information to be stored on a client machine. HttpSessionEvent Encapsulates session changed event. HttpSessionBindingEve Indicates when a listener is bound or unbound from a session nt Interfaces in javax.servlet package 1) Servlet Servlet interface needs to be implemented for creating any Servlet. It provides 3 life cycle methods: init(), service(), and destroy() It initializes the servlet. It is the life cycle method of servlet and void init(ServletConfig config) invoked by the web container only once. void service(ServletRequest Provides response for the request,ServletResponse incoming request. It is invoked response) at each request by the web container. void destroy() It is invoked only once and indicates that servlet is being destroyed. ServletConfig returns the object of getServletConfig() ServletConfig that contains any initialization parametrs String getServletInfo() returns information about servlet such as writer, copyright, version etc. Interfaces in javax.servlet package 2) ServletConfig ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file. we don't need to edit the servlet file if information is modified from the web.xml file. ServletContext Returns an object of getServletContext() ServletContext. String getServletName() Returns the name of the servlet. String getInitParameter(String Returns the parameter value name) for the specified parameter name Enumeration Returns an enumeration of all getInitParameterNames(): the initialization parameter names. Interfaces in javax.servlet package 3) ServletContext ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application. Methods of ServletContext String getInitParameter(String Returns the parameter value for name) the specified parameter name. Enumeration Returns the names of the getInitParameterNames() context's initialization parameters. void setAttribute(String sets the given object in the name,Object object) application scope. Object getAttribute(String Returns the attribute for the name) specified name. Enumeration Returns the names of the getInitParameterNames(): context's initialization parameters as an Enumeration of String objects. void removeAttribute(String Removes the attribute with the name) given name from the servlet context. Interfaces in javax.servlet package 4) ServletRequest used to provide the client request information to a servlet such as content type, content length, parameter names and values, header informations, attributes etc.. String getParameter(String name) used to obtain the value of a parameter by name. String[] getParameterValues(String returns an array of String containing name) all values of given parameter name. Enumeration getParameterNames() returns an enumeration of all of the request parameter names. Methods of ServletRequest int getContentLength() Returns the size of the request entity data, or -1 if not known. String getCharacterEncoding() Returns the character set encoding for the input of this request. String getContentType() Returns the Internet Media Type of the request entity data, or null if not known. ServletInputStream getInputStream() Returns an input stream for reading throws IOException binary data in the request body. abstract String getServerName() Returns the host name of the server that received the request. int getServerPort() Returns the port number on which this request was received. Interfaces in javax.servlet package 5) ServletResponse used to provide the response to the clients request. response either as character or binary data. PrintWriter stream can be used to send character data as servlet response, and ServletOutputStream stream to send binary data as servlet Methods of ServletResponse String getCharacterEncoding() It returns the name of the charset used in the response sent to the client. String getContentType() It returns the response content type. e.g. text, html etc.. ServletOutputStream Returns a ServletOutputStream suitable getOutputStream() for writing binary data in the response. PrintWriter getWriter() Returns the PrintWriter object. void setCharacterEncoding( String Set the charset (character encoding) of charset) the response. void setContentLength(int len) It sets the length of the response body. void setContentType(String type) Sets the type of the response data. Interfaces in javax.servlet.http package 1) HttpServletRequest extends the ServletRequest interface. allow request information for HTTP Servlet String getAuthType() Returns the name of the authentication scheme used to protect the Servlet. String getContextPath () Returns the portion of the request URI that indicates the context of the request. Cookie [] getCookies ( ) Returns an array containing all of the cookie objects the client sent with this request. String getHeader(String name) Returns the value of the specified request header as a string. Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains. Methods of HttpServletRequest String getMethod() Returns the name of the HTTP method with which this request was made, String getPathlnfo() Returns any extra path information associated with the URL the client sent when it made this request. String getQueryString () Returns the query string that is contained in the request URL after the path. public HttpSession getSession () Returns the current session associated with this request, or if the request does not have a session, creates one. HttpSession getSession(boolean Returns the current HttpSession associated create) with this request or, if there is no current. session and create is true, returns a new session Interfaces in javax.servlet.http package 2) HttpServletResponse void addCookie(Cookie cookie) Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie. void addHeader(String name, String Adds a response header with the given name value) and value. boolean containsHeader(String Returns a boolean indicating whether the name) named response header has already been set. void sendRedirect(string location) Sends a temporary redirect response to the throws IOException client using the specified redirect location URL. void setHeader(String name, String Sets a response header with the given name value) and value. void setStatus(int sc) Sets the status code for this response HTTP Request Methods GET Used to retrieve resource representation/information only – and not to modify it in any way. POST Used to create a new resource into the collection of resources. For example, customer information, file upload, etc. using HTML forms. Same as GET but returns only HTTP headers and no document body. Header contains the HEAD entries such as content-type, content-length, last- modified, etc. Used to update existing resource. If the resource does not exist then API may decide to PUT create a new resource or not. For ex. Put an image file on the server. Used to delete resources identified by the DELETE Request-URI. HTTP Request Methods Describes the communication options for the target OPTIONS resource. Establishes a tunnel to the server identified by a given CONNECT URI. The TRACE method is used to echo the contents of an TRACE HTTP Request back to the requester which can be used for debugging purpose at the time of development. HTTP status/response code 1xx Informational Response (100–199) It means the request has been received and the process is continuing. 2xx Successful Response( 200-299) It means the action was successfully received, understood, and accepted. Redirection (300-399) 3xx It means further action must be taken in order to complete the request. Client Errors (400-499) 4xx It means the request contains incorrect syntax or cannot be fulfilled. Server Errors (500-599) 5xx It means the server failed to fulfill an apparently valid request. HTTP status/response code 200 Ok 201 Created 400 Bad Request 403 Forbidden 404 Not Found 500 Internal Server Error 503 Service Unavailable What is the difference between Get and Post? GET POST 1) In case of Get request, only In case of post request, large limited amount of data can be amount of data can be sent sent because data is sent in because data is sent in body. header. 2) Get request is not secured Post request is secured because because data is exposed in URL data is not exposed in URL bar. bar. 3) Get request can be Post request cannot be bookmarked bookmarked 4) GET requests remain in the POST requests do not remain in browser history the browser history 5) Get request have length Post request have no restrictions restrictions on data length. POST is used to send data to a 6) GET is used to request data server to create/update a from a specified resource resource. Interfaces in javax.servlet.http package 3) HttpSession container creates a session id for each user. this id can be used to identify the particular user. An object of HttpSession can be used to perform two tasks: 1. bind objects 2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time. How to get the HttpSession object ? The HttpServletRequest interface provides two methods to get the object of HttpSession public HttpSession getSession () Returns the current session associated with this request, or if the request does not have a session, creates one. HttpSession getSession(boolean create) Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session Methods of HttpSession String getId() Returns a string containing the unique identifier value long getCreationTime() Returns the time when this session was created. long getLastAccessedTime() Returns the last time the client sent a request associated with this session invalidate() Invalidates this session then unbinds any objects bound to it. Servlet Example The servlet can be created by three ways: By implementing Servlet interface, By inheriting GenericServlet class, By inheriting HttpServlet class Servlet Class Hierarchy GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. provides the implementation of all the methods of these interfaces except the service method can handle any type of request it is protocol-independent Generic Servlet supports for HTTP, FTP and SMTP protocols. import javax.servlet.*; import java.io.*; public class DemoServlet extends GenericServlet{ public void service(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(""); pw.println("Welcome to servlet"); pw.println(""); pw.close();//closing the stream }} HttpServlet class extends the GenericServlet class and implements Serializable interface. provides http specific methods such as doGet, doPost, doHead, doTrace etc. can handle only HTTP request it is protocol-dependent HttpServlet supports only HTTP protocols. 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(""); pw.println("Welcome to servlet"); pw.println(""); pw.close();//closing the stream }} Cookies in Servlet As HTTP is a stateless protocol, information is not automatically saved between HTTP requests. Web applications use cookies to store state information on the client. A cookie is a small piece of information that a web application can store on the client machine of users. It is sent by the server to the browser. Size of Cookie: 4 kilo bytes kept for various information tracking purpose A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Cookie data comes in name-value pairs. How Cookie works? By default, each request is considered as a new request. In cookies technique, we add cookie with response from the Servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user. Types of Cookie types of cookies in servlets:- 1. Non-persistent cookie (Session Cookie) 2. Persistent cookie (Permanent Cookie) Non-persistent cookie It is valid for single session only. These cookies are lost when the user exits the web application. Such cookies are identified by a session ID. Stored in memory. Persistent cookie It is valid for multiple session. It is used to store long-term information. It is not removed each time when user closes the browser. These cookies are lost when they expire. Stored in permanent storage. Advantage of Cookies Simplest technique of maintaining the state. Cookies are maintained at client side. Disadvantage of Cookies It will not work if cookie is disabled from the browser. Only textual information can be set in Cookie object. Several limitations exist on the size of the cookie text(4kb in general), number of cookies(20 per site in general), etc. Cookie class javax.servlet.http package contains Cookie class Constructor ◦ Cookie() : constructs a cookie ◦ Cookie(String name, String value) :constructs a cookie with a specified name and value. For adding cookie or getting the value from the cookie, void addCookie(Cookie ck) method of HttpServletResponse interface is used to add cookie in response object. Cookie[] getCookies() method of HttpServletRequest interface is used to return all the cookies from the browser Methods defined by Cookie class Sets the maximum age of the cookie void setMaxAge(int expiry) in seconds. Returns the maximum age of the Int getMaxAge() cookie in seconds. Returns the name of the cookie. The String getName() name cannot be changed after creation. void setName(String name) changes the name of the cookie. String getValue() Returns the value of the cookie. void setValue(String value) changes the value of the cookie. String getpath() Returns the path. Returns true if the cookie is secure. boolean getSecure() Otherwise returns false void setSecure(boolean Sets the security flag. secure) How to add Cookie? Cookie ck=new Cookie("user",“abc");//creating cookie object response.addCookie(ck);//adding cookie in the response How to delete Cookie? Cookie ck=new Cookie("user","");//deleting value of cookie ck.setMaxAge(0);//changing the maximum age to 0 seconds response.addCookie(ck);//adding cookie in the response How to get Cookies? Cookie ck[]=request.getCookies(); for(int i=0;i