






































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







































Servlets are small programs that execute on the server side of a Web connection. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server. Servlets are generic extensions to Java-enabled servers. They are secure, portable, and easy to use replacement for CGI. Servlet is a dynamically loaded module that services requests from a Web server and executed within the Java Virtual Machine. Because the servlet is running on the server side, it does not depend on browser compatibility. Servlet’s Job
HTTP is the protocol that allows web servers and browsers to exchange data over the web. It is a request and response protocol. The client requests a file and the server responds to the request. HTTP uses reliable TCP connections—by default on TCP port 80. HTTP (currently at version 1.1 at the time of this writing) was first defined in RFC 2068. It was then refined in RFC 2616, which can be found at http://www.w3c.org/Protocols/. In HTTP, it's always the client who initiates a transaction by establishing a connection and sending an HTTP request. The server is in no position to contact a client or make a callback connection to the client. Either the client or the server can prematurely terminate a connection. For example, when using a web browser we can click the Stop button on our browser to stop the download process of a file, effectively closing the HTTP connection with the web server. HTTP Requests An HTTP transaction begins with a request from the client browser and ends with a response from the server. An HTTP request consists of three components:
An example of an HTTP request is the following: GET /servlet/default.jsp HTTP/1. Accept: text/plain; text/html Accept-Language: en-gb Connection: Keep-Alive Host: localhost Referer: http://localhost/ch8/SendDetails.htm User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) Content-Length: 33 Content-Type: application/x-www-form- urlencoded Accept-Encoding: gzip, deflate LastName=Franks&FirstName=Michael The method—URI—protocol version appears as the first line of the request. GET /servlet/default.jsp HTTP/1. where GET is the request method, /servlet/default.jsp represents the URI and HTTP/1.1 the Protocol/Version section. The request method will be explained in more details in the next section, "HTTP request Methods." The URI specifies an Internet resource completely. A URI is usually interpreted as being relative to the server's root directory. Thus, it should always begin with a forward slash /. A URL is actually a type of URI (see http://www.ietf.org/rfc/rfc2396.txt). The Protocol version represents the version of the HTTP protocol being used. The request header contains useful information about the client environment and the entity body of the request. For example, it could contain the language the browser is set for, the length of the entity body, and so on. Each header is separated by a carriage return/linefeed (CRLF) sequence. Between the headers and the entity body, there is a blank line (CRLF) that is important to the HTTP request format. The CRLF tells the HTTP server where the entity body begins. In some Internet programming books, this CRLF is considered the fourth component of an HTTP request. In the previous HTTP request, the entity body is simply the following line: LastName=Franks&FirstName=Michael The entity body could easily become much longer in a typical HTTP request. Method Description GET GET is the simplest, and probably, most used HTTP method. GET simply retrieves the data identified by the URL. If the URL refers to a script (CGI, servlet, and so on), it returns the data produced by the script. HEAD The HEAD method provides the same functionality as GET, but HEAD only returns HTTP headers without the document body. POST Like GET, POST is also widely used. Typically, POST is used in HTML
Applications of Java Servlets
PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Servlet Testing"); out.println(""); out.println(""); out.println("Welcome to the Servlet Testing Center"); out.println(""); out.println(""); } } Now, save TestingServlet.java file to /bin directory of JDK.
Testing TestingServlet
class> TestingServlet /servlets/servlet/TestingServlet
The web.xml file has one element—web-app. We should write all our servlets under . For each servlet, we have a element and we need the and elements. The is the name for our servlet, by which it is known Tomcat. The is the compiled file of your servlet without the .class extension. Location of servlet-api.jar file Location of web.xml file Location for storing .java and .class files We can also add multiple servlet names in our file using multiple servlet tags. The url-pattern suggests the url by which we are going to class our servlet in the web browser. Instead of doing this we can just modify the contents of web.xml by adding the names and mapping of our servlet code.
The javax.servlet package contains seven interfaces, three classes, and two exceptions. The seven interfaces are as follows:
Collection Fig. Servlet’s Life Cycle The init( ) method
The following program contains the code for a servlet named PrimitiveServlet, a very simple servlet that exists to demonstrate the life cycle of a servlet. The PrimitiveServlet class implements javax.servlet.Servlet (as all servlets must) and provides implementations for all the five methods of servlet. What it does is very simple. Each time any of the init, service, or destroy methods is called, the servlet writes the method's name to the console. import javax.servlet.*; import java.io.IOException; public class PrimitiveServlet implements Servlet { public void init(ServletConfig config) throws ServletException { System.out.println("init"); } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("service"); } public void destroy() { System.out.println("destroy"); } public String getServletInfo() { return null; } public ServletConfig getServletConfig() { return null; } } The web.xml File for PrimitiveServlet:
PrimitiveServlet PrimitiveServlet
We should then be able to call this servlet from our browser by typing the following URL: http://localhost:8080/examples/servlets/servlet/PrimitiveServlet The first time the servlet is called, the console displays these two lines:
Author:
The RequestDemoServlet.java file: import javax.servlet.*; import java.util.Enumeration; import java.io.IOException; public class RequestDemoServlet implements Servlet { public void init(ServletConfig config) throws ServletException { } public void destroy() { } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("Server Port: " + request.getServerPort()); System.out.println("Server Name: " + request.getServerName()); System.out.println("Protocol: " + request.getProtocol()); System.out.println("Character Encoding: " + request.getCharacterEncoding()); System.out.println("Content Type: " + request.getContentType()); System.out.println("Content Length: " + request.getContentLength()); System.out.println("Remote Address: " + request.getRemoteAddr()); System.out.println("Remote Host: " + request.getRemoteHost()); System.out.println("Scheme: " + request.getScheme()); Enumeration parameters = request.getParameterNames(); while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); System.out.println("Parameter Name: " + parameterName); System.out.println("Parameter Value: " + request.getParameter(parameterName)); } Enumeration attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); System.out.println("Attribute name: " + attribute); System.out.println("Attribute value: " + request.getAttribute(attribute)); } } public String getServletInfo() { return null;
public ServletConfig getServletConfig() { return null; } } The ServletResponse Interface The ServletResponse interface represents the response to the user. The most important method of this interface is getWriter, from which we can obtain a java.io.PrintWriter object that we can use to write HTML tags and other text to the user. The codes of the program given below offer an HTML file named index2.html and a servlet whose service method is overridden with code that outputs some HTML tags to the user. This servlet modifies the example below retrieves various information about the user. Instead of sending the information to the console, the service method sends it back to the user. index2.html
Sending a request
out.println("Parameter Name: " + parameterName); out.println("Parameter Value: " + request.getParameter(parameterName)); } Enumeration attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); out.println("Attribute name: " + attribute); out.println("Attribute value: " + request.getAttribute(attribute)); } out.println(""); out.println(""); } public String getServletInfo() { return null; } public ServletConfig getServletConfig() { return null; } }
Till this point, we have been creating servlet classes that implement the javax.servlet.Servlet interface. Everything works fine, but there are two annoying things that we've probably noticed:
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(""); out.println("Extending GenericServlet"); out.println(""); out.println(""); out.println(""); out.println("Extending GenericServlet makes your code simpler."); out.println(""); out.println(""); } }
The HttpServlet class extends the javax.servlet.GenericServlet class. The HttpServlet class also adds a number of interesting methods to use. The most important are the six doxxx methods that get called when a related HTTP request method is used. The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace. Each doxxx method is invoked when a corresponding HTTP method is used. For instance, the doGet method is invoked when the servlet receives an HTTP request that was sent using the GET method. Of the six doxxx methods, the doPost and the doGet methods are the most frequently used. The doPost method is called when the browser sends an HTTP request using the POST method. The POST method is one of the two methods that can be used by an HTML form. Consider the following HTML form at the client side:
When the user clicks the Submit button to submit the form, the browser sends an HTTP request to the server using the POST method. The web server then passes this request to the Register servlet and the doPost method of the servlet is invoked. Using the POST method in a form, the parameter name/value pairs of the form are sent in the request body. For example, if we use the preceding form as an example and enter ‘Sunil’ as the value for firstName and ‘Go’ as the value for lastName, we will get the following result in the request body: firstName=Sunil
public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("The GET method"); out.println(""); out.println(""); out.println("The servlet has received a GET. "
In addition to providing several more protocol-specific methods in the
HttpServlet class, the javax.servlet.http package also provides more sophisticated request and response interfaces. Obtaining HTTP Request Headers from HttpServletRequest The HTTP request that a client browser sends to the server includes an HTTP request header with important information, such as cookies and the referer. We can access these headers from the HttpServletRequest object passed to a doxxx method. The following example demonstrates how we can use the HttpServletRequest interface to obtain all the header names and sends the header name/value pairs to the browser. //Obtaining HTTP request Headers import javax.servlet.; import javax.servlet.http.; import java.io.; import java.util.; public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration enumeration = request.getHeaderNames(); while(enumeration.hasMoreElements()) { String header = (String) enumeration.nextElement(); out.println(header + ": " + request.getHeader(header) + ""); } } } The RegisterServlet given above uses the getHeaderNames and the getHeader methods. The getHeaderNames is first called to obtain an Enumeration containing all the header names found in the client request. The value of each header then is retrieved by using the getHeader method, passing a header name. The output of the code depends on the client environment, such as the browser used and the operating system of the client's machine. For example, some browsers might send cookies to the server. Also, whether the servlet is requested by the user typing the URL in the Address/Location box or by clicking a hyperlink also accounts for the presence of an HTTP request header called referer. Obtaining the Query String from HttpServletRequest