Unit-4 JSP - Notes - WT
Unit-4 JSP - Notes - WT
Unit-4 JSP - Notes - WT
UNIT- 4
JSP
(Java Server Pages)
CONTENT:
UNIT – IV
1|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
UNIT- 4 : JSP
JSP technology is used to create web application just like Servlet technology. It can be thought
of as an extension to Servlet because it provides more functionality than servlet such as
expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.
1) Its extension to Servlet technology will be the very first reason to learn JSP. In JSP, we can
use all the functionality of Servlet. In addition, speech-language, predefined tags, implicit
entities and custom tags can be used in JSP, making it easier for JSP to create.
2) The second reason would be that there is no need to redeploy and recompile the project in
case the JSP page is modified. If we have to modify the look and sound of the programme, the
Servlet code has to be revised and recompiled.
3) Third would be about how easy JSP is to maintain and manage as we can conveniently
separate the presentation and business logic.
2|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
4) In JSP, we can use several tags which reduce the code, such as action tags, JSTL, custom
tags, etc. We may, in addition, use EL, implied objects, etc.
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP.
In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in
JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In Servlet technology, we mix our business logic with the presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code.
Moreover, we can use EL, implicit objects, etc.
3|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
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 the web server which is responsible for translating the
JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted
into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later
like initialization, committing response to the browser and destroy.
index.jsp
Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
4|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
JSP Declaration
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
5|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>
The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as well
not methods. as methods.
The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.
JSP directives
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.
6|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
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.
1. <html>
2. <body>
3. <%@ include file="header.html" %>
4. Today is: <%= java.util.Calendar.getInstance().getTime() %>
5. </body>
7|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
6. </html>
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.
1. <html>
2. <body>
3. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
4. <mytag:currentDate/>
5. </body>
6. </html>
Expressions in JSP
The expression tag is used to evaluate Java's expression within the JSP, which then converts the result
into a string and forwards the result back to the client browser via the response object. Essentially, it
is implemented for printing the result to the client (browser). An expression tag can hold any java
language expression that can be employed as an argument to the out.print() method.
8|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
This is how the JSP container sees this when it encounters the above expression:
<%= (6*4) %>
out.print((6*4));
Example :
<!DOCTYPE html>
<html>
<head>
<title>Expression Tag in JSP</title>
</head>
<% int rollNo = 02; %>
<body>
The next roll number is: <%= ++rollNo %>
</body>
</html>
Example:
<!DOCTYPE html>
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<% int g = 60; int k = 40; int r = 20; %>
<%= g+k+r %>
</body>
</html>
Example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>GeeksforGeeks</title>
</head>
<body>
<% out.println("Hello guys do some addition "); %> <!-- Sriptlet Tag-->
<% int n1=10; int n2=30; %><!-- Sriptlet Tag-->
<% out.println("<br>sum of n1 and n2 is "); %> <!-- Sriptlet Tag-->
<%= n1+n2 %> <!-- Expression tag -->
</body>
9|P a ge
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
</html>
Snippet is a programming term for a small region of re-usable source code, machine code,
or text. Ordinarily, these are formally defined operative units to incorporate into
larger programming modules. Snippet management is a feature of some text editors,
program source code editors, IDEs, and related software.
Also, how do you use code snippets? With a code file open in the editor, choose Snippets >
Insert Snippet from the right-click menu, then My Code Snippets. You should see
a snippet named Square Root. Double-click it. The snippet code is inserted in the code file.
A snippet is a small section of text or source code that can be inserted into the code of a
program or Web page. Snippets used in software programming often contain one or more
functions written in C, Java, or another programming language.
Code snippets. A code snippet is boilerplate code which is code that can be used without
changing it. When a candidate writes code, it is evaluated using input (STDIN)
and output (STDOUT). STDIN: The default source of providing input to any computer
program.
2. response:
This is the object of HttpServletResponse class associated with the
response to the client.
10 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
3. config: This is the object of ServletConfig class associated with the page.
7. page object: The manner we use the keyword this for current object, page
object is used to refer to the current translated servlet class.
8. exception: The exception object represents all errors and exceptions which
is accessed by the respective jsp. The exception implicit object is of
type java.lang.Throwable.
9. out: This is the PrintWriter object where methods like print and println
help for displaying the content to the client.
Request Object:
A request object is an implicit object that is used to request an implicit object, which
is to receive data on a JSP page, which has been submitted by the user on the
previous JSP/HTML page.
The request implicit object used in Java is an instance of
a javax.servlet.http.HttpServletRequest interface where a client requests a page
every time the JSP engine has to create a new object for characterizing that request.
The container creates it for every request.
It is used to request information such as parameters, header information, server
names, cookies, and HTTP methods.
It uses the getParameter() method to access the request parameter.
Here is an example of a JSP request implicit object where a user submits login information,
and another JSP page receives it for processing:
11 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
Html file:
<!DOCTYPE html>
<html>
<head>
<title>Please insert a User name and a password</title>
</head>
<body>
<form action="login.jsp">
Please insert Username: <input type="text" name="u_name" /> <br />
Please insert Password: <input type="text" name="passwd" /> <br />
<input type="submit" value="Submit Details" />
</form>
</body>
</html>
Login.jsp file
Html page
pageEncoding="UTF-8"%>
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
12 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
</head>
<body>
<%
String name=request.getParameter("username");
%>
</body>
</html>
In JSP the response object is implicitly defined, so you don’t have to create an
object. JSP response object is created by the web container for each request of the
client. It basically is used for redirecting to any other resource.
In the below example we use the response object to send the user on Geeksforgeeks
homepage.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GeeksforGeeks</title>
</head>
<body>
<%
//below line in JSP redirect you to geeksforgeeks page
response.sendRedirect("geeksforgeeks.org");
%>
</body>
</html>
Out object
An out object is an implicit object for writing data to the buffer and sending output as
a response to the client's browser.
The out implicit object is an instance of a javax.servlet.jsp.jspWriter class.
You will learn more about the various concepts of the out Object in subsequent
chapters.
Example (HTML file):
<!DOCTYPE html>
<html>
13 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
<head>
<title>Please insert a User name and a password</title>
</head>
<body>
<% out.println("Today's date-time: "+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
Session object
A session object is the most commonly used implicit object implemented to store user
data to make it available on other JSP pages until the user's session is active.
The session implicit object is an instance of
a javax.servlet.http.HttpSession interface.
This session object has different session methods to manage data within the session
scope.
You will learn more about the use of the session in subsequent chapters.
exception object
<!DOCTYPE html>
<html>
<head>
<title>Enter two Integers for Division</title>
</head>
<body>
<form action="submit.jsp">
Insert first Integer: <input type="text" name="numone" /><br />
Insert second Integer: <input type="text" name="numtwo" /><br />
<input type="submit" value="Get Results" />
</form>
</body>
</html>
14 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
Submit.jsp file
<%
String num1 = request.getParameter("numone");
String num2 = request.getParameter("numtwo");
int var1= Integer.parseInt(num1);
int var2= Integer.parseInt(num2);
int r= var1 / var2;
out.print("Output is: "+ r);
%>
Exception.jsp
<%
out.print("Error Message : ");
out.print(exception.getMessage());
%>
15 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
getPropertyName()
1
For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.
setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will
have only a setPropertyName() method.
JavaBeans Example
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
16 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
}
}
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a
scripting variable that can be accessed by both scripting elements and other custom tags used
in the JSP. The full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on
your requirement. The value of the id attribute may be any value as a long as it is a unique
name among other useBean declarations in the same JSP.
Following example shows how to use the useBean action −
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the
get methods and the <jsp:setProperty/> action to access the set methods. Here is the full
syntax −
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope">
<jsp:setProperty name = "bean's id" property = "property name"
value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
...........
</jsp:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property attribute is the name of the get or the set methods that should
be invoked.
17 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed –
Student Age: 10
18 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
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 as the browser at times does not support a cookie. It is not
recommended to use this procedure to maintain the sessions.
URL Rewriting
You can append some extra data at the end of each URL. This data identifies the session; the
server can associate that session identifier with the data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session
identifier is attached as sessionid = 12345 which can be accessed at the web server to identify
the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they
don't support cookies. The drawback here is that you will have to generate every URL
dynamically to assign a session ID though page is a simple static HTML page.
The session Object
Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession
Interface. This interface provides a way to identify a user across.
19 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated
for each new client automatically. Disabling session tracking requires explicitly turning it off
by setting the page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the
implicit session object. Since session object is already provided to the JSP programmer, the
programmer can immediately begin storing and retrieving data from the object without any
initialization or getSession().
Here is a summary of important methods available through the session object −
20 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
21 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
</body>
</html>
Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once
you run the URL, you will receive the following result −
Welcome to my website
Session Information
22 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
Id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 0
Now try to run the same JSP for the second time, you will receive the following result.
Id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 1
23 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
Log the user out − The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
web.xml Configuration − If you are using Tomcat, apart from the above mentioned
methods, you can configure the session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session
in seconds. So if your session is configured in web.xml for 15
minutes, getMaxInactiveInterval( ) returns 900.
Create Table
To create the Employees table in the EMP database, use the following steps −
Step 1
Open a Command Prompt and change to the installation directory as follows −
C:\>
C:\>cd Program Files\MySQL\bin
C:\Program Files\MySQL\bin>
Step 2
Login to the database as follows −
C:\Program Files\MySQL\bin>mysql -u root -p
Enter password: ********
mysql>
24 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
Step 3
Create the Employee table in the TEST database as follows − −
mysql> use TEST;
mysql> create table Employees
(
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>
mysql>
SELECT Operation
Following example shows how we can execute the SQL SELECT statement using JTSL in
JSP programming −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
25 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
<html>
<head>
<title>SELECT Operation</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>
</body>
</html>
26 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
INSERT Operation
Following example shows how we can execute the SQL INSERT statement using JTSL in
JSP programming −
<%@ page import = "java.io.*,java.util.*,java.sql.*"%>
<%@ page import = "javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix = "c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix = "sql"%>
<html>
<head>
<title>JINSERT Operation</title>
</head>
<body>
<sql:setDataSource var = "snapshot" driver = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost/TEST"
user = "root" password = "pass123"/>
<sql:update dataSource = "${snapshot}" var = "result">
INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
</sql:update>
27 | P a g e
Dept of CSE R.Satheesh, Asst.Prof
Web Technologies Unit-4
</body>
</html>
Access the above JSP, the following result will be displayed −
28 | P a g e
Dept of CSE R.Satheesh, Asst.Prof