Professional Documents
Culture Documents
TEA-I-Unit-3 - Servlets-Notes
Unit-3: Servlets:
3.1 What is a Server?
A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download a file, send email A server is also the software that responds to these requests; a client could be the browser or other software making these requests Typically, your little computer is the client, and someone elses big computer is the server However, any computer can be a server It is not unusual to have server software and client software running on the same computer Ex: Apache Tomcat is a Server Apache is a very popular server o 66% of the web sites on the Internet use Apache o Apache is: Full-featured and extensible Efficient Robust Secure Up to date with current standards Open source Free
Browser
HTML
CGI or Servlet
Server
Contact: khutub27@gmail.com
Page 1
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the Hyper Text Transfer Protocol. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server. Servlets are server side components that provide a powerful mechanism for developing web applications.
Using servlets we can create fast and efficient server side applications and can run it on any servlet enabled web server. Servlet runs entirely inside the JVM (Java Virtual Machine). Since the servlet runs on server side so it does not depend on browser compatibility.
Request
Servlet
Client
Response
Server
Contact: khutub27@gmail.com
Page 2
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
The content of the dynamic web pages need to be generated dynamically. In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request. The process would open connections to one or more databases in order to obtain the necessary information. It communicated with the Web server via an interface known as the Common Gateway Interface (CGI).
3.2.1 How Does CGI works? Why use Servlet when CGI is available?
In CGI every time a request is made a new process starts Ex: let say 100 instances of an application require CGI program to process their request simultaneously, the CGI program must be loaded 100 times in memory. (100 copies are made) It Degrades the performance as the instance increases Once CGI program terminates all the data used by the process is lost and cannot be used by other programs
Contact: khutub27@gmail.com
Page 3
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
Servlets Architecture:
Following diagram shows the position of Servlets in a Web Application.
Contact: khutub27@gmail.com
Page 4
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
A java Servlet is a java class that reads request sent from a client and responds by sending information to the client. The java class must extend HttpServlet and override the Httpservlets doGet() or doPost() methods doGet() used when request is sent using the METHOD=GET attribute of HTML doPost() used when request is sent using the METHOD=POST attribute of HTML Both doGet() and doPost() requires two arguments The first argument is an HttpservletRequest object The secons argument is an HttpservletResponse object The HttpSevletRequest used to receive request from cleint. The HttpServletResponse is used to Respond to Client. (format of data response depends on client, ex: data given is in the form of a HTML or XML page if the client is a browser) Both throws ServletExcetion and IOException
Contact: khutub27@gmail.com
Page 5
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
constructor() destroy()
init()
init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a servlet. They are implemented by every servlet and are invoked at specific times by the server. Procedure: First, user enters URL, browser then generates an HTTP request for this URL, & this request is then sent to the appropriate server. Second, this HTTP request is received by web server, web server maps this request to a particular servlet. The servlet is dynamically retrieved & loaded into the address space of the server. Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself. Fourth, the server invokes the service ( ) method of the servlet. This method is called to process the HTTP request. It may also formulate an HTTP response for the client. The service( ) method is called for each HTTP request. Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet.
Contact: khutub27@gmail.com
Page 6
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
Packages
The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet container. The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container.
javax.servlet
javax.servlet.http
Contact: khutub27@gmail.com
Page 7
TEA-I-Unit-3 - Servlets-Notes
The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.
Interface Summary
RequestDispatcher Servlet ServletConfig ServletContext ServletRequest ServletResponse Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. Defines methods that all servlets must implement. A servlet configuration object used by a servlet container to pass information to a servlet during initialization. Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. Defines an object to provide client request information to a servlet. Defines an object to assist a servlet in sending a response to the client.
Method Summary
void destroy() Called by the servlet container to indicate to a servlet that the servlet is being taken out of service. ServletConfig getServletConfig() Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. java.lang.String getServletInfo() Returns information about the servlet, such as author, version, and copyright. void init(ServletConfig config) Called by the servlet container to indicate to a servlet that the servlet is being placed into service. void service(ServletRequest req, ServletResponse res) Called by the servlet container to allow the servlet to respond to a request.
Contact: khutub27@gmail.com
Page 8
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
The following table summarizes the core classes that are provided in the javax.servlet package.
Class Summary
GenericServlet ServletInputStream ServletOutputStream ServletRequestAttributeEvent ServletRequestEvent The GenericServlet Class The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet implements the Servlet and ServletConfig interfaces. In addition, a method to append a string to the server log file is available. The signatures of this method are shown here: void log(String s) void log(String s, Throwable e) Here, s is the string to be appended to the log, and e is an exception that occurred. Defines a generic, protocol-independent servlet. Provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time. Provides an output stream for sending binary data to the client. This is the event class for notifications of changes to the attributes of the servlet request in an application. Events of this kind indicate lifecycle events for a ServletRequest.
The Servlet Exception Classes javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. The second is UnavailableException, which extends ServletException. It indicates that a servlet is unavailable.
Contact: khutub27@gmail.com
Page 9
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
File Name: PostParametersServlet.java package ServletPrograms; import java.io.*; import javax.servlet.ServletException; import javax.servlet.http*; public class prog2 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException { PrintWriter out=response.getWriter(); out.println("<html>"); out.println("<head><title>user password</title></head>"); out.println("<body>"); String username=request.getParameter("username"); String password=request.getParameter("password"); out.println("username = "+username); out.println("<br>"); out.println("password = "+password); out.println("</body></html>"); out.close(); } }
Contact: khutub27@gmail.com
Page 10
Department of MCA
File Name: PostParameters.html
TEA-I-Unit-3 - Servlets-Notes
<html> <body> <form action="prog2" method="post"> <table> <tr> <td><B>username</b></td> <td><input type=text name="username"></td> </tr> <tr><td><B>password</b></td> <td><input type=password name="password"></td> </tr> </table> <input type=submit value="submit"> </form> </body> </html>
Deployment Descriptor
How does the Container know which Servlet the client has requested for? A Servlet can have 3 names Client known URL name Deployer known secret internal name Actual file name
Web.xml file <web-app> <servlet> <servlet-name> prog2</servlet-name> <servlet-class>Programs.prog2</servlet-class> </servlet> <servlet-mapping> <servlet-name> prog2</servlet-name> <url-pattern>prog2</ url-pattern > </servlet-mapping> </web-app>
Web.xml file It is a deployment descriptor which is by default created by netbean, but in manual procedure we have to create it. With respect to practical exam students should write this file contents too. This file is common for all servlet programs with only change in servlet-name, url, class name as highlighted below
Contact: khutub27@gmail.com
Page 11
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
Output:
The javax.servlet.http Package The javax.servlet.http package contains a number of interfaces classes that are commonly used by servlet developers.
Interface Summary
HttpServlet HttpServletRequest Extends the ServletRequest interface to provide request information for HTTP servlets. Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
HttpServletResponse HttpSession
Contact: khutub27@gmail.com
Page 12
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
Contact: khutub27@gmail.com
Page 13
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
Contact: khutub27@gmail.com
Page 14
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
3.8 Difference between HTTP doGet and HTTP doPost methods of Servlet
Difference Type HTTP Request GET (doGet()) The request contains only the request line and HTTP header. Query string or form data is simply appended to the URL as name-value pairs. The form elements are passed to the server by appending at the end of the URL. The parameter data is limited (the limit depends on the container normally 4kb) GET is Idempotent(can be
applied multiple times without changing the result)
POST (doPost()) Along with request line and header it also contains HTTP body. Form name-value pairs are sent in the body of the request, not in the URL itself. The form elements are passed in the body of the HTTP request. Can send huge amount of data to the server. POST is not idempotent(warns if applied
multiple times without changing the result)
URL Pattern
Parameter passing
Size
Idempotency
Usage
Generally used to fetch some information from the host. Not Safe - A person standing over your shoulder can view your userid/pwd if submitted via Get (Users can see data in address bar.) Supports ASCII.
Security
Safe - No one will be able to view what data is getting submitted (Data hidden from users.)
Data Format
Contact: khutub27@gmail.com
Page 15
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
Web application initialization: First of all the web container reads the deployment descriptor file and then creates a name/value pair for each <context-param> tag. After creating the name/value pair it creates a new instance of ServletContext. Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters. The servlet and jsp which are part of the same web application can have the access of the ServletContext. The Context init parameters are available to the entire web application not just to the single servlet like servlet init parameters. How can we do the mapping of the Context init parameters in web.xml Web.xml File: <servlet> <servlet-name>Mapping</servlet-name> <servlet-class>ContextMapping</servlet-class> </servlet> <context-param> <param-name>Email</param-name> <param-value>admin@roseindia.net</param-value> </context-param> In the servlet code we will write this as ServletContext context = getServletContext(); pw.println(context.getInitParameter("Email");
Contact: khutub27@gmail.com
Page 16
Department of MCA
TEA-I-Unit-3 - Servlets-Notes
Contact: khutub27@gmail.com
Page 17