What are Servlets?
Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server.Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
- Performance is significantly better.
- Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request.
- Servlets are platform-independent because they are written in Java.
- Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted.
- The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
Servlets Tasks:
Servlets perform the following major tasks:- Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program.
- Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth.
- Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly.
- Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
- Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.
Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification.Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.
Setting up Web Server: Tomcat
A number of Web Servers that support servlets are available in the market. Some web servers are freely downloadable and Tomcat is one of them.Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine:
- Download latest version of Tomcat from http://tomcat.apache.org/.
- Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.
%CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.batTomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.shAfter startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result:
Tomcat can be stopped by executing the following commands on windows machine:
C:\apache-tomcat-5.5.29\bin\shutdownTomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine:
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler.If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
set CATALINA=C:\apache-tomcat-5.5.29 set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press the OK button.
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file.
setenv CATALINA=/usr/local/apache-tomcat-5.5.29 setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATHNOTE: Assuming that your development directory is C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH in similar way as you have
Servlets-Life Cycle:
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 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 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 is 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.
Servlets-Example:
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.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(""
+ message + "
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.javaIf 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.
Servlet Deployment:
By default, a servlet application is located at the pathIf 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
HelloWorld
You are almost done, now let us start tomcat server using

Servlets Form Data:
You must have come across many situations when you need to pass some information from your browser to web server and ultimately to your backend program. The browser uses two methods to pass this information to web server. These methods are GET Method and POST Method.GET method:
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as follows:http://www.test.com/hello?key1=value1&key2=value2The GET method is the defualt method to pass information from browser to web server and it produces a long string that appears in your browser's Location:box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet() method.
POST method:
A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method.Reading Form Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending on the situation:- getParameter(): You call request.getParameter() method to get the value of a form parameter.
- getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
- getParameterNames(): Call this method if you want a complete list of all parameters in the current request.
GET Method Example Using URL:
Here is a simple URL which will pass two values to HelloForm program using GET method.http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI Below is HelloForm.java servlet program to handle input given by web browser. We are going to use getParameter() method which makes it very easy to access passed information:
// 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 { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Using GET Method to Read Form Data"; String docType = " + "transitional//en\">\n"; out.println(docType + "\n" + "\n" + "" + title + "\n" + "\n" + ""
+ title + "
- \n"
$ javac HelloForm.javaIf everything goes fine, above compilation would produce HelloForm.class file. Next you would have to copy this class file in
HelloForm
Using GET Method to Read Form Data
|
GET Method Example Using Form:
Here is a simple example which passes two values using HTML FORM and
submit button. We are going to use same Servlet HelloForm to handle this
imput.Keep this HTML in a file Hello.htm and put it in
Try to enter First Name and Last Name and then click submit button to see the result on your local machine where tomcat is running. Based on the input provided, it will generate similar result as mentioned in the above example.
POST Method Example Using Form:
Let us do little modification in the above servlet, so that it can handle GET as well as POST methods. Below is HelloForm.java servlet program to handle input given by web browser using GET or POST methods.// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm 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 = "Using GET Method to Read Form Data"; String docType = " + "transitional//en\">\n"; out.println(docType + "\n" + "\n" + "" + title + "\n" + "\n" + ""
+ title + "
- \n"
Here is the actual output of the above form, Try to enter First and Last Name and then click submit button to see the result on your local machine where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above examples.
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option is required to be selected.Here is example HTML code, CheckBox.htm, for a form with two checkboxes
The result of this code is the following form
Below is CheckBox.java servlet program to handle input given by web browser for checkbox button.
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class CheckBox 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 = "Reading Checkbox Data"; String docType = " + "transitional//en\">\n"; out.println(docType + "\n" + "\n" + "" + title + "\n" + "\n" + ""
+ title + "
- \n"
Reading All Form Parameters:
Following is the generic example which uses getParameterNames() method of HttpServletRequest to read all the available form parameters. This method returns an Enumeration that contains the parameter names in an unspecified order.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 ReadParams 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 = "Reading All Form Parameters"; String docType = " + "transitional//en\">\n"; out.println(docType + "\n" + "\n" + "\n"" + title + "\n" + "\n" + ""
+ title + "
Param Name
Param Value(s)
\n"+ "\n"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print(" "
+ paramName + "\n"
); String[] paramValues = request.getParameterValues(paramName); // Read single valued data if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println("No Value"); else out.println(paramValue); } else { // Read multiple valued data out.println("
- "
Now calling servlet using above form would generate following result:
Reading All Form Parameters
Param Name | Param Value(s) |
---|---|
maths | on |
chemistry | on |
Servlets 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 methods 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 header |
8 | 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 protected |
11 | 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 = " + "transitional//en\">\n"; out.println(docType + "\n" + "\n" + "\n"" + title + "\n"+ "\n" + ""
+ title + "
Header Name
Header Value(s)
\n"+ "\n"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String paramName = (String)headerNames.nextElement(); out.print(" "
+ paramName + "\n"); String paramValue = request.getHeader(paramName); out.println("" + paramValue + "\n"); } out.println("\n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Now calling the above servlet would generate following result:
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 |
Servlets 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 ...> ...</head> ... </body> </html>The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example).
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 methods 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. |
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 = " + "transitional//en\">\n"; out.println(docType + "\n" + "\n" + "Current Time is: " + CT + "\n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } Now calling the above servlet would display current system time after every 5 seconds as follows. Just run the servlet and wait to see the result:" + title + "\n"+ "\n" + ""
+ title + "
Auto Refresh Header Setting
Current Time is: 9:44:50 PMServlets Session Handeling:
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.Still there are following three ways to maintain session between web client and web server:
Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the recieved cookie.This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.
Hidden Form Fields:
A web server can send a hidden HTML form field along with a unique session ID as follows: type="hidden" name="sessionid" value="12345">
This entry means that, when the form is submitted, the specified name
and value are automatically included in the GET or POST data. Each time
when web browser sends request back, then session_id value can be used
to keep the track of different web browsers.This could be an effective way of keeping track of the session but clicking on a regular () hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.
URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.
The HttpSession Object:
Apart from the above mentioned three ways, servlet provides HttpSession Interface which 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.The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below:
HttpSession session = request.getSession();You need to call request.getSession() before you send any document content to the client. Here is a summary of the important methods available through HttpSession object:
S.N. | Method & Description |
---|---|
1 | public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name. |
2 | public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session. |
3 | public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
4 | public String getId() This method returns a string containing the unique identifier assigned to this session. |
5 | public long getLastAccessedTime() This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. |
6 | public int getMaxInactiveInterval() This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. |
7 | public void invalidate() This method invalidates this session and unbinds any objects bound to it. |
8 | public boolean isNew( This method returns true if the client does not yet know about the session or if the client chooses not to join the session. |
9 | public void removeAttribute(String name) This method removes the object bound with the specified name from this session. |
10 | public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified. |
11 | public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session. |
Session Tracking Example:
This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create a session object if it is already not created. HttpSession session = request.getSession(true); // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check if this is new comer on your web page. if (session.isNew()){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); } else { visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); } session.setAttribute(visitCountKey, visitCount); // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = " + "transitional//en\">\n"; out.println(docType + "\n" + "\n" + "" + title + "\n" + "\n" + ""
+ title + "
Session Infomation
\n" + "\n"value\n" + " \n" + " id
\n" + " " + session.getId() + "\n" + " \n" + " Creation Time
\n" + " " + createTime + " \n" + " \n" + " Time of Last Access
\n" + " " + lastAccessTime + " \n" + " \n" + " User ID
\n" + " " + userID + " \n" + " \n" + " Number of visits
\n" + " " + visitCount + "\n" + "\n" + ""); } } Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now running http://localhost:8080/SessionTrack would display the following result when you would run for the first time:
Welcome to my website
Session Infomation
Session info | value |
---|---|
id | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
Time of Last Access | Tue Jun 08 17:26:40 GMT+04:00 2010 |
User ID | ABCD |
Number of visits | 0 |
Welcome Back to my website
Session Infomation
info type | value |
---|---|
id | 0AE3EC93FF44E3C525B4351B77ABB2D5 |
Creation Time | Tue Jun 08 17:26:40 GMT+04:00 2010 |
Time of Last Access | Tue Jun 08 17:26:40 GMT+04:00 2010 |
User ID | ABCD |
Number of visits | 1 |
Deleting Session Data:
When you are done with a user's session data, you have several options:- Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key.
- Delete the whole session: You can call public void invalidate() method to discard an entire session.
- Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.
- Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.
- web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.15
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.
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/htmlAs you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
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=xyzA servlet will then have access to the cookie through the request method request.getCookies() which returns an array of Cookie objects.
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");Keep in mind, neither the name nor the value should contain white space or any of the following characters:
[ ] ( ) = , " / ? @ : ;(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:
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 = "\n"; out.println(docType + "\n" + "" + title + " \n" + "\n" + "" + title + "
\n" + "
- \n" +
"
- First Name: " + request.getParameter("first_name") + "\n" + "
- Last Name: " + request.getParameter("last_name") + "\n" + "
Keep above HTML content in a file Hello.htm and put it in
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 = "\n"; out.println(docType + "\n" + "Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you would have set first_name cookie as "John" and last_name cookie as "Player" then running http://localhost:8080/ReadCookies would display the following result:" + title + " \n" + "\n" ); if( cookies != null ){ out.println("Found Cookies Name and Value
"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" "); } }else{ out.println( "No cookies founds
"); } out.println(""); out.println(""); } }
Found Cookies Name and ValueName : first_name, Value: JohnName : last_name, Value: Player |
Delete 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 = "\n"; out.println(docType + "\n" + "Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now running http://localhost:8080/DeleteCookies would display the following result:" + title + " \n" + "\n" ); if( cookies != null ){ out.println("Cookies Name and Value
"); 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( ) + " "); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" "); } }else{ out.println( "No cookies founds
"); } out.println(""); out.println(""); } }
Cookies Name and ValueDeleted cookie : first_nameName : first_name, Value: John Name : last_name, Value: Player |
Found Cookies Name and ValueName : last_name, Value: Player |
Servlets Filters:
Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:- To intercept requests from a client before they access a resource at back end.
- To manipulate responses from server before they are sent back to the client.
- Authentication Filters.
- Data compression Filters.
- Encryption Filters.
- Filters that trigger resource access events.
- Image Conversion Filters.
- Logging and Auditing Filters.
- MIME-TYPE Chain Filters.
- Tokenizing Filters .
- XSL/T Filters That Transform XML Content.
When the web container starts up your web application, it creates an instance of each filter that you have declared in the deployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.
Servlet Filter Methods:
A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface defines three methods:S.N. | Method & Description |
---|---|
1 | public void doFilter (ServletRequest, ServletResponse, FilterChain) This method is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. |
2 | public void init(FilterConfig filterConfig) This method is called by the web container to indicate to a filter that it is being placed into service. |
3 | public void destroy() This method is called by the web container to indicate to a filter that it is being taken out of service. |
Servlet Filter Example:
Following is the Servlet Filter Example that would print the clients IP address and current date time. This example would give you basic understanding of Servlet Filter, but you can write more sophisticated filter applications using the same concept:// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Implements Filter class public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException{ // Get init parameter String testParam = config.getInitParameter("test-param"); //Print the init parameter System.out.println("Test Param: " + testParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); // Log the IP address and current timestamp. System.out.println("IP "+ ipAddress + ", Time " + new Date().toString()); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy( ){ /* Called before the Filter instance is removed from service by the web container*/ } }Compile LogFilter.java in usual way and put your class file in
Servlet Filter Mapping in Web.xml:
Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is defined and then mapped to a URL pattern. Create the following entry for filter tag in the deployment descriptor file web.xmlLogFilter
Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4J logger to log above log in a separate file.
Using Multiple Filters:
Your web application may define several different filters with a specific purpose. Consider, you define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained above except you need to create a different mapping as mentioned below:LogFilter
Filters Application Order:
The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.For example, above example would apply LogFilter first and then it would apply AuthenFilter to any servlet but the following example would reverse the order:
AuthenFilter
Servlets Interview Questions:
Q: What is servlet?
A: A servlet is a Java programming language class that is used
to extend the capabilities of servers that host applications accessed
by means of a request- response programming model. Before the servlet,
CGI scripting language was used as server side programming language.
Q: What is the use of servlet?
A: Uses of servlet includes:
- Processing and storing data submitted by an HTML form.
- Providing dynamic content.
- A Servlet can handle multiple request concurrently and be used to develop high performance system
- Managing state information on top of the stateless HTTP.
Q: What is the life cycle of servlet?
A: Life cycle of Servlet:
- Servlet class loading
- Servlet instantiation
- Initialization (call the init method)
- Request handling (call the service method)
- Removal from service (call the destroy method)
Q: Why do we need constructor in servlet if we use the init ()?
A: Even though there is an init method in a servlet which gets
called to initialize it, a constructor is still required to instantiate
the servlet. Even though you as the developer would never need to
explicitly call the servlet's constructor, it is still being used by the
container.
Q: How servlet is loaded?
A: The servlet is loaded by:
- First request is made.
- Server starts up (auto-load).
- There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
- Administrator manually loads.
Q: When the servlet is unloaded?
A: Servlet gets unloaded when:
- Server shuts down.
- Administrator manually unloads.
Q: What is servlet interface?
A: The central abstraction in the Servlet API is the Servlet
interface. All servlets implement this interface, either directly or
more commonly by extending a class that implements it.
Q: What is the generic servlet class?
A: GenericServlet is an abstract class that implements the
Servlet interface and the ServletConfig interface. In addition to the
methods declared in these two interfaces, this class also provides
simple versions of the lifecycle methods init () and destroy (), and
implements the log method declared in the ServletContext interface.
Q: What is the difference between GenericServlet and HttpServlet?
A: The difference is:
- The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods. But HttpServlet extends the GenericServlet base class and provides a framework for handling the HTTP protocol.
- The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers. The HttpServlet subclass passes generic service method requests to the relevant doGet () or doPost () method.
- GenericServlet is not specific to any protocol. HttpServlet only supports HTTP and HTTPS protocol.
Q: Why HttpServlet class is declared abstract?
A: The HttpServlet class is declared abstract because the
default implementations of the main service methods do nothing and must
be overridden. This is a convenience implementation of the Servlet
interface, which means that developers do not need to implement all
service methods.
If your servlet is required to handle doGet () requests for example, there is no need to write a doPost () method too.
If your servlet is required to handle doGet () requests for example, there is no need to write a doPost () method too.
Q: Can servlet have a constructor?
A: Yes
Q: What are the type of protocols supported by the HttpServlet?
A: It extends the GenericServlet base class and provides a
framework for handling the HTTP protocol. So, HttpServlet only supports
HTTP and HTTPS protocol.
Q: What is the difference between the doGet () and doPost ()?
A: The difference is:
- In doGet() the parameters are appended to the URL and sent along with header information. In doPost (),send the information through a socket back to the webserver and it won't show up in the URL bar.
- The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. You can send much more information to the server by using post and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
- DoGet() is a request for information.It does not change anything on the server. (doGet () should be idempotent). doPost () provides information (such as placing an order for merchandise) that the server is expected to remember.
Q: When to use doGet() and when doPost()?
A:Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:
- If data is sensitive.
- Data is greater than 1024 characters.
- If your application don't need bookmarks.
Q: How do I support both doGet () and doPost () from same servlet?
A:The easy way is, just support POST, then have your doGet method call your doPost method.
Q: Should I override the service () method?
A: We never override the service method, since the HTTP
Servlets have already taken care of it. The default service function
invokes the doXXX() method corresponding to the method of the HTTP
request. For example, if the HTTP request method is GET, doGet () method
is called by default.
A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.
A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.
Q: What is the ServletContext?
A: A servlet context object contains the information about the
Web application of which the servlet is a part. It also provides access
to the resources common to all the servlets in the application. Each
Web application in a container has a single servlet context associated
with it.
Q: What is the difference between the ServletConfig and ServletContext interface?
A: The ServletConfig interface is implemented by the servlet
container in order to pass configuration information to a servlet. The
server passes an object that implements the ServletConfig interface to
the servlet's init () method. A ServletContext defines a set of methods
that a servlet uses to communicate with its servlet container.
Q: What is the difference between forward () and sendRedirect ()?
A: The difference is:
- A forward is performed internally by the servlet. A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
- The browser is completely unaware that it has taken place, so its original URL remains intact. But in sendRedirect, the browser, in this case, is doing the work and knows that it's making a new request.
Q: What is the difference between forward() and include()?
A: The RequestDispatcher include() method inserts the contents
of the specified resource directly in the flow of the servlet response,
as if it were part of the calling servlet. The RequestDispatcher
forward() method is used to show a different resource in place of the
servlet that was originally called.
Q: What is the use of servlet wrapper classes?
A: The HttpServletRequestWrapper and
HttpServletResponseWrapper classes are designed to make it easy for
developers to create custom implementations of the servlet request and
response types.
The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.
The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.
Q: What is a deployment descriptor?
A: A deployment descriptor is an XML document with an .xml
extension. It defines a component's deployment settings. It declares
transaction attributes and security authorization for an enterprise
bean.
The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
Q: What is the preinitialization of servlet?
A: A container does not initialize the servlets as soon as it
starts up; it initializes a servlet when it receives a request for that
servlet first time. This is called lazy loading.
The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
Q: What is the element?
A: The element of a deployment
descriptor is used to load a servlet file when the server starts instead
of waiting for the first request. It is also used to specify the order
in which the files are to be loaded.
Q: What is session?
A: A session refers to all the requests that a single client
might make to a server in the course of viewing any pages associated
with a given application. Sessions are specific to both the individual
user and the application.
Q: What is the session tracking?
A: Session tracking is a mechanism that servlets use to
maintain state about a series of requests from the same user (requests
originating from the same browser) across some period of time.
Q: What is the need of session tracking in web application?
A: HTTP is a stateless protocol. Every request is treated as
new request. For web applications to be more realistic they have to
retain information across multiple requests. Such information which is
part of the application is referred as "state". To keep track of this
state we need session tracking.
Q: What are the different types of session tracking?
A: Different types are:
- URL rewriting
- Hidden Form Fields
- Cookies
- Secure Socket Layer (SSL) Sessions
Q: How do I use cookies to store session state on client?
A: In a servlet, the HttpServletResponse and
HttpServletRequest objects passed to method HttpServlet. Service () can
be used to create cookies on the client and use cookie information
transmitted during client requests. JSPs can also use cookies, in
scriptlet code or, preferably, from within custom tag code.
- To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
- To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest
Q: What are the advantages of storing session state in cookies?
A: Cookies are usually persistent, so for low-security sites,
user data that needs to be stored long-term (such as a user ID,
historical information, etc.) can be maintained easily with no server
interaction.
For small- and medium-sized session data, the entire session data
(instead of just the session ID) can be kept in the cookie.
Q: What is URL rewriting?
A: URL rewriting is a method of session tracking in which some
extra data is appended at the end of each URL. This extra data
identifies the session. The server can associate this session identifier
with the data it has stored about that session.
Q: How can destroyed session in servlet?
A: Using session.invalidate() method.
Q: What is servlet lazy loading?
A: A container does not initialize the servlets as soon as it
starts up; it initializes a servlet when it receives a request for that
servlet first time. This is called lazy loading.
Q: What is servlet chaining?
A: Servlet Chaining is a method where the output of one
servlet is piped into a second servlet. The output of the second servlet
could be piped into a third servlet, and so on. The last servlet in the
chain returns the output to the Web browser
Q: What is filter?
A: Filters are Java components that are used to intercept an
incoming request to a Web resource and a response sent back from the
resource. It is used to abstract any useful information contained in the
request or response.
No comments:
Post a Comment