JSP (Java Server Pages)
JSP (Java Server Pages)
⮚It helps to insert java code in HTML pages by making use of special JSP tags.
⮚JSP is a server-side program that is similar in design and functionality to java servlet.
Servlet plays a controller role in MVC approach. JSP is the view in MVC approach for showing output.
Servlet can accept all protocol requests. JSP only accept http requests.
In Servlet, we can override the service() method. In JSP, we cannot override its service() method.
In Servlet, we have to implement everything like business In JSP business logic is separated from presentation logic
logic and presentation logic in just one servlet file. by using javaBeans.
Modification in Servlet is a time consuming task because it JSP modification is fast, just need to click the refresh
includes reloading, recompiling and restarting the server. button.
ADVANTAGES OF JSP OVER SERVLETS
⮚JSP needs no compilation. There is automatic deployment of a JSP, recompilation is done
automatically when changes are made to JSP pages.
⮚In a JSP page visual content and logic are separated, which is not possible in a servlet.
⮚i.e. JSP separates business logic from the presentation logic.
⮚Servlets use “println” statements for printing an HTML document which is usually very
difficult to use. JSP has no such tedious task to maintain.
LIFE CYCLE OF JSP
⮚JSP Life Cycle is defined as translation of JSP Page into servlet as a JSP Page needs to be
converted into servlet first in order to process the service requests. The Life Cycle starts
with the creation of JSP and ends with the destruction phase.
⮚Following steps are involved in the JSP life cycle:
2. The webserver checks if a compiled version of the JSP page already exists.
3. If the JSP page's compiled version does not exist, the file is sent to the JSP
Servlet engine, which converts it into servlet content (with .java extension). This
process is known as translation.
4. The web container automatically translates the JSP page into a servlet. So as a
developer, you don't have to worry about converting it manually.
COMPILATION PHASE
1. In case the JSP page was not compiled previously or at any point in time, then the
JSP page is compiled by the JSP engine.
2. In this compilation phase, the Translated .java file of the servlet is compiled
into the Java servlet .class file.
INITIALIZATION PHASE
In this Initialization phase: Here, the container will:
2. Create instance.
This initialization is done only once with the servlet's init method where database
connection, opening files, and creating lookup tables are done.
2. As the requested JSP page is loaded and initiated, the JSP engine has to invoke
the _jspService() method.
3. This method is invoked as per the requests, responsible for generating responses
for the associated requests, and responsible for all HTTP methods.
2. The jspDestroy() method is invoked. You can incorporate and write cleanup codes inside this
method for releasing database connections or closing any file.
2. The server will determine the JAVA code using script tags as an indicator at the start
and end of code. These scripting tags are called scripting elements.
iv. Directive
v. Comment
SCRIPTLET TAG
1. A scriptlet tag is used to insert java source code in JSP.
2. The statement which is written will be moved to _jspservice() using JSP container
while generating servlet from JSP.
3. When client make a request, JSP service method is invoked and after that the content
which is written inside the scriptlet tag executes.
4. Syntax is as follows:
<% java source code %>
<html>
<body>
<% out.println(“Hello World"); %> <!-- scriptlet tag -->
</body>
</html>
EXPRESSION TAG
1. Expression Tag in JSP is used for writing your content on client side. We can use this
tag for displaying information on client browser.
<html>
<body>
out.print((5*5));
<%= 5*5 %> <!-- Expression tag -->
</body>
</html>
DECLARATION TAG
1. This tag is used for declaration of the variables, methods and classes.
2. The declaration of jsp declaration tag is placed outside the _jspService() method.
3. Syntax :
<%! inside this tag we can initialize our variables, methods and classes %>
4. Example:
2. This JSP comment tag tells the JSP container to ignore the comment part from
compilation.
<% -- JSP Comments --%>
DIRECTIVE TAGS
1. The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.
🢝 include directive
🢝 taglib directive
import: This tells the container what packages/classes are needed to be imported into the
program.
Syntax:
<%=d%>
contentType: This defines the format of data that is being exchanged between the client
and the server. It does the same thing as the setContentType method in servlet used to.
<%@page contentType="value"%>
<%-- JSP code to demonstrate how to use page directive to set the type of content --%>
buffer The buffer attribute sets the buffer size in kb to handle output generated by the
JSP page.
The default size of the buffer is 8Kb.
<%@ page buffer="16kb" %>
language The language attribute specifies the scripting language used in the JSP page.
The default value is "java".
<%@ page language="java" %>
autoFlush The autoFlush attribute specifies whether buffered output should be flushed
automatically when the buffer is filled. Bydefault it is true.
<%@ page autoFlush="true" %>
Attributes Description
errorPage It is used to define the error page, if exception occurs in the current page, it will
be redirected to the error page.
<%@ page errorPage="myerrorpage.jsp" %>
isErrorPage It classifies whether the page is an error page or not. By classifying a page as an error
page, it can use the implicit object ‘exception’ which can be used to display exceptions
that have occured.
<%@ page isErrorPage="true" %>
INCLUDE DIRECTIVE
1. JSP include directive is used to include other files into the current jsp page. These
files can be html files, other sp files etc. The advantage of using an include
directive is that it allows code re-usability.
2. They are being created inside service method so we can directly use them
within Scriptlet without initializing and declaring them.
out javax.servlet.jsp.JspWriter. This is the PrintWriter object where methods like print and println
help for displaying the content to the client.
request javax.servlet.http.HttpServletRequest. This is the object of HttpServletRequest class associated
with the request.
response javax.servlet.http.HttpServletResponse. This is the object of HttpServletResponse class
associated with the response to the client.
session javax.servlet.http.HttpSession. It is most frequently used implicit object, which is used for
storing the user’s data to make it available on other JSP pages till the user session is active.
application javax.servlet.ServletContext. This is used for getting application-wide initialization parameters
and to maintain useful data across whole JSP application.
exception javax.servlet.jsp.JspException. Exception implicit object is used in exception handling for
displaying the error messages.
page java.lang.Object
pageContext javax.servlet.jsp.PageContext. It is used for accessing page, request, application and session
attributes.
config javax.servlet.ServletConfig. This is the object of ServletConfig class associated with the page.
This is mainly used for accessing getting configuration information such as servlet context, servlet
name, configuration parameters etc.
IMPLICIT OBJECT : OUT
Servlet
PrintWriter out= response.getWriter();
response.setContentType(“text/html”);
out.print(“hello”);
JSP
<html>
<body>
<% out.print(“hello”); %>
</body>
</html>
IMPLICIT OBJECT : REQUEST
• Instance of javax.servlet.http.HttpServletRequest object associated with the request.
• Each time a client requests a page the JSP engine creates a new object to represent that
request.
• The request object provides methods to get HTTP header information including from data,
cookies, HTTP methods etc.
Resquest.html
1 <form action=”Welcome.jsp">
2 Login:<input type="text" name="login">
3 <input type="submit" value="next">
4 </form>
Welcome.jsp
1 hello,
2 <%
3 out.println(request.getParameter("login"));
4 %>
IMPLICIT OBJECT : REQUEST
• The response object is an instance of a
javax.servlet.http.HttpServletResponse object.
• Through this object the JSP programmer can add new cookies or date stamps,
HTTP status codes, redirect response to another resource, send error etc.
Response.html
1 <form action="welcome.jsp">
2 <input type="text" name="login">
3 <input type="submit" value="next">
4 </form>
Welcome.jsp
1 <%
2 response.sendRedirect("www.darshan.ac.in");
3 %>
IMPLICIT OBJECT : SESSION
• In JSP, session is an implicit object of type javax.servlet.http.HttpSession .
• The Java developer can use this object to set, get or remove attribute or to get
session information.
MySession.html
1 <form action="MySession1.jsp">
2 <input type="text" name="uname">
3 <input type="submit" value="go"><br/>
4 </form>
IMPLICIT OBJECT : SESSION
MySession1.jsp
1 <html>
2 <body>
3 <%
4 String name=request.getParameter("uname");
5 out.print("Welcome "+name);
6 session.setAttribute("user",name);
7 %>
8 <a href="MySession2.jsp">next page</a>
9 </body>
10 </html>
MySession2.jsp
1 <html>
2 <body>
3 <%
4 String name = (String)session.getAttribute("user");
5 out.print("Hello "+name);
6 %>
7 </body>
8 </html>
IMPLICIT OBJECT : EXCEPTION
Index.jsp
1 <form action="process.jsp">
2 No1:<input type="text" name="n1" /><br/><br/>
3 No1:<input type="text" name="n2" /><br/><br/>
4 <input type="submit" value="divide"/>
5
</form>
6
process.jsp
1 <%@ page errorPage="error.jsp" %>
2 <%
3 String num1=request.getParameter("n1");
4
String num2=request.getParameter("n2");
5
6 int a=Integer.parseInt(num1);
7 int b=Integer.parseInt(num2);
8 int c=a/b;
9 out.print("division of numbers is: "+c);
10 %>
IMPLICIT OBJECT : EXCEPTION
error.jsp
1 <%@ page isErrorPage="true" %>
2
3 <h3>Sorry an exception occured!</h3>
4
5
6 Exception is: <%= exception %>
IMPLICIT OBJECT : EXCEPTION
What is Form processing in JSP?
➔ Forms are the common method in
web processing. We need to send
information to the web server and that
information.
➔ The browser uses two methods to
pass this information to the web
server. These are the GET Method
and POST Method.
GET Method
➔ The GET method is the default method to send information from the browser to the
webserver.
➔ It sends the user information to the page request separated by the ? character.
➔ Example: http://www.abc.com/helloworld?key1=v1&key2=v2
➔ It is not suggested to use the GET method if you have some sensitive information or
password to pass to the server because it produces a long string that appears in your
browser's address bar.
➔ Because of the size limitation, we can only send 1024 characters in the request.
POST Method
➔ The POST method is a generally more reliable method of passing information to a back-
end program.
➔ This method packages the information exactly as the GET method, but instead of sending
it as a text form after a ? in the URL, it sends it as a separate message.
➔ This message comes to the backend program in the form of the standard input, which you
can parse and use for your processing.
Form Processing in JSP is handled using
getParameterValues() This method returns multiple values if the specified parameter appears more
than once and returns multiple values.
getParameterNames() It is used to get the name of parameters if you want a complete list of all
parameters in the current request.
getParameter() It is used to get the value of a form parameter.
getInputStream() It is used to read binary data streams coming from the client.
GET Method using the form
➔ In this example, we have two files:
➔ One is our Form(index.html) that takes the input data, and the other is our JSP
file(main.jsp) that reads and processes. Inside our form, we have two fields, “First Name”
and “Last Name” with a submit button through which we will process the action to
another JSP page. We will fetch the input using the getParameter method. With the help
of submit button, we will pass the field values into the main.jsp page.
index.html
POST Method using the form in JSP
JSP ACTION TAGS
1. They perform some specific tasks and are predefined. They provide
functionalities like-
i. Dynamic insertion of a file
1. Directives are used during translation phase used to include the static resources
e.g. HTML files, images, and CSS, etc, while actions are used during request
processing phase (Run Time) used to include more dynamic resources e.g. JSP or
Servlet.
2. Unlike Directives, each time a page is visited, if it contains actions then those
actions get re-evaluated.
jsp:param sets the parameter value. It is used in forward and include mostly.
display.jsp
1 <html>
2 <head>
3 <title>Display Page</title>
4 </head>
5 <body>
6 Hello this is a display.jsp Page
7 </body>
8 </html>
<JSP:INCLUDE>
1. The jsp:include action tag is used to include the content of another resource it may
be jsp, html or servlet.
2. The jsp:include tag can be used to include static as well as dynamic pages.
Attribute Description
page The relative URL of the page to be included.
flush The boolean attribute determines whether the included resource has its
buffer flushed before it is included. By default value is false.
Syntax
<jsp:include page="relative URL" flush="true" />
Example
<jsp:include page="Action.jsp" flush="true">
<jsp:param name="roll_no" value="01" />
</jsp:include>
EXPRESSION LANGUAGE (EL)
SCRIPTING
▪Expression language (EL) has been introduced in JSP 2.0.
▪ It is a simplified language that is used to access and manipulate data within JSP pages
also it provides a convenient way to access the data stored in objects like requests,
sessions, applications, JavaBeans, etc.
▪ EL includes arithmetic, relational and logical operators too.
▪ The purpose of EL is to produce script less JSP pages.
▪ Syntax of EL :
EL OUTPUT
${a=10} 10
$(expression) ${10+20} 30
whatever is present inside braces gets ${20*2} 40
evaluated at runtime and being sent ${10==20} false
to the output stream. ${'a'<'b'} true
EXPRESSION LANGUAGE (EL)
SCRIPTING
▪If we have an object request and we want to retrieve data from this object, so for
this-
🢝 we use request.getParameter() says we have an object session
🢝 If we want to retrieve data from the session, then we will use the session.getAttribute() but this
would require extra code.
🢝 Syntax of EL :
$(expression)
EL IMPLICIT OBJECTS
Implicit Object Usage
pageScope It maps the given attribute name with the value set in the page scope
requestScope It maps the given attribute name with the value set in the request scope
sessionScope It maps the given attribute name with the value set in the session scope
applicationScope It maps the given attribute name with the value set in the application scope
<form action=“displayEL.jsp">
Student Name:<input type="text" name=“stdname">
Roll Number :<input type="text" name="rollno">
<input type="submit” value=“Submit Details">
</form>
EL IMPLICIT EXAMPLE
displayEL.jsp
<body>
Student Name is: ${ param.stdname } <br>
Student Roll No is : ${ param.rollno }
</body>
EL IMPLICIT EXAMPLE
indexEL.jsp
<form action="EL2.jsp">
<% Cookie ck=new Cookie("c1","abc");
response.addCookie(ck);
session.setAttribute("sid","054"); //for session
%>
Enter Name:<input type="text" name="name" >
Enter Address:<input type="text" name="address" >
<input type="submit" value="submit">
</form>
displayEL.jsp
<p>Name is : ${param.name}</p>
<p>Address is :${param.address}</p>
<p>Cookie Name : ${cookie.c1.name}</p>
<p>Cookie value : ${cookie.c1.value}</p>
<p>Session id : ${sessionScope.sid}</p>
EL IMPLICIT EXAMPLE
indexEL.jsp displayEL.jsp
JSP EL OPERATOR
▪JSP EL Arithmetic Operators
▪Arithmetic operators are provided for simple calculations in EL expressions. They are +, -, *, / or div, %
or mod.
▪ JSP EL implicit objects are different from JSP implicit objects except pageContext.
▪ JSP EL is NULL friendly, if given attribute is not found or expression returns null, it
doesn’t throw any exception.
JSTL (JSP STANDARD TAG LIBRARY)
⮚JSTL stands for JSP Standard Tag Library.
▪Advantages of JSTL
🢝 Fast Development: JSTL provides many tags that simplifies the JSP.
Note: For creating JSTL application, you need to load jstl.jar file.
JSTL TAGS
Tag Name Function URI Prefix
▪ The syntax used for including JSTL core library in your JSP is:
JSTL CORE TAG LIST
Tags Description
c:out It display the result of an expression, similar to the way <%=...%> tag work.
c:import It Retrives relative or an absolute URL and display the contents to either a String in 'var',a Reader in 'varReader' or the page.
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, It is the simple conditional tag that includes its body content if the evaluated condition is true.
c:when,
c:otherwise
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.
c:url It creates a URL with optional query parameters.
<C:OUT>
<%@index.jsp
taglib uri= "http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<c:out value="${'Welcome to JSTL'}"/>
</body>
</html>
<C:SET>
JSTL FUNCTION TAGS
▪The JSTL function provides a number of standard functions, most of these functions are
common string manipulation functions.
▪ The syntax used for including JSTL function library in your JSP is:
JSTL FUNCTION TAGS
JSTL Functions Description
fn:contains() It is used to test if an input string containing the specified substring in a program.
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case insensitive way.
fn:endsWith() It is used to test if an input string ends with the specified suffix.
fn:trim() It removes the blank spaces from both the ends of a string.
fn:startsWith() It is used for checking whether the given string is started with a particular string value.
fn:substring() It returns the subset of a string according to the given start and end position.
fn:length() It returns the number of characters inside a string, or the number of items in a collection.
fn:replace() It replaces all the occurrence of a string with another string sequence.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>Function-Contains</title>
</head>
<body>
<h1>
<c:set var="name" value="Hello i am Jstl function tag"/>
${fn:contains(name,'function')}
</h1>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>Function-endsWith</title>
</head>
<body>
<c:set var="name" value="ssit near bhat"/>
${fn:endsWith(name,'ssit')}
</body>
</html>
JSTL SQL TAGS
❏ SQL tags in JSTL are used to communicate with a relational database to perform
various database operations.
❏ The syntax used for including JSTL SQL tags library in your JSP is:
sql:setDataSource It is used for creating a simple data source suitable only for prototyping.
sql:query It is used for executing the SQL query defined in its sql attribute or the body.
sql:update It is used for executing the SQL update defined in its sql attribute or in the tag body.
sql:param It is used for sets the parameter in an SQL statement to the specified value.
sql:dateParam It is used for sets the parameter in an SQL statement to a specified java.util.Date value.
sql:transaction It is used to provide the nested database action with a common connection.
sql:setDataSource
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>sql:setDataSource Tag</title>
</head>
<body>
url="jdbc:mysql://localhost/test"
user="root" password="1234"/>
</body>
</html>
sql:query
<html>
<head>
<title>Select</title>
</head>
<body>
user="root" password="root"/>
${student.Student_Id} ${student.Student_Name}<br>
</c:forEach>
</body>
JSTL-XML tag library
▪In JSTL, XML tags are used for creating and manipulating xml documents.
▪ The following syntax represent the URL of XML tag: -
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
▪To utilize the functionality of XML tags, it is required to download and add two jar files within
the lib directory of your project.Following are the required jar files: -
🢝 XercesImpl.jar
🢝 xalan.jar
JSTL-XML tag library
XML TAGS DESCRIPTION
x:out Similar to <%= ... > tag, but for XPath expressions.
x:parse It is used for parse the XML data specified either in the tag body or an attribute.
x:choose It is a conditional tag that establish a context for mutually exclusive conditional operations.
x:when It is a subtag of that will include its body if the condition evaluated be 'true'.
x:otherwise It is subtag of that follows tags and runs only if all the prior conditions evaluated be 'false'.
x:if It is used for evaluating the test XPath expression and if it is true, it will processes its body content.
x:transform It is used in a XML document for providing the XSL(Extensible Stylesheet Language)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<head>
<title>Tutorial and Example</title>
</head>
<body>
<h2>JSTL XML Tag Demo </h2>
<c:set var="website">
<website>
<name>Tutorial and Example</name>
<tutorial>Java Server Pages</tutorial>
</website>
</c:set>
<x:parse xml="${website}" var="output"/>
<b>Website :: </b>
<x:out select="$output/website[1]/name" /><br>
<b>Tutorial ::</b>
<x:out select="$output/website[1]/tutorial" />
</body>