Servlets
Servlets
Servlets
Servlets:
Servlets are small programs that execute on the server side of a web connection
Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the
functionality of a web server.
Disadvantages of CGI:
It suffered serious performance problems.
It was expensive in terms of processor and memory resources to create a separate process for each client request.
It was also expensive to open and close database connections for each client request.
CGI programs were not platform-independent.
Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP
request.
You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for
the client. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients.
The service( ) method is called for each HTTP request.
Finally, the server may decide to unload the servlet from its memory.
The algorithms by which this determination is made are specific to each server.
The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for
the servlet.
Important data may be saved to a persistent store.
The memory allocated for the servlet and its objects can then be garbage collected.
web.xml:
For instance, assuming the first example, called HelloServlet, you will add the following lines in the section that defines the
servlets:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
Next, you will add the following lines to the section that defines the servlet mappings.
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
Sample Program:
1. Create and Compile the Servlet Source Code
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
Explanation:
- It imports the javax.servlet package. This package contains the classes and interfaces required to build servlets.
- Next, the program defines HelloServlet as a subclass of GenericServlet.
- The GenericServlet class provides functionality that simplifies the creation of a servlet. For example, it provides
versions of init( ) and destroy( ), which may be used as is. You need supply only the service( ) method.
- Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is overridden. This method
handles requests from a client.
- The first argument is a ServletRequest object. This enables the servlet to read data that is provided via the client
request.
- The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
- The call to setContentType( ) establishes the MIME type of the HTTP response.
- In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML
source code.
- The getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of
the HTTP response.
- Then println( ) is used to write some simple HTML source code as the HTTP response.
- Compile this source code and place the HelloServlet.class file in the proper Tomcat directory as described in the
previous section.
- Also, add HelloServlet to the web.xml file,
2. Start Tomcat
Start Tomcat as explained earlier. Tomcat must be running before you try to execute a servlet.
PostParametersServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
Servlet developers typically extend this class in order to process HTTP requests.
For example, SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND indicates that the
requested resource is not available.
10 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
HelloServlet.java
package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
11 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
Output:
12 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
<input type=submit>
</form>
</center>
</body>
</html>
HelloServletGet.java
package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServletGet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<h1> My First Servlet Program </h1>");
}
}
13 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
View:
Enter Number 1:
Enter Number 2:
Select Operations
Add
Subtract
Divide
Multiply
Calculate
Calculator.java
package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
14 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
//retriving & storing the values from the textboxes into the String Variables.
String n1 = request.getParameter("fnum");
int num1 = Integer.parseInt(n1); //Converting String into Integer Variable
String n2 = request.getParameter("snum");
int num2 = Integer.parseInt(n2); int ans=0;
//performing calculation according to the selection made from the Radio Buttons named "calc".
if(request.getParameter("calc").equals("Add"))
ans = num1+num2;
if(request.getParameter("calc").equals("Sub"))
ans = num1-num2;
if(request.getParameter("calc").equals("Div"))
ans = num1/num2;
if(request.getParameter("calc").equals("Multi"))
ans = num1*num2;
15 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse
interface.
The data for that cookie is then included in the header of the HTTP response that is sent to the browser.
The names and values of cookies are stored on the user’s machine.
Some of the information that is saved for each cookie includes the following:
The name of the cookie
The value of the cookie
The expiration date of the cookie
The domain and path of the cookie
The expiration date determines when this cookie is deleted from the user’s machine. If an expiration date is not
explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in
a file on the user’s machine.
The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user
enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it
is not.
16 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
17 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound:
HttpSession getSession( )
The getValue( ) method obtains the value of the attribute that is being bound or unbound.
Object getValue( )
Using Cookies
How to use cookies?
Example:
The servlet is invoked when a form on a web page is submitted
The HTML source code for AddCookie.html page contains a text field in which a value can be entered.
There is also a submit button on the page.
When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request.
AddCookie.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/WebApplicationServlets/AddCookieServlet" >
<B>Enter a value for MyCookie:</B>
<input type=text name="data" size=25 value=""/>
<input type=submit value="Submit"/>
</form>
</body>
</html>
The source code for AddCookieServlet.java gets the value of the parameter named “data”.
It then creates a Cookie object that has the name “MyCookie” and contains the value of the “data” parameter.
The cookie is then added to the header of the HTTP response via the addCookie( ) method.
A feedback message is then written to the browser.
AddCookieServlet.java
package basic;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
18 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
import javax.servlet.http.HttpServletResponse;
/**
* @author Bemesha
*/
public class AddCookieServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");
// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>AddCookieServlet</servlet-name>
<servlet-class>basic.AddCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddCookieServlet</servlet-name>
<url-pattern>/AddCookieServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Execution:
19 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
Output:
Run AddCookie.html
The HTML source code for AddCookie.html page contains a text field in which a value can be entered.
There is also a submit button on the page.
When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request.
AddCookie.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form name="Form1" method="get" action="http://localhost:8080/WebApplicationServlets/GetCookiesServlet">
<B>Enter a value for MyCookie:</B>
<input type=text name="data" size=25 value=""/>
<input type=submit value="Submit"/>
</form>
</body>
</html>
The source code for GetCookiesServlet.java invokes the getCookies( ) method to read any cookies that are included in the HTTP GET request.
The names and values of these cookies are then written to the HTTP response.
20 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
Observe that the getName( ) and getValue( ) methods are called to obtain this information.
In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAge( ) method of Cookie. Therefore, the cookie expires
when the browser session ends.
You can experiment by using setMaxAge( ) and observe that the cookie is then saved to the disk on the client machine.
GetCookiesServlet.java
package basic;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Bemesha
*/
public class GetCookiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>GetCookiesServlet</servlet-name>
<servlet-class>basic.GetCookiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetCookiesServlet</servlet-name>
21 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
<url-pattern>/GetCookiesServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Execution:
************************************************
22 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
Session Tracking
Session Tracking:
HTTP is a stateless protocol.
Each request is independent of the previous one.
However, in some applications, it is necessary to save state information so that information can be collected from
several interactions between a browser and a server. Sessions provide such a mechanism.
A session can be created via the getSession( ) method of HttpServletRequest.
An HttpSession object is returned. This object can store a set of bindings that associate names with objects.
The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage
these bindings.
It is important to note that session state is shared among all the servlets that are associated with a particular client.
Program:
package basic;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
23 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
Execution in Netbeans:
24 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets
***************************************************************
25 | P a g e H.Bemesha Smitha,AP/IT,
LICET