Unit 6 - Servlets and Java Server Pages (JSP)
Unit 6 - Servlets and Java Server Pages (JSP)
Unit 6 - Servlets and Java Server Pages (JSP)
Servlets
Servlet is one of the server-side programming language which runs on Java enabled server. It is
used to develop web-based applications. As it is built on Java platform, servlet is fully compatible
with Java classes and interfaces. Let’s see what are servlets, Java servlets architecture and
advantages of servlets in detail.
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was common as a server-side programming language.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
Servlet can be described in many ways, depending on the context.
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes including documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic web page.
Step 1 : Client i.e. web browser sends the request to the web server.
Step 2 : Web server receives the request and sends it to the servlet container. Servlet container is
also called web container or servlet engine. It is responsible for handling the life of a servlet.
Step 3 : Servlet container understands the request’s URL and calls the particular servlet.
Actually, it creates a thread for execution of that servlet. If there are multiple requests for the
same servlet, then for each request, one thread will be created.
Step 4 : Servlet processes the request object and prepares response object after interacting with
the database or performing any other operations and sends the response object back to the web
server.
Step 5 : Then web server sends the response back to the client.
JavaScript. The web components typically execute in Web Server and respond to the HTTP
request.
Web browser
A web browser is a program which acts as an interface between user and web application
e.g. Internet Explorer, Chrome, Safari, Mozilla firefox etc.
In the context of a Web application, the client/server model is important because Java code can
run in two places: on the client or on the server. There are trade-offs to both approaches. Server-
based programs have easy access to information that resides on the server, such as customer orders
or inventory data. Because all of the computation is done on the server and results are transmitted
to the client as HTML, a client does not need a powerful computer to run a server-based program.
On the other hand, a client-based program may require a more powerful client computer, because
all computation is performed locally. However, richer interaction is possible, because the client
program has access to local resources, such as the graphics display (e.g., perhaps using Swing) or
the operating system. Many systems today are constructed using code that runs on both the client
and the server to reap the benefit of both approaches.
Web applications built with Java include Java applets, Java servlets, and Java Server Pages
(JSP). Java applets run on the client computer. JavaScript, which is a different language than Java
despite its similar name, also runs on the client computer as part of the Web browser. Java servlets
and Java Server Pages run on the server. Java Server pages which are a dynamic version of Java
servlets. Servlets must be compiled before they can run, just like a normal Java program. In
contrast, JSP code is embedded with the corresponding HTML and is compiled “on the fly” into a
servlet when the page is requested. This flexibility can make it easier to develop Web applications
using JSP than with Java servlets. The following fig1, fig2 and fig3 shows that the running a Java
applet, Java Servlet and JSP program.
Disadvantages of CGI
There are many problems in CGI technology:
COMPILED BY ER. SANTOSH SHRESTHA 7
CHAPTER-10 JAVA SERVER PAGES (JSP) / SERVLET TECHNOLOGY
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for handling
the multiple requests to the Servlet. Threads have many benefits over the Processes such as they
share a common memory area, lightweight, cost of communication between the threads are low.
The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
4. Secure: because it uses java language.
Servlet API
• javax.servlet and javax.servlet.http packages contains the classes and interfaces
for servlet API. These packages are the standard part of Java’s enterprise edition.
• javax.servlet contains a number of classes and interfaces which are mainly used
by servlet container.
• javax.servlet.http contains a number of classes and interfaces which are mainly
used by http protocol.
HTTP Servlet
If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class, which is an
abstract class. Unlike Generic Servlet, the HTTP Servlet doesn’t override the service() method.
Instead it overrides one or more of the following methods. It must override at least one method
from the list below:
• doGet() – This method is called by servlet service method to handle the HTTP GET request
from client. The Get method is used for getting information from the server
• doPost() – Used for posting information to the Server
• doPut() – This method is similar to doPost method but unlike doPost method where we
send information to the server, this method sends file to the server, this is similar to the
FTP operation from client to server
• doDelete() – allows a client to delete a document, webpage or information from the server
• init() and destroy() – Used for managing resources that are held for the life of the servlet
• getServletInfo() – Returns information about the servlet, such as author, version, and
copyright.
In Http Servlet there is no need to override the service() method as this method dispatches the Http
Requests to the correct method handler, for example if it receives HTTP GET Request it dispatches
the request to the doGet() method.
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
To create a Servlet application, at first, we need to follow some steps like installing
Tomcat Server, which gets described below-
First, we need to create the above directory structure inside a directory named
Apache – Tomcat\webapps directory. We need to keep all HTML, static files,
images under the web application creating a folder. The servlets must be kept in the
class folder. Lastly, the web.xml file should be under the WEB-INF folder.
2. Creating a Servlet
To start the Apache Tomcat server, we need to double click on the startup.bat file
under apache-tomcat/bin directory, and it will start working.
To start Tomcat Server for the first time, we need to set JAVA_HOME in the
Environment variable. The following steps are mentioned below.
b. Next, we will go to Advanced Tab, and we need to click on the Environment Variables
button.
c. Therefore, we will click on the New button and enter JAVA_HOME inside the Variable
name text field and the path of JDK inside the Variable value text field. Then, we need to
save it by clicking, OK.
Methods
1. getAttribute(String)
2. getAttributeNames()
It returns the names of the present attributes that are requested by the clients.
3. getCharacterEncoding()
4. getContentLength()
5. getContentType()
At first, it requests the object’s identity. If not found, it returns a NULL value.
6. getInputStream()
Returns a binary stream of data received by the client and then returns the strings.
7. getParameter(String)
8. getParameterNames()
9. getParameterValues(String)
It returns the values of the parameters. They always exist in the form of a string.
10. getProtocol()
11. getReader()
12. getRealPath(String)
13. getRemoteAddr()
14. getRemoteHost()
15. getScheme()
16. getServerName()
17. getServerPort()
Servlet Response
ServletResponse invokes an object, and the response of various users is recorded.
The web container is responsible for all these activities. The step to create this is
very much important. The step is to create an object.
ServletConfig
a. Web container creates the config object based on the initialisation
parameters.
b. 2. One ServletConfig per Servlet must be present.
Methods
1. Equals(Object)
checks if the current object has equal value with the given object.
2. GetHashCode()
3. GetType()
4. MemberwiseClone()
If we invoke this object, a shallow copy can be created. It refers to the present
object by default.
5. ToString()
Types of Servlets
The two types of servlets can be defined as:
1. Generic Servlets
• HTML File
We can create a very uncomplicated HTML file that can look like
WebContent/index.html.
• XML File
We can find this file in the path WebContent/WEB-INF/web.xml. We can
map the servlet with a specific URL.
2. HTTP servlet
The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it. So, before
creating a Servlet object, let’s first understand the life cycle of the Servlet object which is actually
understanding how the Servlet container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
• Loading a Servlet.
• Initializing the Servlet.
• Request handling.
• Destroying the Servlet.
Let’s look at each of these stages in details:
1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing
the Servlet by the Servlet container. The Web container or Servlet Container can load the
Servlet at either of the following two stages :
• Initializing the context, on configuring the Servlet with a zero or positive integer
value.
• If the Servlet is not preceding stage, it may delay the loading process until the Web
container determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
• Loading : Loads the Servlet class.
• Instantiation : Creates an instance of the Servlet. To create a new instance of the
Servlet, the container uses the no-argument constructor.
2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container
initializes the instantiated Servlet object. The container initializes the Servlet object by
invoking the Servlet.init(ServletConfig) method which accepts ServletConfig object
reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once,
immediately after the Servlet.init(ServletConfig) object is instantiated successfully. This
method is used to initialize the resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
3. Handling request: After initialization, the Servlet instance is ready to serve the client
requests. The Servlet container performs the following operations when the Servlet
instance is located to service a request :
// service() method
public class MyServlet implements Servlet{
public void service(ServletRequest res, ServletResponse res)
throws ServletException, IOException {
// request handling code
}
// rest of code
}
3. destroy() method: The destroy() method runs only once during the lifetime of a Servlet
and signals the end of the Servlet instance.
//destroy() method
public void destroy()
As soon as the destroy() method is activated, the Servlet container releases the Servlet
instance.
There are three life cycle methods in the Servlet interface. There are as follows:
1. init() method :
• A servlet’s life begins here .
• This method is called only once to load the servlet.Since it is called only once in it’s
lifetime,therefore “connected architecture” code is written inside it because we only
want once to get connected with the database.
Now Question Arises is that:-
Q.Why can’t we write connected architecture code inside the constructor, since
constructor also run only once in it’s entire life?
Ans. Suppose if the connection doesn’t get established, then we can throw an
exception from init() and the rest of the steps stop executing. But in the constructor
we can’t use, throw in it’s prototype otherwise it is an error.
• This method receives only one parameter, i.e ServletConfig object.
• This method has the possibility to throw the ServletException.
• Once the servlet is initialized, it is ready to handle the client request.
• The prototype for the init() method:
public void init(ServletConfig con)throws ServletException{ }
where con is ServletConfig object
NOTE:- In programs of servlet,we use non parameterized version of init().
Now, Question Arises is that:-
Q. Why it is recommended to use the non parameterized version of init() instead of
parameterized version as seen above?
Ans. To answer this, we have to go into detail. Think like developers,i.e there must be
some valid reason for this and the answer will blow your mind. Coming to answer:
APPROACH 1
Whenever the lifecycle method of a servlet starts executing,i.e when public void
init(ServletConfig con) throws ServletException gets call then our class public void
init(ServletConfig con) throws ServletException gets called but we have to run the code
which initializes servlet config object which is written inside “HttpServlet” method
// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}
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, we can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).
HTTP
• HTTP stands for Hyper Text Transfer Protocol. Following are some of the important
properties of HTTP:
• Based on how the data is sent in the request, HTTP requests are categorized into several
types, but the most important and widely used are the GET requests and POST requests.
GET Request
o GET request is the simplest of all the requests. This type of request is normally used for
accessing server-side static resources such as HTML files, images etc. This doesn’t mean
that GET requests cannot be used for retrieving dynamic resources. To retrieve dynamic
resources, some data must be sent in the request and GET request can send the data by
appending it in the URI itself as shown below:
http://somedomain.com?uid=John&role=admin
In the above URI, the HTTP request sends two pieces of data in the form of name value
pairs. Each name-value pair must be separated by ‘&’ symbol. The server side program
will then read the data, process it, and send a dynamic response.
Þ All the data in the request is appended to the URI itself making the data visible to
everyone. When secure information need to be sent, GET request is not the solution.
Þ GET requests can only send text data and not the binary data. Therefore in situations
where you need to upload image files to server, GET request cannot be used.
POST Request
• In most of the real world applications, all the HTTP requests are sent as POST requests.
The server- side is the heart of any web application as it comprises of the following:
Web Container
• A Web container is the heart of Java based web application which is a sophisticated
program that hosts the server side programs like Servlets.
• Once the Servlet programs are deployed in this container, the container is ready to
receive HTTP requests and delegate them to the programs that run inside the container.
These programs then process the requests and generate the responses.
• Also a single web container can host several web applications.
• Look at the following figure that shows how a typical web container looks
There are several J2EE Web Containers available in the market. One of the most notable one is
the Apache’s Tomcat container which is available for free of cost.
For the web container to run the web application, the web application must follow a standard
directory structure within the container. Let’s say we want to build a web application named
myweb. The directory structure for this application must be as shown below:
Where webapps is a standard directory within the web container (Tomcat installation directory).
It is from this directory, you need to start creating the directory structure. Following table lists
the purpose of each directory:
All the static resources namely html files, image files can be stored directly under myweb
directory. With the above directory structure, all the components within myweb application
should be accessed with the URL starting with:
http://localhost:8080/myweb/
If you want to create another web application like mywebproject, you must again create the same
directory structure with mywebproject as the root directory and should access the components
using the URL starting with:
http://localhost:8080/mywebproject/
The form data will be sent in the HTTP request object as name value pairs as shown below:
http://localhost:8080/myweb/SomeServlet?name=John&age=20
The servlet then reads the above request data using the HttpServletRequest object as shown
below:
String fn = request.getParameter(“name”);
String age = request.getParameter(“age”);
fn will now have John and age will have 20. The servlet can do whatever it want with the data,
and send a confirmation message back.
//File: SimpleInterestFindingServlet.java
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 SimpleInterestFindingServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//reading the values
String principle =request.getParameter("principle");
String time=request.getParameter("time");
String rate=request.getParameter("rate");
//parsing the string values to double
double t = Double.parseDouble(time);
double p = Double.parseDouble(principle);
double r = Double.parseDouble(rate);
// declaring variable to hold the result
double si;
//computing simple interest
si = (p*t*r)/100;
Example: Reading the values from html form and storing in a table of a database
</tr>
<tr>
<td> <br/><br/></td>
<td><br/><br/><input type="submit" value="Submit"/>
</tr>
</table>
</form>
</body>
</html>
//File: FormProcessingServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FormProcessingServlet extends HttpServlet {
String driverName;
String dbURL;
final String DB_USERNAME="root";
final String DB_PASSWORD="";
@Override
public void init(ServletConfig config) throws
ServletException {
// This method is called before the following methods are called
//and gets called only ONCE. This is like a
// constructor. We do all the initialization here.
driverName = config.getInitParameter("driver");
dbURL = config.getInitParameter("URL");
}
@Override
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String responseMessage;
// Reading the form data
String name = request.getParameter("name");
String a = request.getParameter("age");
String addr = request.getParameter("address");
try{
//converting age value into int
int age = Integer.parseInt(a);
//calling method which conneccts to db and inserts values
int status=connectAndInsert(name,age,addr);
if (status!=-1)
responseMessage = "Congratulations! the form is successfully submitted";
else
Statement st;
st = con.createStatement();
int n;
n=st.executeUpdate(queryToFire);
st.close();
con.close();
return n;
}}
-------------------------------------------------------------
File: 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>FormProcessingServlet</servlet-name>
<servlet-
class>someservlets.FormProcessingServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>URL</param-name>
<param-
value>jdbc:mysql://localhost:3306/java2lab</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FormProcessingServlet</servlet-name>
<url-pattern>/formprocessing</url-pattern>
</servlet-mapping>
</web-app>
Outputs:
In web application terminology we call the shared data or information as state. Having state is
just not sufficient. Someone must be able to pass this state from one servlet to other servlet so
that they can share the data. So, who does this state propagation? Can HTTP do this? No,
because HTTP is a stateless protocol which means it cannot propagate the state. So, is there
anyone to help us out here to make the state available to all the servlets? Yes, there is one guy
who is always there for our rescue and it’s none other than web container (Tomcat).
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.
A web container provides a common storage area called as session store the state and provides
access to this session to all the servlets within the web application. For instance, servlet A can
create some state (information) and store it in the session. Servlet B can then get hold of the
session and read the state.
There are following ways to maintain session between web client and web server (i.e. State can
be maintained indirectly) using –
1. Cookies
2. Hidden Form Fields
3. URL Rewriting
4. HttpSession Object
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 received cookie.
This may not be an effective way because many time browser does not support a cookie.
This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) 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.
URL rewriting is a better way to maintain sessions and it works even when browsers don't
support cookies. The drawback of URL re-writing is that you would have to generate every
URL dynamically to assign a session ID, even in case of a simple static HTML page.
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 −
Since the state (data or information) in the session is user specific, the web container maintains a
separate session for each and every user as shown in the following diagram.
If you look at the above figure, every user will have his own session object for storing the state
pertaining to his transaction and all the servlets will have access to the same session. Also notice,
the session objects are present within the container.
Now that we know what a session is, let’s see how a servlet uses the session for sharing the data
across multiple pages in a web application. A servlet can do the following four most important
operations to work with sessions.
Creating a Session
The servlet API provides us with a class called HttpSession to work with sessions. To create a
session, we do the following:
The above method returns a new session object if one is not present, otherwise it returns the old
session object that is already created before.
session.setAttribute(“price”,new Double(“12.45”));
To read the data, we need to use the getAttribute() method by passing in the key as shown below
which then returns the value object:
Double d = (Double)session.getAttribute(“price”);
Notice that we need to do proper casting here. Since we stored Double object, we need to cast it
again as Double while reading it.
A session is usually destroyed by the last page or servlet in the web application. A session is
destroyed by invoking the invalidate() method as shown below:
session.invaliadte()
Request Dispatching
• Request dispatching is the ability of one servlet to dispatch or delegate the request to another
servlet for processing.
• In simple words, let's say we have a servlet A which doesn't know how to completely process
the request. Therefore, after partially processing the request, it should forward the request to
another servlet B. This servlet then does the rest of the processing and sends the final response
back to the browser.
• The class used for dispatching requests is the RequestDispatcher interface in Servlet API. This
interface has two methods namely forward() and include().
Syntax:
public RequestDispatcher getRequestDispatcher(String resource);
Example:
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
//servlet2 is the url-pattern of a servlet
rd.forward(request, response); //method may be include or forward
The forward() method
This method is used for forwarding request from one servlet to another. Consider two servlets A
and B. Using this method, A gets the request, which then forwards the request to B, B processes
the request and sends the response to the browser. This method takes HttpServletRequest and
HttpServletResponse as parameters.
The include() method
With this method, one servlet can include the response of other servlet. The first servlet will then
send the combined response back to the browser. This method also takes HttpServletRequest
and HttpServletResponse as parameters.
Following two figures demonstrate dispatching using forward() and include() methods
Note:
It forwards the request from one servlet to another resource (such as servlet, JSP, HTML file).
public void include(HttpServletRequest request, HttpServletResponse response): It includes the
content of the resource(such as servlet, JSP, HTML file) in the response.
To understand the difference between these two methods, let’s take an example: Suppose you
have two pages X and Y. In page X you have an include tag, this means that the control will be
in the page X till it encounters include tag, after that the control will be transferred to page Y. At
the end of the processing of page Y, the control will return back to the page X starting just after
the include tag and remain in X till the end.
In this case the final response to the client will be send by page X.
Now, we are taking the same example with forward. We have same pages X and Y. In page X,
we have forward tag. In this case the control will be in page X till it encounters forward, after
this the control will be transferred to page Y. The main difference here is that the control will not
return back to X, it will be in page Y till the end of it.
In this case the final response to the client will be send by page Y.
index.html
<html>
<head>
<title>RequestDispatching</title>
<h4> Login </h4>
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="LOGIN"/>
</form>
</body>
</html>
//Login.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Login extends HttpServlet {
@Override
RequestDispatcher
rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
} }}
//WelcomeServlet.java
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 WelcomeServlet extends HttpServlet {
@Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("userName");
out.print("Welcome "+name);
} }
//web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>someservlets.Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>someservlets.WelcomeServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
In this example, we are creating 3 links: login, logout and profile. User can't go to profile page
until s/he is logged in. If user is logged out, s/he need to login again to visit profile.
1. main.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml
//main.html
<!DOCTYPE html>
<html>
<head><title>MainPage</title></head>
<body>
<div align = "center">
<h1>Login App using HttpSession</h1>
<hr/>
<h2>
<a href="login.html">Login</a>|
<a href="LogoutServlet">Logout</a>|
<a href="ProfileServlet">Profile</a>
</h2>
<br/><hr/>
</div>
</body>
</html>
//login.html
<!DOCTYPE html>
<html><head><title>LoginPage</title></head>
<body>
<div align ="center"><h2> Login </h2>
<form action="LoginServlet" method="post">
</html>
//link.html
<!DOCTYPE html>
<html>
<head><title>Links</title></head>
<body>
<div align ="center">
<h2> <a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
</h2><hr/> <hr/>
</div>
</body>
</html>
//LoginServlet.java
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;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
@Override
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin123")){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
} else{
out.close();
}
} ---------------------------------------------------
//LogoutServlet.java
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;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
@Override
} }
HttpSession session=request.getSession(false);
if(session==null){
out.print("You are not logged in yet!");
}
else {
session.invalidate();
out.print("You are successfully logged out!");
}
out.close();
}
}
//ProfileServlet.java
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;
import javax.servlet.http.HttpSession;
public class ProfileServlet extends HttpServlet {
@Override
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
out.print("Hello, "+name+" Welcome to Profile <br/> You
are awesome :)");
} else{
out.close();
}
} ----------------------------------------------- //web.xml
<web-app>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>someservlets.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>someservlets.LogoutServlet</servlet-
class>
</servlet>
<servlet>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>someservlets.ProfileServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
</web-app>
-------------------------------------------------------------
JSP Programming
• JSP is another J2EE technology for building web applications using Java.
• 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.
• Java Server Pages (JSP) is a technology which is used to develop web pages by
inserting Java code into the HTML pages by making special JSP tags.
• JSP technology is built on top of servlet technology. This is why we can call JSP as an
abstraction over servlet. What does abstraction mean? In simple terms, abstraction is a
simplified fine grained layer over a slightly more complex layer that makes the
development faster and easier. More the abstraction, more the simplicity.
• JSP technology is used to create dynamic web applications. JSP pages are easier to
maintain than a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code
inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything
a Servlet can do, a JSP page can also do it.
JSP Basics
A typical JSP page very much looks like html page with all the html markup except that you also
see Java code in it. So, in essence,
Therefore, JSP content is a mixed content, with a mixture of HTML and Java. If this is the case,
one question arises. Can we save this mixed content in a file with “.html” extension? You guessed
it right. No we can’t, because the html formatter will also treat the Java code as plain text which is
not what we want. We want the Java code to be executed and display the dynamic content in the
page. For this to happen, we need to use a different extension which is the “.jsp” extension. Good.
To summarize, a html file will only have html markup, and a jsp file will have both html
markup and Java code. Point to be noted.
• When the browser requests for html file, the web container simply responds with a html
response without any processing.
• However, when the browser sends a JSP page request, the web container assumes that the
JSP page might include Java code, and translates the page into a Servlet. The servlet then
processes the Java code, and returns the complete html response including the dynamic
content generated by the Java code.
• For a web container to translate JSP, it needs to identify from the JSP page, as to which is
HTML markup and which is Java code. According to J2EE specification, a JSP page must
use special symbols as placeholders for Java code. The web container instead of scratching
its head to identify Java code, simply uses the special symbols to identify it. This is a
contract between JSP and the Web container.
• Let’s understand what these special symbols are. In JSP, we use four different types of
placeholders for Java code. Following table shows these placeholders along with how the
web container translates the Java code with them.
To better understand the above four place holders, let’s take a sample JSP page and see how the
web container translates it into a Servlet. See the following JSP and Servlet code snippets.
Lifecycle of JSP
A JSP page is converted into Servlet in order to service requests. The translation of a JSP page to
a Servlet is called Lifecycle of JSP. JSP Lifecycle is exactly same as the Servlet Lifecycle, with
one additional first step, which is, translation of JSP code to Servlet code. Following are the JSP
Lifecycle steps:
Translation – JSP pages doesn’t look like normal java classes, actually JSP container parse
the JSP pages and translate them to generate corresponding servlet source code. If JSP file name
is home.jsp, usually its named as home_jsp.java.
Compilation – If the translation is successful, then container compiles the generated servlet
source file to generate class file.
Class Loading – Once JSP is compiled as servlet class, its lifecycle is similar to servlet and
it gets loaded into memory.
Instance Creation – After JSP class is loaded into memory, its object is instantiated by
the container.
Initialization – The JSP class is then initialized and it transforms from a normal class to
servlet. After initialization, ServletConfig and ServletContext objects become accessible to JSP
class.
Request Processing – For every client request, a new thread is spawned with
ServletRequest and ServletResponse to process and generate the HTML response.
Destroy – Last phase of JSP life cycle where it’s unloaded into memory.
Web Container translates JSP code into a servlet class source (.java) file, then compiles that into
a java servlet class. In the third step, the servlet class bytecode is loaded using classloader. The
Container then creates an instance of that servlet class.
The initialized servlet can now service request. For each request the Web Container call
the _jspService() method. When the Container removes the servlet instance from service, it calls
the jspDestroy() method to perform any required clean up.
Let's see what really happens to JSP code when it is translated into Servlet. The code written
inside <% %> is JSP code.
<html>
<head><title>My First JSP Page</title> </head>
<%
int count = 0;
%>
<body>
</html>
This is just to explain, what happens internally. As a JSP developer, you do not have to worry
about how a JSP page is converted to a Servlet, as it is done automatically by the web container.
If the session attribute is set to true, then the page will have access to session.
Ex 3: If a JSP page should forward to a custom error page for any exceptions within the page,
the page directive will be as shown below:
The web container will then forward the request to Error.jsp if it encounters exceptions within
the page.
Ex 4: If a JSP page should allow itself as an error page for other JSP pages, it should use the
following page attribute:
Instead of defining one attribute per page directive, we can define all the attributes at a time as
shown below:
Example:
//File:PageDirectiveDemo.jsp
<%@ page import="java.util.*" session= 'true'
isErrorPage='false'%>
<HTML>
<HEAD><TITLE>PageDirectiveDemo</TITLE></HEAD>
<BODY>
<h4>Welcome to the world of JSP</h4>
This JSP uses the page directive
</BODY>
</HTML>
This directive is used to include the response of another resource (JSP or html) at the point where
the directive is placed in the current JSP. Its usage is shown below.
<HEAD><TITLE>IncludeDirectiveDemo</TITLE></HEAD>
<BODY>
<h4> This is the response from the current JSP page</h4>
<h3> Following is the response from another JSP </h3>
<hr/>
<%@ include file='/jsps/PageDirectiveDemo.jsp' %>
<hr/>
</BODY>
</HTML>
This directive allows the JSP page to use custom tags written in Java. Custom tag definitions are
usually defined in a separate file called as Tag Library Descriptor. For the current JSP to use a
custom tag, it needs to import the tag library file which is why this directive is used. Following is
how taglib directive is used.
JSP Declarations
JSP declarations are used to declare global variables and methods that can be used in the entire
JSP page. A declaration block is enclosed within <%! and %> symbols as shown below:
<%!
Variable declarations
Global methods
%>
Example:
<html>
<head><title>JSPDeclarationDemo</title></head>
<body>
<%@ page import = "java.util.Date" %>
<%!
String getGreeting( String name){
Date d = new Date();
return "Namaste " + name + "! It's "+ d + " and how are you
doing today";
}
%>
<h3> This is a JSP Declaration demo. The JSP invokes the
JSP Expressions
Expressions in JSP are used to display the dynamic content in the page. An expression could be a
variable or a method that returns some data or anything that returns a value back. Expressions are
enclosed in <%= and %> as shown below
int result;
if(n==0){
return 1;
}
else{
result = n*fact(n-1);
return result;
}
%>
<br/>
JSP Scriptlets
A Scriptlet is a piece of Java code that represents processing logic to generate and display the
dynamic content where ever needed in the page. Scriptlets are enclosedbetween <% and %>
symbols. This is the most commonly used placeholder for Java. code.
This JSP Scripting Element allows you to put in a lot of Java code in your HTML code. This
Java code is processed top to bottom when the page is the processed by the web server. Here the
result of the code isn’t directly combined with the HTML rather you have to use “out.println()”
to show what you want to mix with HTML.
<html>
<head><title>JSP Scriplet Demo</title></head>
<body>
<h2> This is an example using JSP Scriplets</h2>
<br/><hr/><h3>The multiplication table of 7 </h3>
<% for(int i =1; i<=10;i++){
out.print("7 * "+ i+ "= "+7*i+"<br/>");
} %>
<br/><hr/><br/>
<h3> Following is generated by the Loop</h3>
<% for(int i=2;i<=5;i++){
if( i % 2 == 0){
out.print(i + " is an even number <br/>");
}
else{
out.print(i + " is an odd number <br/>");
} } %>
</body>
</html>
showdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %> </body>
</html>
It can also be used to set, get and remove attributes from the jsp request scope.
Let's see the simple example of request implicit object where we are printing the name of the
user with welcome message.
form1.html
welcome.jsp
<form action="welcome.jsp">
<input type="text" name="uname"> <input type="submit" value="go"><br/>
</form>
It can be used to add or manipulate response such as redirect response to another resource, send
error etc.
Let's see the example of response implicit object where we are redirecting the response to the
‘wordlover’.
form2.html
<form action="redirect.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
redirect.jsp
<body>
<%
response.sendRedirect("http://www.wordloverbipin.wordpr
ess.com");
%>
</body>
In JSP, pageContext is an implicit object of type PageContext class.The pageContext object can
be used to set,get or remove attribute from one of the following scopes:
• page
• request
• session
• application
Object page=this;
Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
JSTL Tags
There JSTL mainly provides five types of tags:
Core tags The JSTL core tag provide variable support, URL management, flow control,
etc. The URL for the core tag is http://java.sun.com/jsp/jstl/core. The prefix
of core tag is c.
Function The functions tags provide support for string manipulation and string length.
tags The URL for the functions tags is http://java.sun.com/jsp/jstl/functions and
prefix is fn.
Formatting The Formatting tags provide support for message formatting, number and date
tags formatting, etc. The URL for the Formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
XML tags The XML tags provide flow control, transformation, etc. The URL for the
XML tags is http://java.sun.com/jsp/jstl/xml and prefix is x.
SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.
For creating JSTL application, you need to load the jstl.jar file
2) fn:containsIgnore..
3) fn:endsWith()
4) fn:escapeXml()
5) fn:indexOf()
6) fn:trim()
7) fn:startsWith()
8) fn:split()
9) fn:toLowerCase()
10) fn:toUpperCase()
11) fn:substring()
12) fn:substringAfter()
13) fn:substringBefore()
14) fn:length()
15) fn:replace()
1) fmt:parseNumber
2) fmt:timeZone
3) fmt:formatNumber
4) fmt:parseDate
5) fmt:bundle
6) fmt:setTimeZone
7) fmt:setBundle
8) fmt:message
9) fmt:formatDate
1) x:out
2) x:parse
3) x:set
4) x:choose
5) x:when
6) x:otherwise
7) x:if
8) x:transform
9) x:param
1) sql:setDataSource
2) sql:query
3) sql:update
4) sql:param
5) sql:dateParam
6) sql:transaction
Tags Description
c:out It displays the result of an expression, similar to the way <%=...%> tag
work.
c:remove It is used for removing the specified scoped variable from a particular
scope.
c:catch It is used for Catches any Throwable exceptions that occurs in the body.
c:if It is conditional tag used for testing the condition and display the body
content only if the expression evaluates is true.
c:choose, c:when, It is the simple conditional tag that includes its body content if the
c:otherwise evaluated condition is true.
c:forEach It is the basic iteration tag. It repeats the nested body content for fixed
number of times or over collection.
c:redirect It redirects the browser to a new URL and supports the context-relative
URLs.