Unit-5 JSP Notes
Unit-5 JSP Notes
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 Tag etc.
There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of 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 a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover,
we can use EL, implicit objects etc.
1
As depicted in the above diagram, JSP page is translated into servlet by the help of JSP translator. The JSP
translator is a part of webserver that is responsible to translate the JSP page into servlet. Afterthat Servlet
page is compiled by the compiler and gets converted into the class file. Moreover, all the processes that
happens in servlet is performed on JSP later like initialization, committing response to the browser and
destroy.
To create the first jsp page, write some html code as given below, and save it by .jsp extension. We have
save 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.
index.jsp
Let's see the simple example of JSP, here we are using the scriptlet tag to put java code in the JSP page.
We will learn scriptlet tag later.
<html>
<body>
<% out.print(“welcome to JSP”); %>
</body>
</html>
2
How to run a simple JSP Page?
No, there is no need of directory structure if you don't have class files or tld files. For example, put jsp files
in a folder directly and deploy that folder.It will be running fine.But if you are using bean class, Servlet or
tld file then directory structure is required.
The directory structure of JSP page is same as servlet. We contains the jsp page outside the WEB-INF
folder or in any directory.
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what the scripting
elements are 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
3
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
index.html
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name and password
In this example, we have created two files index.html and welcome.jsp. The index.html file gets the
username and password from the user and the welcome.jsp file prints the username and password with
the welcome message.
index.html
<html>
<body>
<form action="welcome.jsp">
Enter Username: <input type="text" name="uname"> <br>
</html>
welcome.jsp
<%
String name=request.getParameter("uname");
String pass=request.getParameter("pwd");
out.print("welcome "+name);
4
out.println(“password” + pass);
%>
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.
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Example of JSP expression tag that prints the user name and password
index.html
<html>
<body>
<form action="welcome.jsp">
</body>
</html>
welcome.jsp
<%
String name=request.getParameter("uname");
String pass=request.getParameter("pwd");
%>
5
<%= "welcome” + name %>
<%= "password” + pass %>
In this example, we are printing the username and password using the expression tag. The index.html file gets the
username and password and sends the request to the welcome.jsp file, which displays the username and password.
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
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>
The jsp scriptlet tag can only declare The jsp declaration tag can declare
variables not methods. variables as well as methods.
</body>
</html>
6
Example of JSP declaration tag that declares method
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
<%!
int cube(int n)
{
return n*n*n*;
}
%>
There are 9 jsp implicit objects. These objects are created by the web container that are available to all the
jsp pages.
The available implicit objects are out, request, config, session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
For writing any data to the buffer, JSP provides an implicit object named out. It is the object of JspWriter.
In case of servlet you need to write:
7
PrintWriter out=response.getWriter();
index.jsp
<%
out.print("welcome to jsp”);
%>
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.
Let's see the simple example of request implicit object where we are printing the name of the user with
welcome message.
<form action="welcome.jsp">
Enter Username: <input type="text" name="uname"> <br>
Enter Password: <input type="password" name="pwd"> <br>
<input type="submit" >
<input type="reset" >
</form>
</body>
</html>
welcome.jsp
<%
String name=request.getParameter("uname");
String pass=request.getParameter("pwd");
8
out.print("welcome "+name);
out.println(“password” + pass);
%>
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 Google.
<input type="submit"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
In JSP, config is an implicit object of type ServletConfig. This object can be used to get initialization
parameter for a particular JSP page. The config object is created by the web container for each jsp page.
web.xml file
<web-app>
9
<servlet>
<servlet-name>myservlet</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>student</param-name>
<param-value>Rajesh</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
String std=config.getInitParameter("student");
%>
The instance of ServletContext is created only once by the web container when application or project is
deployed on the server.
This object can be used to get initialization parameter from configuaration file (web.xml). It can also be
used to get, set or remove attribute from the application scope.
<input type="submit">
</form>
web.xml file
10
<web-app>
<servlet>
<servlet-name>myservlet</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>student</param-name>
<param-value>Rahul</param-value>
</context-param>
</web-app>
welcome.jsp
<%
String std=config.getInitParameter("student");
%>
Syntax:
session.setAttribute(“name”,”value”);
session.getAttribute(“name”);
session.removeAttribute(“name”);
Example:
Index.html
<html>
<body>
<form action="login.jsp">
Enter User Name:<input type="text" name="uname"> <br>
11
Enter Password: <input type="password" name="pwd"><br>
<input type="submit">
<input type="reset">
</form>
</body>
</html>
Links.html
<a href="index.html">Login</a>|
<a href="profile.jsp">Profle</a>|
<a href="logout.jsp">Logout</a>
<hr>
Login.jsp
<jsp:include page="links.html" />
</br>
<%
String name=request.getParameter("uname");
String pass=request.getParameter("pwd");
String un = "lbrce";
String ps = "lbrce123";
<br>
<%
session.removeAttribute("user");
out.println("logout successfully");
%>
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:
o page
o request
o session
o application
pageContext.setAttribute(“name”,”value”, PageContext.PAGE_SCOPE);
pageContext.getAttribute(“name”);
PageContext.removeAttribute(“name”);
session scope:
pageContext.setAttribute(“name”,”value”, PageContext.SESSION_SCOPE);
pageContext.getAttribute(“name”);
PageContext.removeAttribute(“name”);
request scope:
pageContext.setAttribute(“name”,”value”, PageContext.REQUEST_SCOPE);
13
pageContext.getAttribute(“name”);
PageContext.removeAttribute(“name”);
application scope:
pageContext.setAttribute(“name”,”value”, PageContext.APPLICATION_SCOPE);
pageContext.getAttribute(“name”);
PageContext.removeAttribute(“name”);
In JSP, page is an implicit object of type Object class.This object is assigned to the reference of auto
generated servlet class. It is written as:
Object page=this;
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.It is better to learn it after page directive. Let's see
a simple example:
Index.html
<input type="submit">
<input type="reset">
</form>
Welcome.jsp
14
<%@ page errorPage="error.jsp" %>
<%
int x = Integer.parseInt(request.getParameter("num1"));
int y = Integer.parseInt(request.getParameter("num2"));
%>
Error.jsp
%>
JSP program to insert data from HTML form to oracle database
Index.html
<form name="myform" action="register.jsp">
enter username <input type="text" name="uname"> <br>
15
eter password <input type="password" name="pwd"> <br>
enter your mail<input type="mail" name="mail"><br>
choose your gender:<input type ="radio" name="gender" value="male">male
<input type ="radio" name="gender" value="female">female<br>
<input type="submit" >
<input type="reset">
</form>
Register.jsp
<%@ page import="java.sql.*" %>
<%
String un=request.getParameter("uname");
String ps=request.getParameter("pwd");
String email=request.getParameter("mail");
String gen=request.getParameter("gender");
try{
oracle.jdbc.driver.OracleDriver d=new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(d);
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","cse","cse");
String qry="insert into student values(?,?,?,?)";
PreparedStatement pst=con.prepareStatement(qry);
pst.setString(1,un);
pst.setString(2,ps);
pst.setString(3,email);
pst.setString(4,gen);
int i=pst.executeUpdate();
out.println(i+"Row's inserted successully");
}
catch(Exception e)
{
e.printStackTrace();
}
%>
JSP Program to display data from oracle database to web browser.
Display.jsp
<%@page import="java.sql.*"%>
<%
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(("jdbc:oracle:thin:@localhost:1521:xe","cse","cse");
Statement stmt=con.createStatement();
String query="select * from student";
ResultSet rs=stmt.executeQuery(query);
%>
<html>
<body bgcolor="pink">
<center>
16
<h1>Welcome to Student Details</h1>
<table border="5" bgcolor="white">
<th>
<tr>
<td colspan="5" align="center">Student Details</td></tr>
</th>
<tr>
<td>Student id</td>
<td>Name</td>
<td>Address</td>
<td>DOB</td>
</tr>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
</tr>
<%
}
%>
</table>
<br>
<br>
}
catch(Exception e)
{
out.println(e.toString());
}
%>
JSP program to print multiplication table for the given table number with limit from HTML form
Index.html
<form name="myform" action="welcome.jsp">
Enter table number: <input type="text" name="table"><br>
Enter limit value: <input type="text" name="limit"><br>
<input type="submit">
<input type="reset">
</form>
Welcome.jsp
<%
int table = Integer.parseInt(request.getParameter("table"));
int limit = Integer.parseInt(request.getParameter("limit"));
out.println("<table border=1>");
for(int i=1; i<=limit; i++)
17
{
out.println("<tr>");
out.println("<td>"+table+"</td>");
out.println("<td>*</td>");
out.println("<td>"+i+"</td>");
out.println("<td>=</td>");
out.println("<td>"+table*i+"</td>");
out.println("</tr>");
}
out.println("</table>");
%>
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
o page directive
o include directive
o taglib directive
The page directive defines attributes that apply to an entire JSP page.
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.
</body>
</html>
errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be
redirected to the error page.
</body>
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
19
Note: The exception object can only be used in the error page.
</body>
</html>
Jsp Include Directive
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).
Code Reusability
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. In the custom tag section we will use this tag so it will be better to learn
it in custom tag.
There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags are
given below.
The jsp:forward action tag is used to forward the request to another resource it may be jsp, html or
another resource.
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:
Code reusability : We can use a page many times such as including header and footer pages in all pages.
So it saves a lot of time.
21
The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is
already created, it doesn't create the bean depending on the scope. But if object of bean is not created, it
instantiates the bean.
The jsp:setProperty action tag sets a property value or values in a bean using the setter method.
Syntax of jsp:setProperty action tag
<jsp:setProperty ="instanceOfBean" property="propertyName" value="value of property”/>
jsp:getProperty action tag
The jsp:getProperty action tag returns the value of the property.
Example:
Employee.java
package mypack;
public class Employee implements java.io.Serializable
{
private int id;
private String name;
public Employee()
{
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
22
{
this.name=name;
}
public String getName()
{
return name;
}
index.jsp
<jsp:useBean id="emp" class="mypack.Employee"/>
Example:
MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString(“hello world”,150,150);
}
}
23
welcome.jsp
<jsp:plugin type="applet code="MyApplet.class" codebase="."/>
</jsp:plugin>
Example:
MyApplet.java
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{ g.drawString(“hello world”,150,150);
}
}
welcome.jsp
<jsp:plugin type="applet code="MyApplet.class" codebase=".">
</jsp:plugin>
24