Introduction To JSP
Introduction To JSP
Introduction To JSP
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 enables us to write HTML pages containing tags, inside which we can include powerful Java
programs. Using JSP, one can easily separate Presentation and Business logic.
1. Servlet is a mixture of java skills and web related HTML skills, because you have to write the
business logic in java and for presentation you should write the HTML, so the role-based
development is missing in pure servlet. The developer who is writing servlet should know java
and HTML both.
2. The servlet technology requires more steps to develop, servlet require too long time for
development.
3. If your application is built on using only servlet technology, it is very difficult for enhancement
and bug fixing.
5. Servlets are very difficult for Non-Java Programmers to understand and carry out.
6. We know that, Servlet is a picture of both Presentation logic (HTML) and Business Logic (Java).
At the time of development of Servlet by using both of the above (Presentation and Business
Logic), it may become imbalance, because a Servlet developer can’t be good in both
Presentation logic and Business logic.
7. Servlet never provides separation between or clarity between Presentation Logic and Business
Logic. So that servlets do not give Parallel Development.
9. If we develop any web application with servlets, then it is mandatory for the web application
developer to configure web-application configuration file (Deployment descriptor- web.xml).
10. Servlets do not offer any implicit object [Implicit objects generally provided by containers
during the dynamic program execution].
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.
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.
To create the first JSP page, write some HTML code as given below, and save it by .jsp extension. We
have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in
Apache tomcat to run the JSP page.
<html>
<body>
<% out.print(2*5); %>
</body>
</html>
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into servlet content. This
conversion is very simple in which all template text is converted to println () statements and
all JSP elements are converted to Java code. This code implements the corresponding
dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format. The output is further
passed on to the web server by the servlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside the HTTP
response exactly as if it were a static page.
JSP Elements
JSP elements are called the JSP tags on JSP page. On the JSP page mainly three groups of JSP
elements are used:
The scripting elements provide the ability to insert java code inside the jsp. There are three types of
scripting elements:
scriptlet tag
expression tag
declaration tag
Example
<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>
<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>
JSP expression tag
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 %>
Example
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with semicolon in case of expression tag.
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.html
<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>
Syntax
<%! field or method declaration %>
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>
<%!
int cube (int n) {
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube (3) %>
</body>
</html>
1. The jsp scriptlet tag can only declare variables not methods.
2. The declaration of scriptlet tag is placed inside the _jspService () method.
Comments in JSP
JSP comment marks to text or statements that the JSP container should ignore. A JSP comment is
useful when you want to hide or "comment out", a part of your JSP page.
Following is the syntax of the JSP comments −
<% -- This is JSP comment -- %>
Model View Controller (MVC) is a software design architectural pattern for developing the web
application. MVC pattern separates business logic, presentation, and data. MVC pattern has the
following three parts —
1. Model – This level is responsible for all kinds of business logic operations. It has the classes
which have the connection with the database.
2. View – This is the presentation layer which consists of HTML, JSP pages. This layer is responsible
for displaying the application’s output to the end users.
3. Controller – This layer handles the HTTP requests and sends to the appropriate Model layer for
data processing, and once the data are processed and sent back to the controller and then
displayed on the View layer.
JSP container makes some Java objects available to the JSP page. No specific declaration or
initialization is required within the JSP page. These objects are called implicit objects. List of the JSP
implicit objects is included below
Object Type
Out JspWriter
Request HttpServletRequest
Response HttpServletResponse
Config ServletConfig
Application ServletContext
Session HttpSession
pageContext PageContext
Page Object
Exception Throwable
Out is one of the implicit objects to write the data to the buffer and send output to the client
in response
Out object allows us to access the servlet's output stream
Out is object of javax.servlet.jsp.jspWriter class
While working with servlet, we need printwriter object
Example:
<html>
<head>
</head>
<body>
<% int num1=10; int num2=20;
out.println("num1 is " +num1);
out.println("num2 is "+num2);
%>
</body>
</html>
The JSP request is an implicit object of type HttpServletRequest i.e., created for each jsp request by
the web container.
It can be used to get request information such as parameter, header information, remote address,
server name, server port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request scope.
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
config implicit object
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
application implicit object
index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
session implicit object
In JSP, session is an implicit object of type HttpSession. The Java developer can use this object to set,
get or remove attribute or to get session information.
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user”, name,PageContext.SESSION_SCOPE);
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)pageContext.getAttribute("user”, PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
page implicit object
In JSP, page is an implicit object of type Object class. This object is assigned to the reference of auto
generated servlet class.
This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page.
It is written as:
Object page=this;
For using this object, it must be cast to Servlet type. For example:
Since, it is of type Object it is less used because you can use this object directly in jsp. For example:
In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to
print the exception. But it can only be used in error pages.
JSP directives
Directives control the processing of an entire JSP page. It gives directions to the server
regarding processing of a page.
Directive Tag gives special instruction to Web Container at the time of page translation.
JSP directives are the messages to JSP container. They provide global information about an
entire JSP page.
1. Page directive
2. Include directive
3. Taglib directive
Syntax:
<%@ directive_name [attribute name= “value” attribute name= “value” ........] %>
Page directive
Syntax:
import
The import attribute is used to import class, interface or all the members of a package. It is similar to
import keyword in java class or interface.
Example:
<html>
<body>
</body>
</html>
contentType
The contentType attribute defines the MIME (Multipurpose Internet Mail Extension) type of the HTTP
response. The default value is "text/html;charset=ISO-8859-1".
Example:
<html>
<body>
Info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
<html>
<body>
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet. For example:
The include directive is used to include the contents of any resource it may be jsp file, html file or
text file.
The include directive includes the original content of the included resource at page translation time
(the jsp page is translated only once so it will be better to include static resource).
This directive tells the container to merge the content of other external files with the current JSP
during the translation phase. You may code the include directives anywhere in your JSP page.
Syntax
Example
<html>
<body>
</body>
</html>
header.html
<html>
<body>
Taglib directive
The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag
Library Descriptor) file to define the tags.
Syntax
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example
In this example, we are using our tag named currentDate. To use this tag, we must specify the taglib
directive so the container may get information about the tag.
<html>
<body>
<mytag:currentDate/>
</body>
</html>
The exception is normally an object that is thrown at runtime. Exception Handling is the process to
handle the runtime errors.
Example:
In this case, you must define and create a page to handle the exceptions, as in the error.jsp page. The
pages where may occur exception, define the errorPage attribute of page directive, as in the
process.jsp page.
index.jsp
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No2:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>
process.jsp
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
error.jsp
The action tags are used to control the flow between pages and to use Java Bean. JSP provides a
bunch of standard action tags that we can use for specific tasks such as working with java bean
objects, including other resources, forward the request to another resource etc. The Jsp action tags
are given below.
jsp:include To include a resource at runtime, can be HTML, JSP or any other file
jsp:useBean To get the java bean object from given scope or to create a new object of java bean.
jsp:getProperty To get the property of a java bean, used with jsp:useBean action.
jsp:setProperty To set the property of a java bean object, used with jsp:useBean action.
To generate the browser-specific code that makes an OBJECT or EMBED tag for the
jsp:plugin
Java plugin.
jsp:param sets the parameter value. It is used in forward and include mostly.
jsp:forward action tag
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or
another resource.
Syntax
(or)
<html>
<head>
<title>Demo of JSP Param Action Tag</title>
</head>
<body>
<h3>JSP page: Demo Param along with forward</h3>
<jsp:forward page="second.jsp">
</jsp:forward>
</body>
</html>
Second.jsp
The jsp:include action tag is used to include the content of another resource it may be jsp, html or
servlet.
The jsp include action tag includes the resource at request time so it is better for dynamic
pages because there might be changes in future.
The jsp:include tag can be used to include static as well as dynamic pages.
Syntax
<jsp:include page="relativeURL | <%= expression %>"/>
(or)
Example
index.jsp
printdate.jsp
Syntax
page: specifies that you can use this bean within the JSP page. The default scope is
page.
request: specifies that you can use this bean from any JSP page that processes the
same request. It has wider scope than page.
session: specifies that you can use this bean from any JSP page in the same session
whether processes the same request or not. It has wider scope than request.
application: specifies that you can use this bean from any JSP page in the same
application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but it
must have no-arg or no constructor and must not be abstract.
<jsp:setProperty> Action Tag
This action tag is used to set the property of a Bean, while using this action tag, you may need to
specify the Bean’s unique name (it is nothing but the id value of useBean action tag).
Syntax:
Syntax
EmployeeBeanTest.jsp
<html>
<head>
<title>JSP Page to show use of useBean action</title>
</head>
<body>
<h1>Demo: Action</h1>
<jsp:useBean id="student" class="javabeansample.StudentBean"/>
<jsp:setProperty name="student" property="name" value=”Raju”/>
<jsp:setProperty name="student" property="rollno" value=”501”/>
<h1>
Name:<jsp:getProperty name="student" property="name"/><br>
Rollno:<jsp:getProperty name="student" property="rollno"/><br>
</h1>
</body>
</html>
StudentBean.java
package javabeansample;
public class StudentBean {
public StudentBean() {
}
private String name;
private int rollno;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public void setRollno(int rollno)
{
this.rollno=rollno;
}
public int getRollno()
{
return rollno;
}
}
Parsing of JSP
Turning JSP into servlet
Compiling the servlet