Unit 4
Unit 4
Unit 4
Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a requests 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
• The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. 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 −
// 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 −
• The service () method is called by the container and service method invokes doGet,
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.
• 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.
// Servlet code }
• A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
// Servlet code
• 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 −
// Finalization code...
Architecture Diagram
• 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.
Advantages of Servlets
A servlet can be imagined to be as an applet running on the server side. Some of the other
server side technologies available are Common Gateway Interface (CGI), server side
JavaScript and Active Server Pages (ASP). Advantages of servlets over these server side
technologies are as follows:
Persistent: Servlets remain in memory until explicitly destroyed. This helps in serving
several incoming requests. Servlets establishes connection only once with the database
and can handle several requests on the same database. This reduces the time and
resources required to establish connection again and again with the same database.
Whereas, CGI programs are removed from the memory once the request is processed and
each time a new process is initiated whenever new request arrives.
Portable: Since servlets are written in Java, they are portable. That is, servlets are
compatible with almost all operating systems. The programs written on one operating
system can be executed on other operating system.
Server-independent: Servlets are compatible with any web server available today. Most
of the software vendors today support servlets within their web server products. On the
other hand, some of the server side technologies like server side JavaSricpt and ASP can
run on only selected web servers. The CGI is compatible with the web server that has
features to supports it.
Protocol-independent: Servlets can be created to support any of the protocols like FTP
commands, Telnet sessions, NNTP newsgroups, etc. It also provides extended support for
the functionality of HTTP protocol.
Extensible: Servlets being written in Java, can be extended and polymorphed into the
objects that suits the user requirement.
Secure: Since servlets are server side programs and can be invoked by web server only,
they inherit all the security measures taken by the web server. They are also safe from
the problems related to memory management as Java does not support the concept of
pointers and perform garbage collection automatically.
Fast: Since servlets are compiled into bytecodes, they can execute more quickly as
compared to other scripting languages. The bytecode compilation feature helps servlets
to give much better performance. In addition, it also provides advantage of strong error
and type checking.
Cookies
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.
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 sign-out.
Advantage of Cookies:
Disadvantage of Cookies:
Cookie class:
Constructor Description
Cookie() Constructs a cookie.
Cookie(String name, String Constructs a cookie with a specified name and
value) value.
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be changed
after creation.
public String getValue() Returns the value of the cookie.
public void setName(String Changes the name of the cookie.
name)
public void setValue(String Changes the value of the cookie.
value)
Other methods required for using Cookies:
For adding cookie or getting the value from the cookie, we need some methods provided by
other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used
to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.
Create Cookie:
Delete Cookie:
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
Get Cookies:
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
}
Example of Servlet Cookies:
In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.
index.html
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.print("<form action='servlet2'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
try{
response.setContentType("text/html");
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Output
Session
HttpSession Interface 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.
Web container creates a session id for each user. The container uses this id to identify the
particular 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.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. publicHttpSessiongetSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.
2. publicHttpSessiongetSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns
a new session.
Destroy Session
session.invalidate();
Methods
public String getId():Returns a string containing the unique identifier value.
public long getCreationTime():Returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970 GMT.
public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1, 1970
GMT.
public void invalidate():Invalidates this session then unbinds any objects bound to it.
Steps
On client's first request, the Web Container generates a unique session ID and gives it back
to the client with response. This is a temporary session created by web container.
The client sends back the session ID with each request. Making it easier for the web container
to identify where the request is coming from.
The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.
Ex: SessionTrack.java
<web-app>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<url-pattern>/SessionTrack</url-pattern>
</servlet- mapping>
</web-app
Output
JSP (Java Server Pages)
JSP Stands for "Java Server Pages". Using "JSP" we can use both, static HTML with
dynamically-generated HTML. Web pages created using CGI programs are mostly static,
dynamic part is limited to a few small locations. But using CGI and servlet, you can generate
entire page through one program. Using JSP, you can built two parts separately.
JSP is the product of Sun Microsystems Inc. JSP has more advance features than Servlet. JSP
separates the presentation logic from the business logic, provide facility to developers to
work separately without any trouble. JSP have the properties of Cold fusion and ASP and
hence provide the flexibility to embed the business logic efficiently within the HTML content
(presentation logic).
Advantages of JSP:-
JSP is useful for server side programming
JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.
JSP uses simplified scripting language based syntax for embedding HTML into JSP.
JSP containers provide easy way for accessing standard objects and actions.
JSP reaps all the benefits provided by JAVA servlets and web container environment, but
they have an added advantage of being simpler and more natural program for web
enabling enterprise developer
JSP use HTTP as default request /response communication paradigm and thus make JSP
ideal as Web Enabling Technology
OBJECT CLASS
Out JSP writer
Request HttpServletRequest
Response HttpServletRespose
Session HttpSession
Application ServletContext
In servlets both the presentation and business logic are place it together where as in jsp both
are separated by defining by java beans.
Servlet is a java code where HTML code can be embedded whereas in jsp, it is a kind of HTML
where java code can be embedded by using special tags.
JSP allows creating and using custom tag libraries.
For example
</body> </html>
In this code, jsp elements that use java code are merged with HTML code.
Scoped Variables
Four different types of variable scopes within the JSP page can be used:
Page Scope: Objects stored in page scope can only be retrieved during the processing of
that page for a specific request.
Request Scope: Objects stored in request scope can be retrieved during the processing
of all pages taking part in the processing of a request
Session Scope: Object stored in session scope can be retrieved by any pages accessed by
a user during a single interactive session with the Web application
Application Scope: Object stored in application scope is accessible from all pages and
for all users, until the Web application itself is unloaded
Applications
A web application is a collection of resources that are used together to implement some web-
based functionality
To develop a web applications the following resources are needed:
Server side Programming
Servlets /JSP,
Client side programming: HTML documents, style sheets, XML , images, non-servlet java
classes etc,
Web form validation: JavaScript, non-servlet Java classes, etc.
Other resources:
Databases: MS-Access, MySQL/SQL
Web server: Appache Tiomcat/ Java Web server/ Glass fish,
Browser: IE/Netscape/Chrome/FireFox
Basic JSP
The directives are used to specify the attributes of the JSP page. Also it can be used to import
java packages in to the jsp page.
For example,
Where language=”java” tells tha the page is contains java code, the code
contentType=”text/html” specifies the MIME type, the code import =”java.util.*” used to
import all the classes of java’s utility package into this page.
Declarations
Provide a mechanism to define variables and methods. Declarative statements are placed
within <%! and %> symbols and always end with a semicolon.
Syntax: <%! Declare all the variables here %> For example, <% int a, b %>
Scriplets:
Consists of valid Java code snippets that are enclosed within <% and %> symbols. The syntax
to declare JSP scriptlets to include valid Java code is:
Scriplets can't generate HTML itself. Using "out" variable, it can generate HTML. This variable
does not need to be declared. It is already predefined for Scriplets, along with some other
variables. The "out" variable is of type "javax.servlet.jsp.JspWriter".
For example,
<HTML>
<BODY>
<%
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>
Insert values directly into the output. The syntax to include a JSP expression in the JSP file is:
Actions:
The elements which are used to access the java bean in a jsp page is called jsp action
elements.
JSP defines the following action elements:
1. Standard action and Custom action
2. JSTL
The JSTL tags can be classified, according to their functions, into the following JSTL tag
library groups that can be used when creating a JSP page −
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
Core Tags:
The core group of tags are the most commonly used JSTL tags. Following is the syntax to
include the JSTL Core library in your JSP −
Formatting tags:
The JSTL formatting tags are used to format and display text, the date, the time, and numbers
for internationalized Websites. Following is the syntax to include formatting library in your
JSP −
SQL Tags:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP −
XML tags:
The JSTL XML tags provide a JSP-centric way of creating and manipulating the XML
documents. Following is the syntax to include the JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with the XML data. This includes
parsing the XML, transforming the XML data, and the flow control based on the XPath
expressions.
JSTL Functions:
JSTL includes a number of standard functions, most of which are common string
manipulation functions. Following is the syntax to include JSTL Functions library in your
JSP −
<%@ taglib prefix = "fn" uri = "http://java.sun.com/jsp/jstl/functions" %>
Following table lists out the various JSTL Functions –
S.No. Function & Description
fn:contains()
1
Tests if an input string contains the specified substring.
fn:containsIgnoreCase()
2
Tests if an input string contains the specified substring in a case insensitive way.
fn:endsWith()
3
Tests if an input string ends with the specified suffix.
fn:escapeXml()
4
Escapes characters that can be interpreted as XML markup.
fn:indexOf()
5
Returns the index withing a string of the first occurrence of a specified substring.
fn:join()
6
Joins all elements of an array into a string.
fn:length()
7
Returns the number of items in a collection, or the number of characters in a string.
fn:replace()
8 Returns a string resulting from replacing in an input string all occurrences with a
given string.
fn:split()
9
Splits a string into an array of substrings.
fn:startsWith()
10
Tests if an input string starts with the specified prefix.
fn:substring()
11
Returns a subset of a string.
fn:substringAfter()
12
Returns a subset of a string following a specific substring.
fn:substringBefore()
13
Returns a subset of a string before a specific substring.
fn:toLowerCase()
14
Converts all of the characters of a string to lower case.
fn:toUpperCase()
15
Converts all of the characters of a string to upper case.
fn:trim()
16
Removes white spaces from both ends of a string.