Servlet and JSP
Servlet and JSP
What is a Servlet?
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
1. Consider a request for a static web page. A user enters a Uniform Resource Locator (URL)
into a browser.
2. The browser generates an HTTP request to the appropriate web server. The web server
maps this request to a specific file. That file is returned in an HTTP response to the browser.
3. The HTTP header in the response indicates the type of the content. The Multipurpose
Internet Mail Extensions (MIME) are used for this purpose. For example, ordinary ASCII
text has a MIME type of text/plain. The Hypertext Markup Language (HTML) source code of
a web page has a MIME type of text/html.
21
Consider dynamic content. Assume that an online store uses a database to store information
about its business. This would include items for sale, prices, availability, orders, and so forth.
It wishes to make this information accessible to customers via web pages. The contents of
those web pages must be dynamically generated to reflect the latest information in the
database.
In the early days of the Web, a server could dynamically construct a page by creating a
separate process to handle each client request. The process would open connections to one or
more databases in order to obtain the necessary information. It communicated with the web
server via an interface known as the Common Gateway Interface (CGI). CGI allowed the
separate process to read data from the HTTP request and write data to the HTTP response. A
variety of different languages were used to build CGI programs. These included C, C++, and
Perl .However, CGI 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. In addition,the
CGI programs were not platform-independent. Therefore, other techniques were introduced.
Among these are servlets. Servlets offer several advantages in comparison with CGI.
First, performance is significantly better. Servlets execute within the address space of a web
server. It is not necessary to createa separate process to handle each client request.
Second, servlets are platform-independent because they are written in Java.
Third, the Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine.
Finally, 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.
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
21
Static website
Static website is the basic type of website that is easy to create. You don't need the
knowledge of web programming and database design to create a static website. Its web pages
are coded in HTML. The codes are fixed for each page so the information contained in the
page does not change and it looks like a printed page.
Dynamic website
Dynamic website is a collection of dynamic web pages whose content changes dynamically.
It accesses content from a database or Content Management System (CMS). Therefore, when
you alter or update the content of the database, the content of the website is also altered or
updated.Dynamic website uses client-side scripting or server-side scripting, or both to
generate dynamic content.
Client side scripting generates content at the client computer on the basis of user input. The
web browser downloads the web page from the server and processes the code within the page
21
to render information to the user.In server side scripting, the software runs on the server and
processing is completed in the server then plain pages are sent to the user.
Two packages contain the classes and interfaces that are required to build servlets. These are
1. javax.servlet
2. javax.servlet.http
The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
21
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access
. information about their environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a client.
ServletOutputStream Provides an output stream for writing responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable
javax.servlet.http Package
The javax.servlet.http package contains a number of interfaces and classes that are commonly
used by servlet developers.
Interface Description
HttpServletRequest Enables servlets to read data from an HTTP request.
HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from
a session.
The following table summarizes the core classes that are provided in this package. The
most important of these is HttpServlet. Servlet developers typically extend this class in
order to process HTTP requests.
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
21
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a
Session value, or that a session attribute changed.
The servlet is invoked when a form on a web page is submitted. The example contains two
ColorGetServlet.java. It defines a form that contains a select element and a submit button.
<html>
<body>
<center>
examples/servlet/ColorGetServlet">
<B>Color:</B>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
21
The doGet( ) method is overridden to process any HTTP GET requests that are sent to this
servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection
that was made by the user.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
The servlet is invoked when a form on a web page is submitted. A web page is defined in
ColorPost.html, and a servlet is defined in the class ColorPostServlet.java. It is identical to
ColorGet.html except that the method parameter for the form tag explicitly specifies that the
POST method should be used, and the action parameter for the form tag specifies a
different servlet.
<html>
<body>
<center>
<form name="Form1"method="post"
action="http://localhost:8080/servletsexamples/servlet/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
21
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for ColorPostServlet.java is shown in the following listing. The doPost( )
method is overridden to process any HTTP POST requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the selection that was made
by the user. import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
21
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
21
Using Cookies
The servlet is invoked when a form on a web page is submitted. The example contains three
files as summarized here:
File Description
AddCookie.htm Allows a user to specify a value for the cookie named
MyCookie.
AddCookieServlet.java Processes the submission of AddCookie.htm.
GetCookiesServlet.java Displays cookie values.
The HTML source code for AddCookie.html is shown in the following listing. This 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.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
The source code for AddCookieServlet.java is shown in the following listing. It 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.
21
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException {
The source code for GetCookiesServlet.java is shown in the following listing. It 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. Observe that
the getName( ) and getValue( ) methods are called to obtain this information.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
21
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +"; value = " + value);
}
pw.close();
}
}
Session Tracking
1. Session Tracking
2. Session Tracking Techniques
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we need
to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:
21
Why use Session Tracking?
A Date object encapsulating the current date and time is then created.
The setAttribute( ) method is called to bind the name “date” to this object.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
21
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
21
JSP
JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.
There are many advantages of JSP over the Servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.
21
The Lifecycle of a JSP Page
JSP page is translated into Servlet by the help of JSP translator. The JSP translator is a part of
the web server which is responsible for translating the JSP page into Servlet. After that,
Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all
the processes that happen in Servlet are performed on JSP later like initialization, committing
response to the browser and destroy.
21
JSP Scriptlet tag (Scripting elements)
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are
the scripting elements first.
The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
In this example, we have created two files index.html and welcome.jsp. The index.html file
gets the username from the user and the welcome.jsp file prints the username with the
welcome message.
File: index.html
<html>
21
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data. It is mainly used to print the values of variable
or method.
Syntax :
<%= statement %>
21
2. Example of JSP expression tag that prints current time
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
In this example, we are printing the username using the expression tag. The index.html file
gets the username and sends the request to the welcome.jsp file, which displays the username.
File: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
The JSP declaration tag is used to declare fields and methods.The code written inside the
jsp declaration tag is placed outside the service() method of auto generated servlet.So it
doesn't get memory at each request.
21
Syntax:
<%! field or method declaration %>
The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variables as well as
methods. methods.
The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is placed outside the
_jspService() method. _jspService() method.
In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.
index.jsp
<html>
<body>
<%!
21
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
21