Servlets
03:18Introduction to Java Servlet
A Servlet is a Java programming language class used to extend the capabilities of a server. Although servlets can respond to any types of requests, they are commonly used to extend the applications hosted by web servers, so they can be thought of as Java Applets that run on servers instead of in web browsers.[1] These kinds of servlets are the Java counterpart to non-Java dynamic Web content technologies such as PHP and ASP.NET.
A Servlet is a Java-based server-side web technology. Technically speaking, a Servlet is a Java class in Java EE that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. Servlets could in principle communicate over any client-server protocol, but they are most often used with the HTTP protocol. Therefore, the word "Servlet" is often used in the meaning of "HTTP Servlet".[2] Thus, a software developer may use a servlet to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting.
To deploy and run a Servlet, a web container must be used. A web container (also known as a Servlet container) is essentially the component of a web server that interacts with the Servlets. The web container is responsible for managing the lifecycle of Servlets, mapping a URL to a particular Servlet and ensuring that the URL requester has the correct access rights. The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the web container and a servlet.[2] A Servlet is an object that receives a request and generates a response based on that request. The basic Servlet package defines Java objects to represent Servlet requests and responses, as well as objects to reflect the Servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the web server and a client. Servlets may be packaged in a WAR file as a web application. Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. While the direct usage of Servlets to generate HTML (as shown in the example below) has become rare, the higher level MVC web framework in Java EE (JSF) still explicitly uses the Servlet technology for the low level request/response handling via the FacesServlet. A somewhat older usage is to use Servlets in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view-controller pattern.
A Servlet is a Java-based server-side web technology. Technically speaking, a Servlet is a Java class in Java EE that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. Servlets could in principle communicate over any client-server protocol, but they are most often used with the HTTP protocol. Therefore, the word "Servlet" is often used in the meaning of "HTTP Servlet".[2] Thus, a software developer may use a servlet to add dynamic content to a web server using the Java platform. The generated content is commonly HTML, but may be other data such as XML. Servlets can maintain state in session variables across many server transactions by using HTTP cookies, or URL rewriting.
To deploy and run a Servlet, a web container must be used. A web container (also known as a Servlet container) is essentially the component of a web server that interacts with the Servlets. The web container is responsible for managing the lifecycle of Servlets, mapping a URL to a particular Servlet and ensuring that the URL requester has the correct access rights. The Servlet API, contained in the Java package hierarchy javax.servlet, defines the expected interactions of the web container and a servlet.[2] A Servlet is an object that receives a request and generates a response based on that request. The basic Servlet package defines Java objects to represent Servlet requests and responses, as well as objects to reflect the Servlet's configuration parameters and execution environment. The package javax.servlet.http defines HTTP-specific subclasses of the generic servlet elements, including session management objects that track multiple requests and responses between the web server and a client. Servlets may be packaged in a WAR file as a web application. Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs embed Java code in HTML. While the direct usage of Servlets to generate HTML (as shown in the example below) has become rare, the higher level MVC web framework in Java EE (JSF) still explicitly uses the Servlet technology for the low level request/response handling via the FacesServlet. A somewhat older usage is to use Servlets in conjunction with JSPs in a pattern called "Model 2", which is a flavor of the model-view-controller pattern.
History
The complete Servlet specification was created by Sun Microsystems, with version 1.0 finalized in June 1997. Starting with version 2.3, the Servlet specification was developed under the Java Community Process. JSR 53 defined both the Servlet 2.3 and JavaServer Page 1.2 specifications. JSR 154 specifies the Servlet 2.4 and 2.5 specifications. As of March 26, 2010, the current version of the Servlet specification is 3.0.
In his blog on java.net, Sun veteran and GlassFish lead Jim Driscoll details the history of Servlet technology. James Gosling first thought of Servlets in the early days of Java, but the concept did not become a product until Sun shipped the Java Web Server[clarify] product. This was before what is now the Java Platform, Enterprise Edition was made into a specification.
Servlet API history Servlet API version Released Platform Important Changes Servlet 3.0 December 2009 JavaEE 6, JavaSE 6 Pluggability, Ease of development, Async Servlet, Security, File Uploading Servlet 2.5 September 2005 JavaEE 5, JavaSE 5 Requires JavaSE 5, supports annotation Servlet 2.4 November 2003 J2EE 1.4, J2SE 1.3 web.xml uses XML Schema Servlet 2.3 August 2001 J2EE 1.3, J2SE 1.2 Addition of Filter
Servlet 2.2 August 1999 J2EE 1.2, J2SE 1.2 Becomes part of J2EE, introduced independent web applications in .war files Servlet 2.1 November 1998 Unspecified First official specification, added RequestDispatcher
,ServletContext
Servlet 2.0 JDK 1.1 Part of Java Servlet Development Kit 2.0 Servlet 1.0 June 1997
Usage
Servlets are most often used to :
- process or store data that was submitted from an HTML form
- provide dynamic content such as the results of a database query
- manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer.
Life cycle of a Servlet
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
The service () method is called by the container and service method invokes doGe, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.
After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:

- The servlet is initialized by calling the init () method.
- The servlet calls service() method to process a client's request.
- The servlet is terminated by calling the destroy() method.
- Finally, servlet is garbage collected by the garbage collector of the JVM.
The init() method :
The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition looks like this:
public void init() throws ServletException { // Initialization code... } |
The service() method :
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ } |
The doGet() and doPost() are most frequently used methods with in each service request. Here are the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code } |
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code } |
The destroy() method :
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this:
public void destroy() { // Finalization code... } |
Architecture Digram:
The following figure depicts a typical servlet life-cycle scenario.- First the HTTP requests coming to the server are delegated to the servlet container.
- The servlet container loads the servlet before invoking the service() method.
- Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the service() method of a single instance of the servlet.

Creating and Initializing a Servlet
Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.
Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows:
If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There could be various entries in this table already available, but never mind.
You are almost done, now let us start tomcat server using <Tomcat-installation-directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address box. If everything goes fine, you would get following result:

Sample Code for Hello World:
Following is the sample source code structure of a servlet example to write Hello World:// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } } |
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH.Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows:
$ javac HelloWorld.java |
This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable.
If everything goes fine, above compilation would produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.
Servlet Deployment:
By default, a servlet application is located at the path <Tomcat-installation-directory>/webapps/ROOT and the class file would reside in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class.
For now, let us copy HelloWorld.class into <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> |
You are almost done, now let us start tomcat server using <Tomcat-installation-directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address box. If everything goes fine, you would get following result:

-
Servlet - Client Request
When a browser requests for a web page, it sends lot of information to the web server which can not be read directly because this information travel as a part of header of HTTP request. You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you would use very frequently in web programming:
Header Description Accept This header specifies the MIME types that the browser or other clients can handle. Values of image/png or image/jpeg are the two most common possibilities. Accept-Charset This header specifies the character sets the browser can use to display the information. For example ISO-8859-1. Accept-Encoding This header specifies the types of encodings that the browser knows how to handle. Values of gzip or compress are the two most common possibilities. Accept-Language This header specifies the client's preferred languages in case the servlet can produce results in more than one language. For example en, en-us, ru, etc. Authorization This header is used by clients to identify themselves when accessing password-protected Web pages. Connection This header indicates whether the client can handle persistent HTTP connections. Persistent connections permit the client or other browser to retrieve multiple files with a single request. A value of Keep-Alive means that persistent connections should be used Content-Length This header is applicable only to POST requests and gives the size of the POST data in bytes. Cookie This header returns cookies to servers that previously sent them to the browser. Host This header specifies the host and port as given in the original URL. If-Modified-Since This header indicates that the client wants the page only if it has been changed after the specified date. The server sends a code, 304 which means Not Modified header if no newer result is available. If-Unmodified-Since This header is the reverse of If-Modified-Since; it specifies that the operation should succeed only if the document is older than the specified date. Referer This header indicates the URL of the referring Web page. For example, if you are at Web page 1 and click on a link to Web page 2, the URL of Web page 1 is included in the Referer header when the browser requests Web page 2. User-Agent This header identifies the browser or other client making the request and can be used to return different content to different types of browsers. Methods to read HTTP Header:
There are following methods which can be used to read HTTP header in your servlet program. These method are available with HttpServletRequest object.
S.N. Method & Description 1 Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this request.2 Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes available to this request.3 Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains.4 Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request.5 HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.6 HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.7 Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header8 Object getAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.9 ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream.10 String getAuthType()
Returns the name of the authentication scheme used to protect the servlet, for example, "BASIC" or "SSL," or null if the JSP was not protected11 String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.12 String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.13 String getContextPath()
Returns the portion of the request URI that indicates the context of the request.14 String getHeader(String name)
Returns the value of the specified request header as a String.15 String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.16 String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.17 String getPathInfo()
Returns any extra path information associated with the URL the client sent when it made this request.18 String getProtocol()
Returns the name and version of the protocol the request.19 String getQueryString()
Returns the query string that is contained in the request URL after the path.20 String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.21 String getRemoteHost()
Returns the fully qualified name of the client that sent the request.22 String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.23 String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query string in the first line of the HTTP request.24 String getRequestedSessionId()
Returns the session ID specified by the client.25 String getServletPath()
Returns the part of this request's URL that calls the JSP.26 String[] getParameterValues(String name)
Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.27 boolean isSecure()
Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.28 int getContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known.29 int getIntHeader(String name)
Returns the value of the specified request header as an int.30 int getServerPort()
Returns the port number on which this request was received.HTTP Header Request Example:
Following is the example which uses getHeaderNames() method of HttpServletRequest to read the HTTP header infromation. This method returns an Enumeration that contains the header information associated with the current HTTP request.
Once we have an Enumeration, we can loop down the Enumeration in the standard manner, using hasMoreElements() method to determine when to stop and using nextElement() method to get each parameter name.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class DisplayHeader extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "HTTP Header Request Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<table width=\"100%\" border=\"1\" align=\"center\">\n" + "<tr bgcolor=\"#949494\">\n" + "<th>Header Name</th><th>Header Value(s)</th>\n"+ "</tr>\n"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String paramName = (String)headerNames.nextElement(); out.print("<tr><td>" + paramName + "</td>\n"); String paramValue = request.getHeader(paramName); out.println("<td> " + paramValue + "</td></tr>\n"); } out.println("</table>\n</body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
HTTP Header Request Example
Header Name Header Value(s) accept */* accept-language en-us user-agent Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; InfoPath.2; MS-RTC LM 8) accept-encoding gzip, deflate host localhost:8080 connection Keep-Alive cache-control no-cache
-
Servlet - Server Response
As discussed in previous chapter, when a Web server responds to a HTTP request to the browser, the response typically consists of a status line, some response headers, a blank line, and the document. A typical response looks like this:
HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html>
Following is a summary of the most useful HTTP 1.1 response headers which go back to the browser from web server side and you would use them very frequently in web programming:
Header Description Allow This header specifies the request methods (GET, POST, etc.) that the server supports. Cache-Control This header specifies the circumstances in which the response document can safely be cached. It can have values public, private or no-cache etc. Public means document is cacheable, Private means document is for a single user and can only be stored in private (nonshared) caches and no-cache means document should never be cached. Connection This header instructs the browser whether to use persistent in HTTP connections or not. A value of close instructs the browser not to use persistent HTTP connections and keep-alive means using persistent connections. Content-Disposition This header lets you request that the browser ask the user to save the response to disk in a file of the given name. Content-Encoding This header specifies the way in which the page was encoded during transmission. Content-Language This header signifies the language in which the document is written. For example en, en-us, ru, etc. Content-Length This header indicates the number of bytes in the response. This information is needed only if the browser is using a persistent (keep-alive) HTTP connection. Content-Type This header gives the MIME (Multipurpose Internet Mail Extension) type of the response document. Expires This header specifies the time at which the content should be considered out-of-date and thus no longer be cached. Last-Modified This header indicates when the document was last changed. The client can then cache the document and supply a date by an If-Modified-Since request header in later requests. Location This header should be included with all responses that have a status code in the 300s. This notifies the browser of the document address. The browser automatically reconnects to this location and retrieves the new document. Refresh This header specifies how soon the browser should ask for an updated page. You can specify time in number of seconds after which a page would be refreshed. Retry-After This header can be used in conjunction with a 503 (Service Unavailable) response to tell the client how soon it can repeat its request. Set-Cookie This header specifies a cookie associated with the page. Methods to Set HTTP Response Header:
There are following methods which can be used to set HTTP response header in your servlet program. These method are available with HttpServletResponse object.
S.N. Method & Description 1 String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is not needed, returns the URL unchanged.2 String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged.3 boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been set.4 boolean isCommitted()
Returns a boolean indicating if the response has been committed.5 void addCookie(Cookie cookie)
Adds the specified cookie to the response.6 void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.7 void addHeader(String name, String value)
Adds a response header with the given name and value.8 void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.9 void flushBuffer()
Forces any content in the buffer to be written to the client.10 void reset()
Clears any data that exists in the buffer as well as the status code and headers.11 void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.12 void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the buffer.13 void sendError(int sc, String msg)
Sends an error response to the client using the specified status.14 void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location URL.15 void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.16 void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent to the client, for example, to UTF-8.17 void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.18 void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not been committed yet.19 void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.20 void setHeader(String name, String value)
Sets a response header with the given name and value.21 void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.22 void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.23 void setStatus(int sc)
Sets the status code for this response.HTTP Header Response Example:
You already have seen setContentType() method working in previous examples and following example would also use same method, additionally we would use setIntHeader() method to set Refresh header.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class Refresh extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Set response content type response.setContentType("text/html"); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriter out = response.getWriter(); String title = "Auto Refresh Header Setting"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p>Current Time is: " + CT + "</p>\n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Auto Refresh Header Setting
Current Time is: 9:44:50 PM -
Servlets - Cookies Handling
Cookies are text files stored on the client computer and they are kept for various information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
- Server script sends a set of cookies to the browser. For example name, age, or identification number etc.
- Browser stores this information on local machine for future use.
- When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
The Anatomy of a Cookie:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet that sets a cookie might send headers that look something like this:
HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT; path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this:
GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz
Servlet Cookies Methods:
Following is the list of useful methods which you can use while manipulating cookies in servlet.
S.N. Method & Description 1 public void setDomain(String pattern)
This method sets the domain to which cookie applies, for example tutorialspoint.com.2 public String getDomain()
This method gets the domain to which cookie applies, for example tutorialspoint.com.3 public void setMaxAge(int expiry)
This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.4 public int getMaxAge()
This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.5 public String getName()
This method returns the name of the cookie. The name cannot be changed after creation.6 public void setValue(String newValue)
This method sets the value associated with the cookie.7 public String getValue()
This method gets the value associated with the cookie.8 public void setPath(String uri)
This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories.9 public String getPath()
This method gets the path to which this cookie applies.10 public void setSecure(boolean flag)
This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.11 public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.12 public String getComment()
This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.Setting Cookies with Servlet:
Setting cookies with servlet involves three steps:
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
[ ] ( ) = , " / ? @ : ;
cookie.setMaxAge(60*60*24);
response.addCookie(cookie);
Example:
Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Setting Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>: " + request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " + request.getParameter("last_name") + "\n" + "</ul>\n" + "</body></html>"); } }
<html> <body> <form action="HelloForm" method="GET"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html>
Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.
Next section would explain you how you would access these cookies back in your web application.
Reading Cookies with Servlet:
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.
Example:
Let us read cookies which we have set in previous example:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class ReadCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } }
Found Cookies Name and Value
Name : first_name, Value: John
Name : last_name, Value: PlayerDelete Cookies with Servlet:
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:
- Read an already exsiting cookie and store it in Cookie object.
- Set cookie age as zero using setMaxAge() method to delete an existing cookie.
- Add this cookie back into response header.
Example:
Following example would delete and existing cookie named "first_name" and when you would run ReadCookies servlet next time it would return null value for first_name.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class DeleteCookies extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Delete Cookies Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" ); if( cookies != null ){ out.println("<h2> Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie : " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } out.println("</body>"); out.println("</html>"); } }
Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player
Found Cookies Name and Value
Name : last_name, Value: Player
-
Finalizing a Servlet
Finalizing a Servlet
When a servlet container determines that a servlet should be removed from service (for example, when a container wants to reclaim memory resources, or when it is being shut down), it calls thedestroy
method of theServlet
interface. In this method, you release any resources the servlet is using and save any persistent state. The followingdestroy
method releases the database object created in theinit
method described in Initializing a Servlet:public void destroy() { bookDB = null; }
All of a servlet'sservice
methods should be complete when a servlet is removed. The server tries to ensure this completion by calling thedestroy
method only after all service requests have returned or after a server-specific grace period, whichever comes first. -
Servlet- Page redirection
Page redirection is generally used when a document moves to a new location and we need to send the client to this new location or may be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is using method sendRedirect() of response object. Following is the signature of this method:
public void HttpServletResponse.sendRedirect(String location) throws IOException
.... String site = "http://www.newpage.com" ; response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); ....
Example:
This example shows how a servlet performs page redirection to an another location:
import java.io.*; import java.sql.Date; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class PageRedirect extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // New location to be redirected String site = new String("http://www.photofuntoos.com"); response.setStatus(response.SC_MOVED_TEMPORARILY); response.setHeader("Location", site); } }
.... <servlet> <servlet-name>PageRedirect</servlet-name> <servlet-class>PageRedirect</servlet-class> </servlet> <servlet-mapping> <servlet-name>PageRedirect</servlet-name> <url-pattern>/PageRedirect</url-pattern> </servlet-mapping> ....
-
Other resources
Click here to download java platforms
Click Here to download java development toolkit
Click Here to download java runtime envirnoment
0 comments: