Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit - V Java Server Pages Final

Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

JSP:= 1> server side technology

2>used to creating web application


3>create dynamic web content
4> JSP tags are used to insert JAVA code into HTML pages.
5>advanced version of Servlet Technology.
6>Web based technology helps us to create dynamic and platform independent web pages.
7>Java code can be inserted in HTML/ XML pages or both.
Unit - V
8>JSP is first converted into servlet by JSP container before processing the client’s request.

Java Server Pages

 JSP :-
 It stands for Java Server Pages.
 It is a server side technology.
 It is used for creating web application.
 It is used to create dynamic web content.
 In this JSP tags are used to insert JAVA code into HTML pages.
 It is an advanced version of Servlet Technology.
 It is a Web based technology helps us to create dynamic and platform independent web
pages.
 In this, Java code can be inserted in HTML/ XML pages or both.
 JSP is first converted into servlet by JSP container before processing the client’s request.

 What is JSP LifeCycle?


 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 disintegration of that.
 Let’s learn different phases of JSP Life Cycle
When the browser asks for a JSP, JSP engine first checks whether it needs to compile the page.
If the JSP is last compiled or the recent modification is done in JSP, then the JSP engine
compiles the page.
Compilation process of JSP page involves three steps:
 Parsing of JSP
 Turning JSP into servlet
 Compiling the servlet
JSP Lifecycle is depicted in the below diagram.

WHAT IS JSP LIFECYCLE:=


1> translation of JSP Page into servlet as a JSP Page needs to be converted into servlet first in order to process
the service requests
2>creation of JSP and ends with the disintegration of that
3>
Parsing of JSP
Turning JSP into servlet
Compiling the servlet

Page 1 Prof. Patil R. M


Page 2 Prof. Patil R. M
Following steps explain the JSP life cycle:
1. Translation of JSP page
2. Compilation of JSP page(Compilation of JSP page into _jsp.java)
3. Classloading (_jsp.java is converted to class file _jsp.class)
4. Instantiation(Object of generated servlet is created)
5. Initialisation(_jspinit() method is invoked by container)
6. Request Processing(_jspservice() method is invoked by the container)
7. Destroy (_jspDestroy() method invoked by the container)

Detailed summary on the above points:


1. Translation of the JSP Page:
 A Java servlet file is generated from a JSP source file. This is the first step of JSP life cycle.
In translation phase, container validates the syntactic correctness of JSP page and tag files.

Page 3 Prof. Patil R. M


 The JSP container interprets the standard directives and actions, and the custom actions
referencing tag libraries used in this JSP page.
 In the above pictorial description, demo.jsp is translated to demo_jsp.java in the first step.
 Let’s take an example of “demo.jsp” as shown below:

Demo.jsp
<html>
<head>
<title>Demo JSP</title>
</head>
<%
int demvar=0;%>
<body>
Count is:
<% Out.println(demovar++); %>
<body>
</html>

Demo JSP Page is converted into demo_jsp servlet in the below code.

Output:

 Here you can see that in the screenshot theOutput is 1 because demvar is initialized to 0 and
then incremented to 0+1=1

In the above example,

Page 4 Prof. Patil R. M


 demo.jsp, is a JSP where one variable is initialized and incremented. This JSP is converted to
the servlet (demo_jsp.class ) wherein the JSP engine loads the JSP Page and converts to servlet
content.
 When the conversion happens all template text is converted to println() statements and all JSP
elements are converted to Java code.
This is how a simple JSP page is translated into a servlet class.

2. Compilation of the JSP Page :-


 The generated java servlet file is compiled into java servlet class
 The translation of java source page to its implementation class can happen at any time between
the deployment of JSP page into the container and processing of the JSP page.
 In the above pictorial description demo_jsp.java is compiled to a class file demo_jsp.class

3. Classloading :-
 Servlet class that has been loaded from JSP source is now loaded into the container.

4. Instantiation :-
 In this step the object i.e. the instance of the class is generated.
 The container manages one or more instances of this class in the response to requests and other
events. Typically, a JSP container is built using a servlet container. A JSP container is an
extension of servlet container as both the container support JSP and servlet.
 A JSPPage interface which is provided by container provides init() and destroy () methods.
 There is an interface HttpJSPPage which serves HTTP requests, and it also contains the service
method.

5. Initialization :-
public void jspInit()
{
//initializing the code
}
 _jspinit() method will initiate the servlet instance which was generated from JSP and will be
invoked by the container in this phase.
 Once the instance gets created, init method will be invoked immediately after that
 It is only called once during a JSP life cycle, the method for initialization is declared as shown
above

6. Request processing :-
void _jspservice(HttpServletRequest request HttpServletResponse
response)
Page 5 Prof. Patil R. M
{
//handling all request and responses
}
 _jspservice() method is invoked by the container for all the requests raised by the JSP page
during its life cycle
 For this phase, it has to go through all the above phases and then only service method can be
invoked.
 It passes request and response objects
 This method cannot be overridden
 The method is shown above: It is responsible for generating of all HTTP methods i.e. GET,
POST, etc.

7. Destroy:-
public void _jspdestroy()
{
//all clean up code
}

 _jspdestroy() method is also invoked by the container.


 This method is called when container decides it no longer needs the servlet instance to service
requests.
 When the call to destroy method is made then, the servlet is ready for a garbage collection.
 This is the end of the life cycle.
 We can override jspdestroy() method when we perform any cleanup such as releasing database
connections or closing open files.

First Program:-
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2> First Programm </h2>
</body>
</html>

Page 6 Prof. Patil R. M


 JSP Elements – Declaration, Syntax & Expression

1) JSP Declarations :-
 It is often wont to provide all the java declarations like variable declarations, method
definitions. Classes declarations and so on.
 A declaration can consist of either method declarations or variables, static constants are a good
example of what to put in a declaration.
 The JSP you write turns into a category definition. All the scriptlets you write are placed inside
one method of this class. You can also add variable and method declarations to the present
class.
 You can then use these variables and methods from your scriptlets and expressions. We can use
declarations to declare one or more variables and methods at the category level of the compiled
servlet.
 The fact that they are declared at a class level rather than in the body of the page is significant.
The class members (variables and methods) can then be employed by Java code within the
remainder of the page.
 When you write a declaration during a JSP page, remember these rules:
1. Must end the declaration with a semicolon.
2. <% int i=0;%>
3. We can use variables or methods that are declared in packages imported by the page directive,
without declaring them in a declaration element.
4. We can declare any number of variables or methods within one declaration element, as long as
you end each declaration with a semicolon. The declaration must be valid in the Java
programming language.

If we offer any java declarations by using-declaration scripting element then that each one java
declarations are going to be available to the translated servlet as class-level declarations.

JSP Declarations Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Declaration</title>
</head>
<body>
<h3>--Welcome--</h3>
Page 7 Prof. Patil R. M
<h3>Use of Declaration in JSP</h3>
<%!int num1 = 2, num2 = 3, n = 0;%>
<%
n = num1 + num2 + 1;
out.println("The number after adding declared variables is " + n);
%>
</body>
</html>

Output

The code placed in the declaration tag goes to JES class outside of the _jspService(_,_) method.
Variables declared in the declaration tag becomes global variables in JES class. Variables declared in
the declaration tag become a global variable in JES class. Implicit objects are not visible in the
declaration tag because they are the local variable of _jspService(_,_) method, and the code placed in
the declaration tag goes to the outside _jspService(_,_) method. We can also use declaration tag to
place jspInit() and jspDestroy() method definition in our JSP program.
Note: The XML equivalent of <%! Code %> is:
<jsp:declaration>
Code
</jsp:declaration>

2) JSP Scriptlets:-
This scripting element is often wont to provide a block of java code. It can contain any number of
language statements, variable or method declarations, or expressions that are valid within the page
scripting language. Within a scriptlet, you can do the following:
1. On the JSP page declare variables or methods to use later.
2. Write valid expressions in the page scripting language.
3. Use any of the implicit objects or any object declared with the element.
4. On the JSP page, write any other statement valid in the scripting language used.
5. All text, HTML tags, or JSP elements you write must be outside the scriptlet.

Page 8 Prof. Patil R. M


If we offer any block of java code by using scriptlets then that code is going to be available to
translated servlet inside _jspService(_,_) method. The code placed in scriptlet goes to _jspService(_,_)
of JES class as it is. This code is useful as request processing logic to process the request. Variables
declared in scriptlet becomes a local variable of _jspService(_,_). All implicit objects of JSPs are local
variables of _jspService(_,_) method, and the code of scriptlet also goes _jspService(_,_). So, we can
use implicit objects in Scriptlets. We cannot place method definitions in JSP because they become the
nested method of _jspService(_,_) and java does not support nested methods.

JSP Scriptlets Example:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Scriptlets</title>
</head>
<body>
<h3>--Welcome--</h3>
<h3>Use of scriptlet in JSP</h3>
<%
int a = 3;
int b = 4;
int c = 5;
out.println("a is: " + a + "<br>" + "b is:" + b + "<br>" + "c is:" + c + "<br>");
out.println("Multiplication gives: " + a * b * c + "<br>");
out.println("Addition gives:" + (a + b + c));
%>
</body>
</html>

Output

Page 9 Prof. Patil R. M


Scriptlets are executed at request time when the JSP container processes the request. If the scriptlet
produces output, the output is stored within the out object. If you want to use the characters “%>”
inside the scriptlet, enter “%\>” instead.
Note: The XML equivalent of <% Code %> is:
<jsp:scriptlet>
Code
</jsp:scriptlet>

3) JSP Expressions:-
This is scripting element are often wont to evaluate the only java expression and display that
expression resultant value onto the client browser. The expression element contains a Java expression
that returns a worth. This value is then written to the HTML page. The Expression tag can contain any
expression that’s valid consistent with the Java Language Specification. This includes variables,
method calls then return values, or any object that contains a toString() method. It evaluates the given
expression displays generated results onto browser windows. Anything that returns a result is called an
expression.
Syntax: <%=Java Expression%>
If we provide any java expression in expression scripting elements then that expression will be
available to translated servlet inside _JspService(_,_) method as a parameter to out.write() method. If
the expression tag is used perfectly then there is no need of using out.println() on the JSP page. The
code placed in the expression tag goes to the _JspService(_,_) method of JES class, so we can use
implicit objects in expression tags. We can use the expression tag for instantiation and display data of
the object. We can use the expression tag to call both user-defined and pre-defined methods, which
return results. Here, the java expression is evaluated and then converted to String and inserted in the
page. This evaluation is performed at run-time (when the page is requested), and thus has full access to
the information about the request.

JSP Expressions Example:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>

Page 10 Prof. Patil R. M


<body>
Current Time:
<%=java.util.Calendar.getInstance().getTime()%>
</body>
</html>

Output

Note: XML authors can use an alternative syntax for JSP expressions:
<jsp:expression>
Java Expression
</jsp:expression>
The XML elements, unlike HTML ones, are case sensitive. So be sure to use lowercase

 JSP Implicit Objects :-


What are JSP Implicit Objects?
 Implicit Objects are a set of Java objects which the JSP Container makes available to developers on
each page.
 These objects can be accessed as built-in variables via scripting elements. It can also be accessed
programmatically by JavaBeans and Servlets.
 These are created automatically for you within the service method.
 In J2SE applications, for every java developer, it is a common requirement to display data on the
command prompt. To perform this operation every time we have to prepare PrintStream object with
command prompt location as target location:
Printstream ps = new PrintStream(“C:\Program files\…..\cmd.exe”);
ps.println(“Hello”);
 In Java applications, the PrintStream object is a frequent requirement so that java technology has
provided that PrintStream object as a predefined object in the form of out variable in System class.
public static final PrintStream out;
 Similarly, in web applications, all the web developers may require some objects like request, response,
config, context, session, and so on are a frequent requirement, to get these objects we have to write
some piece of java code.
 Once the above-specified objects are a frequent requirement in web applications, JSP technology has
provided them as predefined support in the form of JSP Implicit Objects in order to reduce the burden
on the developers.
 Implicit objects in JSP need not be declared or instantiated by the JSP author. They are automatically
instantiated by the container which is accessed by using standard variables. Hence, they are called
implicit objects.

Page 11 Prof. Patil R. M


 These are parsed by the container and inserted into the generated servlet code. They are only available
within the JSP service method and not in any declaration.

Types of Implicit Objects in JSP:-


For every JSP file when the JSP compiler generates the servlet program it will create the following 9
implicit objects inside the _jspService() method.
1. Request
2. Response
3. PageContext
4. Session
5. Application
6. Config
7. Out
8. Page
9. Exception
Hence all these objects are created and available inside the _jspService() method we can use all these
implicit objects directly inside the JSP scriptlets.

1) Request Object in JSP:-


 It is an instance of javax.servlet.http.HttpServletRequest object.
 This implicit object is used to process the request sent by the client.
 It is the HttpServletRequest object associated with the request.
 When a client requests a page the JSP engine creates a new object to represent that request.

Following are methods of request object:


1. getCookies(): It returns an array containing all of the cookie objects the client sent with this
request.
2. getAttributeNames(): It returns an enumeration containing the names of the attributes available to
this request.
3. getHeaderNames(): It returns an enumeration of all the header names it contains.
4. getParameterNames(): It returns a String object containing the names of the parameters contained
in this request.
5. getSession(): It returns the current session associated with this request.
6. getLocale(): It returns the preferred Locale that the client will accept content in.
7. getInputStream(): It helps us to retrieve the body of the request as binary data using a
ServletInputstream.
8. getAuthType(): It returns the name of the authentication scheme used to protect the servlet.
9. getContentType(): It returns the MIME type of the body of the request.
10. getContextPath(): It returns the portion of the request URI.
Page 12 Prof. Patil R. M
11. getMethod(): It returns the name of the HTTP method with which this request was made.
12. getPathInfo(): It returns extra path information associated with the URL.
13. getProtocol(): It returns the name and version of the protocol the request uses.
14. getQueryString(): It returns the query string that is contained in the requested URL.
15. getRequestedSessionId(): It returns the session ID specified by the client.
16. getServletPath(): It returns the part of the request’s URL that calls the JSP.
17. isSecure(): It returns True or False indicating whether the request was made using a secure channel
or not.
18. getContentLength(): It returns the length of the request body and made available by the input
stream.
19. getServerPort(): It returns the port number on which the request was received.
20. getRemoteAddr(): It returns the IP address of the client that sent the request.

Example of Request Object in JSP


In this example, we are printing the name of the user with a welcome message. Here we are receiving the
input from the user on the index.html page and displaying it in the welcome.jsp page using request implicit
object.
index.html

<!DOCTYPE html>
<html>
<head>
<title>request implicit object</title>
</head>
<body bgcolor="pink">
<form action="welcome.jsp">
<input type="text" name="uname"> <input type="submit"
value="GO"><br />
</form>
</body>
</html>

welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>

Page 13 Prof. Patil R. M


<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
String name = request.getParameter("uname");
out.print("welcome " + name);
%>
</body>
</html>

Output
Run your code to get the following output.

2) Response Object in JSP:-


 This is the HttpServletResponse object associated with the response to the client.
 This implicit object is used to process the request and send the response to the client. We can
send content-type as well as error reports and text.
 The object is by default available to scriptlets and expressions to get response-related
information and to set response-related information.
 If a JSP wants to redirect a request from this server to another server then it can use the
response object and sendRedirect method call.

Page 14 Prof. Patil R. M


Following are the methods of response object:
1. encodeRedirectURL(String url): It is used to encode the specified URL for use in the
sendRedirect method.
2. containsHeader(String name): It returns True or False indicating whether the named response
header has already been set.
3. isCommitted(): It returns True or False indicating if the response has been committed.
4. addCookie(): It is used to add the specified cookie to the response.
5. addHeader(String name, String value): It is used to add a response header with the given
name and value.
6. flushBuffer(): It is used to force any content in the buffer to be written to the client.
7. reset(): It is used to clear the data that exists in the buffer as well as the status code and
headers.
8. sendError(int sc): It is used to send an error response to the client using the specified status
code and clearing the buffer.
9. sendRedirect(String location): It is used to send a temporary redirect response to the client
using the specified redirect location URL.
10. setBufferSize(int size): It is used to set the preferred buffer size for the body of the response.
11. setContentType(int len): It is used to set the length of the content body on the response.
12. setContentType(String type): It is used to set the content type of the response being sent to
the client.
13. setHeader(String name, String value): It is used to set a response header with the given name
and value.
14. setLocale(Locale loc): It is used to set the locale of the response.
15. setStatus(int sc): It is used to set the status code for the response.

Example of Response Object in JSP


In this example, we are redirecting the response to “Google”. Here we are receiving the input from the
user on the index.html page and redirecting it on the welcome.jsp page using response implicit object.
index.html

!DOCTYPE html>
<html>
<head>
<title>implicit object</title>
</head>
<body bgcolor="pink">
<form action="welcome.jsp">
<input type="text" name="uname"> <input type="submit"
value="GO"><br />

Page 15 Prof. Patil R. M


</form>
</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
response.sendRedirect("http://www.google.com");
%>
</body>
</html>

Output
Run your code to get the following output:

Page 16 Prof. Patil R. M


3) PageContext Implicit Object in JSP:
pageContext is an implicit object in JSP Technology, it can be used to get all the JSP implicit
objects even in a Non-JSP environment. It is created for pageContext class which is used for
creating all the implicit variables like a session, ServletConfig, out, etc… While preparing Tag
handler classes in custom tags container will provide pageContext object as part of its life cycle,
from this we are able to get all the implicit objects. In JSP applications, by using the pageContext
object we are able to perform some operations with the attributes in the JSP scopes page,
request, session, and application like adding an attribute, removing an attribute, getting an
attribute, and finding an attribute. This encapsulates the use of server-specific features like higher
performance JSPWriters. The pageContext reference points to pageContext class sub-class
object.
Following are the methods of pageContext object:
1. setAttribute(String name, Object value, int scope): It is used to set an attribute onto a
particular scope. Where scope may be page, request, session, or application.
2. getAttribute(String name): It is used to get an attribute from page scope.
3. getAttribute(String name, int scope): If we want to get an attribute value from the
specified scope we have to use this method.
4. removeAttribute(String name, int scope): It is used to remove an attribute from a
particular scope.
5. findAttribute(String name): To find an attribute value from page scope, request scope,
session scope, and application scope we have to use this method.
Example of PageContext Object in JSP:
In this example, in index.html we are taking user input and storing user’s credentials using
Pagecontext with the session scope is welcome.jsp page. So that we can able to access the
details till the user’s session is active. Then we are fetching the stored attributes using the
getAttribute method on the second.jsp page.
index.html

Page 17 Prof. Patil R. M


<!DOCTYPE html>
<html>
<head>
<title>implicit object</title>
</head>
<body bgcolor="pink">
<form action="welcome.jsp">
<input type="text" name="uname"> <input type="submit"
value="GO"><br />
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
String name = request.getParameter("uname");
out.print("Welcome " + name);
pageContext.setAttribute("user", name, PageContext.SESSION_SCOPE);
%>
<a href="second.jsp">second jsp page</a>
</body>
</html>
second.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">

Page 18 Prof. Patil R. M


<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
String name = (String) pageContext.getAttribute("user", PageContext.SESSION_SCOPE);
out.print("Hello " + name);
%>
</body>
</html>
Output
Run the index.html page, you will get the following output:

4) Session Object in JSP:


 This is the HttpSession object associated with the request. A session is an implicit object which
is created for HttpSession class using which we can store and access data.
 The session reference point HttpSession implementation object. By default, this reference is
available to scriptlet, expression tags.
 These tags can access session related info and they can manage session scope attributes.

Page 19 Prof. Patil R. M


 By using this reference these tags can delete session objects by calling session.invalidate() and
these reference tags can set session timeout.

Following are the methods of the session object:


1. getAttribute(String name): It returns the object bound with the specified name in this session.
2. getAttributeNames(): It returns an Enumeration of String objects containing the names of all
the objects bound to this session.
3. getCreationTime(): It returns the time when this session was created.
4. getId(): It returns a string containing the unique identifier assigned to this session.
5. getLastAccessedTime(): It returns the last time the client sent a request associated with this
session.
6. getMaxInactiveInterval(): It returns the maximum time interval that the servlet container will
keep this session open between client accesses.
7. invalidate(): It invalidates the session and unbinds any objects bound to it.
8. isNew(): It returns True if the client does not know about the session or if the client chooses not
to join the session.
9. removeAttribute(String name): It removes the object bound with the specified name from
this session.
10. setAttribute(String name, Object value): It binds an object to this session using the specified
name.
11. setMaxInactiveInterval(int interval): It specifies the time between client requests before the
servlet container will invalidate this session.

Example of Session Object in JSP:


In this example, the index.html page would display a text box along with a submit button which would
transfer the control to welcome.jsp page which will display the name user has entered. And it then
stores the same variable in the session object so that it can be fetched on any page until the session
becomes inactive. Then in second.jsp we are fetching the variable’s value from the session object and
displaying it.
index.html

<!DOCTYPE html>
<html>
<head>
<title>implicit object</title>
</head>
<body bgcolor="pink">
<form action="welcome.jsp">
<input type="text" name="uname"> <input type="submit"
value="GO"><br />

Page 20 Prof. Patil R. M


</form>
</body>
</html>

welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
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
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
String name = (String) session.getAttribute("user");
out.print("Hello " + name);
%>
</body>
Page 21 Prof. Patil R. M
</html>

Output

5) Application Object in JSP:-


 This is the ServletContext object associated with the application context.
 Application is an implicit object which is created for ServletContext class and used to access
the data of the ServletContaxt object same as in servlets.
 The application reference point ServletContext implementation object.
 By using this reference, a JSP can access application-related information such as managing
application scope attributes, getting the application init parameters, etc.

Following are the methods of application object:


1. setAttribute(String Key, Object Value): This method is used to set a hit counter variable and
to reset the same variable.
2. getAttribute(String Key): This method is used to read the current value of the hit counter and
increase it by one and again set it for future use whenever a user accesses your page.

Example of Implicit Application Object in JSP


In this example, we are using the application object to get the initialization parameter from the
web.xml configuration file.
index.html

<!DOCTYPE html>

Page 22 Prof. Patil R. M


<html>
<head>
<title>implicit object</title>
</head>
<body bgcolor="pink">
<form action="welcome">
<input type="text" name="uname"> <input type="submit"
value="GO"><br />
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
out.print("Welcome " + request.getParameter("uname"));
String driver = application.getInitParameter("dname");
out.print("driver name is=" + driver);
%>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>welcome</servlet-name>

Page 23 Prof. Patil R. M


<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>welcome</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>

Output
Run your code to get the following output:

6) Implicit Config Object in JSP:


 This is the ServletContext object associated with the page.
 This implicit object is created for ServletConfig class and used to access the data of the
ServletConfig object same as in servlets.
 The config reference points ServletConfig implementation object.
 By using this config reference a JSP page can get initialization parameters of JSP configuration,
get initialization parameters names, get servlet names, and can get servlet context reference.

Following is the only method of config object:


1. getServletName(): This method returns the servlet name which is the string contained in the
<servlet-name> element defined in the web.xml configuration file.
2. getServletContext(): It returns a reference to the Servlet Context.

Example of Config Object in JSP


Page 24 Prof. Patil R. M
In this example, we are calling the getServletName() method of config object for fetching the servlet
name from web.xml.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
String sname = config.getServletName();
out.print("Servlet Name is: " + sname);
%>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>

Page 25 Prof. Patil R. M


Output

7) Out Object in JSP:


This is the PrintWriter object used to send output to the client. The out-reference points JSPWriter
subclass object. By using the object, we can print HTML tags and plain text data on the browser.

Methods of out object


1. out.print(dataType dt): It is used to print a data type value.
2. out.println(dataType dt): It is used to print a data type value then terminate the line with a
new line character.
3. out.flush(): It is used to flush the stream.

Example of Out Object in JSP


In this example, we are using the print method of OUT for displaying messages to the client.

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%
out.print("Today is:" + java.util.Calendar.getInstance().getTime());
%>
</body>
</html>

Output

Page 26 Prof. Patil R. M


8) Page Object in JSP:-
This is simply a synonym for this and is used to call the methods defined by the translated servlet class.
The page reference points current JSP page object.

Example
public final view_jsp extends HttpBase…{
public void _jspService(request, response)…{
Object page=this;
}
}

9) Exception Object in JSP:-


The Exception object allows the exception data to be accessed by a designated JSP. This reference
points to any exception object raised in the .jsp page and provides that exception object to the error JSP
page.

Methods of Exception implicit object


1. getMessage(): It gives a detailed message about the exception that has occurred. This is
initialized in the Throwable constructor.
2. getCause(): It returns the cause of the exception as represented by a Throwable object.
3. toString(): It gives the name of the class concatenated with the result of getMessage().
4. printstackTrace(): It prints the result of toString() along with the stack trace to System.err.
5. getStackTrace(): It returns an array containing each element on the stack trace.
6. fillnStackTrace(): It fills the stack trace of this Throwable object with the current stack trace.

Example of Implicit Exception Object in JSP


In this example, we are taking two inputs(integer) from the user and then performing division between
them. Here we have used the exception implicit object to handle any kind of exception.
index.html

<!DOCTYPE html>

Page 27 Prof. Patil R. M


<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<form action="division.jsp">
Input First Integer:<input type="text" name="firstnum" /> Input
Second Integer:<input type="text" name="secondnum" /> <input
type="submit" value="Get Results" />
</form>
</body>
</html>

division.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%@ page errorPage="exception.jsp"%>
<%
String num1 = request.getParameter("firstnum");
String num2 = request.getParameter("secondnum");
int v1 = Integer.parseInt(num1);
int v2 = Integer.parseInt(num2);
int res = v1 / v2;
out.print("Output is: " + res);
%>
</body>
</html>

exception.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
Page 28 Prof. Patil R. M
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="pink">
<%@ page isErrorPage="true"%>
Got this Exception:
<%=exception%>
Please correct the input data.
</body>
</html>

Output

Page 29 Prof. Patil R. M


 Exception handling in JSP :-
 Java Server Pages declares 9 implicit objects, the exception object being one of them.
 It is an object of java.lang.Throwable class, and is used to print exceptions. However, it can
only be used in error pages.
 There are two ways of handling exceptions in JSP. They are:
 By errorPage and isErrorPage attributes of page directive
 By <error-page> element in web.xml file

Handling Exception using page directive attributes


The page directive in JSP provides two attributes to be used in exception handling. They’re:
 errorPage: Used to site which page to be displayed when exception occurred.
Syntax :
<%@page errorPage="url of the error page"%>
 isErrorPage: Used to mark a page as an error page where exceptions are displayed.
Syntax :
<%@page isErrorPage="true"%>
In order to handle exceptions using the aforementioned page directives, it is important to have a jsp
page to execute the normal code, which is prone to exceptions. Also, a separate error page is to be
created, which will display the exception. In case the exception occurs on the page with the
exception prone code, the control will be navigated to the error page which will display the
exception.
The following is an example illustrating exception handling using page directives:
index.html

 HTML

<html>
<head>
<body>
<form action="a.jsp">
Number1:<input type="text" name="first" >
Number2:<input type="text" name="second" >
<input type="submit" value="divide">
</form>
</body>
</html>

A.jsp
 Java
Page 30 Prof. Patil R. M
// JSP code to divide two numbers
<% @page errorPage = "error.jsp" %> < %
String num1 = request.getParameter("first");
String num2 = request.getParameter("second");
// extracting numbers from request
int x = Integer.parseInt(num1);
int y = Integer.parseInt(num2);
int z = x / y; // dividing the numbers
out.print("division of numbers is: " + z); // result
%>

error.jsp
 Java
// JSP code for error page, which displays the exception
<% @page isErrorPage = "true" %>

<h1> Exception caught</ h1>

The exception is : <%= exception %> // displaying the exception

Output:
index.html

error.jsp

Page 31 Prof. Patil R. M


 JSTL (JSP Standard Tag Library) :-
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates the core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating
XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating
the existing custom tags with the JSTL tags.

Advantage of JSTL
1. Fast Developement JSTL provides many tags that simplifies the JSP.
2. Code Reusability We can use the JSTL tags in various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.

JSTL Tags :-

There JSTL mainly provides 5 types of tags: 10

Classification of The JSTL Tags


The JSTL tags can be classified, according to their functions, into the following JSTL tag library
groups that can be used when creating a JSP page −
 Core Tags
 Formatting tags
 SQL tags
 XML tags
 JSTL Functions

1) Core Tags
The core group of tags are the most commonly used JSTL tags. Following is the syntax to include the
JSTL Core library in your JSP −
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
Following table lists out the core JSTL Tags −

S.No. Tag & Description

1 <c:out>

Page 32 Prof. Patil R. M


Like <%= ... >, but for expressions.

<c:set >
2
Sets the result of an expression evaluation in a 'scope'

<c:remove >
3
Removes a scoped variable (from a particular scope, if specified).

<c:catch>
4
Catches any Throwable that occurs in its body and optionally exposes it.

<c:if>
5
Simple conditional tag which evalutes its body if the supplied condition is true.

<c:choose>
6 Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>.

<c:when>
7
Subtag of <choose> that includes its body if its condition evalutes to 'true'.

<c:otherwise >
8
Subtag of <choose> that follows the <when> tags and runs only if all of the prior
conditions evaluated to 'false'.

<c:import>
9 Retrieves an absolute or relative URL and exposes its contents to either the page, a
String in 'var', or a Reader in 'varReader'.

<c:forEach >
10
The basic iteration tag, accepting many different collection types and supporting
subsetting and other functionality .

<c:forTokens>
11
Iterates over tokens, separated by the supplied delimeters.

Page 33 Prof. Patil R. M


<c:param>
12
Adds a parameter to a containing 'import' tag's URL.

<c:redirect >
13
Redirects to a new URL.

<c:url>
14
Creates a URL with optional query parameters

2) Formatting Tags:-
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Websites. Following is the syntax to include Formatting library in your JSP −
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
Following table lists out the Formatting JSTL Tags −

S.No. Tag & Description

<fmt:formatNumber>
1
To render numerical value with specific precision or format.

<fmt:parseNumber>
2
Parses the string representation of a number, currency, or percentage.

<fmt:formatDate>
3
Formats a date and/or time using the supplied styles and pattern.

<fmt:parseDate>
4
Parses the string representation of a date and/or time

<fmt:bundle>
5
Loads a resource bundle to be used by its tag body.

6 <fmt:setLocale>

Page 34 Prof. Patil R. M


Stores the given locale in the locale configuration variable.

<fmt:setBundle>
7 Loads a resource bundle and stores it in the named scoped variable or the bundle
configuration variable.

<fmt:timeZone>
8
Specifies the time zone for any time formatting or parsing actions nested in its
body.

<fmt:setTimeZone>
9
Stores the given time zone in the time zone configuration variable

<fmt:message>
10
Displays an internationalized message.

<fmt:requestEncoding>
11
Sets the request character encoding

3) SQL Tags:-
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such
as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>
Following table lists out the SQL JSTL Tags −

S.No. Tag & Description

<sql:setDataSource>
1
Creates a simple DataSource suitable only for prototyping

<sql:query>
2
Executes the SQL query defined in its body or through the sql attribute.

Page 35 Prof. Patil R. M


<sql:update>
3
Executes the SQL update defined in its body or through the sql attribute.

<sql:param>
4
Sets a parameter in an SQL statement to the specified value.

<sql:dateParam>
5
Sets a parameter in an SQL statement to the specified java.util.Date value.

<sql:transaction >
6 Provides nested database action elements with a shared Connection, set up to
execute all statements as one transaction.

4) XML tags:-
The JSTL XML tags provide a JSP-centric way of creating and manipulating the XML documents.
Following is the syntax to include the JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with the XML data. This includes parsing
the XML, transforming the XML data, and the flow control based on the XPath expressions.
<%@ taglib prefix = "x"
uri = "http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you will need to copy the following two XML and XPath
related libraries into your <Tomcat Installation Directory>\lib −
 XercesImpl.jar − Download it from https://www.apache.org/dist/xerces/j/
 xalan.jar − Download it from https://xml.apache.org/xalan-j/index.html
Following is the list of XML JSTL Tags −

S.No. Tag & Description

<x:out>
1
Like <%= ... >, but for XPath expressions.

<x:parse>
2
Used to parse the XML data specified either via an attribute or in the tag body.

Page 36 Prof. Patil R. M


<x:set >
3
Sets a variable to the value of an XPath expression.

<x:if >
4
Evaluates a test XPath expression and if it is true, it processes its body. If the test
condition is false, the body is ignored.

<x:forEach>
5
To loop over nodes in an XML document.

<x:choose>
6
Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise> tags.

<x:when >
7
Subtag of <choose> that includes its body if its expression evalutes to 'true'.

<x:otherwise >
8
Subtag of <choose> that follows the <when> tags and runs only if all of the prior
conditions evaluates to 'false'.

<x:transform >
9
Applies an XSL transformation on a XML document

<x:param >
10
Used along with the transform tag to set a parameter in the XSLT stylesheet

5) JSTL Functions:-
JSTL includes a number of standard functions, most of which are common string manipulation
functions. Following is the syntax to include JSTL Functions library in your JSP −
<%@ taglib prefix = "fn"
uri = "http://java.sun.com/jsp/jstl/functions" %>
Following table lists out the various JSTL Functions −

S.No. Function & Description

Page 37 Prof. Patil R. M


fn:contains()
1
Tests if an input string contains the specified substring.

fn:containsIgnoreCase()
2
Tests if an input string contains the specified substring in a case insensitive way.

fn:endsWith()
3
Tests if an input string ends with the specified suffix.

fn:escapeXml()
4
Escapes characters that can be interpreted as XML markup.

fn:indexOf()
5
Returns the index withing a string of the first occurrence of a specified substring.

fn:join()
6
Joins all elements of an array into a string.

fn:length()
7
Returns the number of items in a collection, or the number of characters in a string.

fn:replace()
8
Returns a string resulting from replacing in an input string all occurrences with a
given string.

fn:split()
9
Splits a string into an array of substrings.

fn:startsWith()
10
Tests if an input string starts with the specified prefix.

fn:substring()
11
Returns a subset of a string.

Page 38 Prof. Patil R. M


fn:substringAfter()
12
Returns a subset of a string following a specific substring.

fn:substringBefore()
13
Returns a subset of a string before a specific substring.

fn:toLowerCase()
14
Converts all of the characters of a string to lower case.

fn:toUpperCase()
15
Converts all of the characters of a string to upper case.

fn:trim()
16
Removes white spaces from both ends of a string.

What is JSTL?
 JSTL stands for Java server pages standard tag library.
 It is a collection of custom JSP tag libraries that provide common web development
functionality.
 JSTL is a standard tag library of the JSP.
 JSTL (JSP Standard Tag Library) is a collection of custom tags that provide common
functionalities like flow control, database operations, etc.
 JSTL tags can be embedded in Java Server Pages just like other HTML tags.
 It is convenient for front-end developers to work with HTML-like tags for including logic in
webpages rather than writing Java code in scripts.
 To use JSTL tags, the following dependencies must be included in pom.xml in a maven project:

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

JSTL tags are grouped into five major categories:


1. Core Tags
2. Formatting Tags
3. SQL Tags
4. XML Tags
5. Function Tags
This article focuses on JSTL Core tags.
Page 39 Prof. Patil R. M
JSTL Core Tags
Core tags in JSTL are used for iteration, conditional logic, url management, handling exceptions,
redirect, etc.

The following tags are included in the JSTL Core tag library:
 catch
 choose
 if
 import
 forEach
 forTokens
 out
 otherwise
 param
 redirect
 remove
 set
 url
 when

1) c:set
It is used to set a value to a variable that can be used within the specified scope in a JSP.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.SetTag
 Body content: jsp
 Attributes:
 var: It is used to provide the name of the variable.
 value: It is used to provide the value for the variable. It can contain any expression.
 scope: It is used to set the scope of the variable.
 target: It is used to provide the target object whose property is to be set.
 property: It is used to specify the name of the property to be set for the target object.
Example:
set.jsp
<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Set Tag</title>
</head>

Page 40 Prof. Patil R. M


<body>
<h1>
<c:set var="name" value="John"/>
My Name is
<c:out value="${name}"/>
</h1>
</body>
</html>

Output:
My Name is John

2) c:remove
removes the specified variable.
 Tag handler class: org.apache.taglibs.standard.tag.common.core.RemoveTag
 Body-content: empty
 Attributes:
 var: It is used to specify the variable to be removed.
Example:
remove.jsp

<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Remove Tag</title>
</head>
<body>
<h1>
<c:set var="name" value="John"/>
My Name is
<c:out value="${name}"/>
<br>

Page 41 Prof. Patil R. M


<c:remove var="name"/>
My Name is
<c:out value="${name}"/>
</h1>
</body>
</html>

Output:
My Name is John
My Name is
In the above example, the variable name is removed, therefore, the second <c:out>
doesn’t display the name.

3) c:out
It is used to display the content on the web page similar to the expression tag (<%=
%).
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.OutTag.
 Body content: jsp
 Attributes:
 value: It is used to provide the value to be displayed.
 default: It is used to provide the default value, in case, the value
provided is null.
Example:
out.jsp
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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Out Tag</title>
</head>
<body>
<h1>
<c:out value="We are learning JSTL Core Tags"/>

Page 42 Prof. Patil R. M


</h1>
</body>
</html>

Output:
We are learning JSTL Core Tags

4) c:forEach
used to iterate over a collection or an array.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.ForEachTag
 Body content: jsp
 Attributes:
 items: It is used to provide a collection of objects to iterate over.
 begin: It is used to specify the beginning of the iteration.
 end: It is used to specify the end of the iteration.
 step: It is used to provide the steps to be taken between two
consecutive iterations.
 var: It is used to provide a variable for a current item of the iteration.
Example:
forEach.jsp
<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>ForEach Tag</title>
</head>
<body>
<h1>
<c:forEach var="i" begin="1" end="10" step="2">
<c:out value="${i}"/>
</c:forEach>
<br>
<%
int[] marks={10,12,15,14,9};
session.setAttribute("marks",marks);
%>

Page 43 Prof. Patil R. M


<c:forEach var="mark" items="${marks}">
<c:out value="${mark}"/>
</c:forEach>
</h1>
</body>
</html>

Output:
1 3 5 7 9
10 12 15 14 9

5) c:import
It is used to include the contents from relative or absolute urls within or outside the
server.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.ImportTag
 Body content: jsp
 Attributes:
 url: It is used to specify the url of the resource to be imported.
 var: It is used to provide the var in which contents of the imported
resource are to be stored.
 scope: It is used to specify the scope.
Example:
import.jsp
<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Import Tag</title>
</head>
<body>
<c:import var="content" url="http://www.google.com"/>
<c:out value="${content}"/>
</body>
</html>

Page 44 Prof. Patil R. M


6) c:param
It is used with <c:import> or <c:redirect> to send parameters in the url to the
imported or redirected pages respectively.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.ParamTag
 Body content: jsp
 Attributes:
 name: It is used to provide the name of the parameter.
 value: It is used to provide value for the parameter.
c:redirect
It is used to redirect a page to another url.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.RedirectTag
 Body content: jsp
 Attributes:
 url: It is used to provide the url of the resource to be redirected to.
Example:
redirect.jsp
<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Redirect Tag</title>
</head>
<body>
<h1>
<c:redirect url="welcome.jsp">
<c:param name="name" value="John"/>
</c:redirect>
</h1>
</body>
</html>

<%@ page language="java" contentType="text/html; charset=ISO -8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

Page 45 Prof. Patil R. M


<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Welcome</title>
</head>
<body>
<h1>
Welcome <%= request.getParameter("name") %>!
</h1>
</body>
</html>

Output:
Welcome John!

7) c:catch
It is used to catch any exception of type Throwable that occurs in the body.
 Tag handler class: org.apache.taglibs.standard.tag.common.core.CatchTag
 Body-content: jsp
 Attributes:
 var: used to store the exception thrown by body-content.
Example:
catch.jsp

<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Catch Tag</title>
</head>
<body>

Page 46 Prof. Patil R. M


<h1>
<c:catch var="e">
<%int x=2/0; %>
</c:catch>
<c:if test="${e!=null }">
<c:out value="${e }"></c:out>
</c:if>
<br>
</h1>
</body>
</html>
Output:
java.lang.ArithmeticException:/by zero

8) c:if
It is used to include the conditional statement in the java server pages. Body content
is evaluated only when the condition evaluates to true.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.IfTag
 Body-content: jsp
 Attributes:
 test: used to provide the testing condition.
Example:
if.jsp
<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>If Tag</title>
</head>
<body>
<h1>
<c:set var="marks" value="80"/>
<c:if test="${marks>33 }">
Qualified!!
</c:if>
</h1>

Page 47 Prof. Patil R. M


</body>
</html>

10) c:choose, c:when, c:otherwise


It is used to include a conditional statement on the page. It allows multiple conditions
similar to if-else ladder or switch case statements.
<c:choose>: It marks the beginning of conditional and encloses <c:when> and
<c:otherwise>.
 Tag handler class: org.apache.taglibs.standard.tag.common.core.ChooseTag
 Body content: jsp
 Attributes: no attribute
<c:when>: It is used to provide the condition and encloses the body to be executed
if the condition evaluates to true.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.WhenTag
 Body content: jsp
 Attributes:
 test: It is used to provide the condition.
<c:otherwise>: It encloses the content to be executed if all the above conditions
evaluate as false.
 Tag handler class: org.apache.taglibs.standard.tag.common.core.OtherwiseTag
 Body content: jsp
 Attributes: no attribute
Example:
choose.jsp

<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Choose Tag</title>
</head>
<body>
<h1>
<c:set var="marks" value="95"/>
<c:choose>
<c:when test="${marks>90}">A Grade</c:when>
<c:when test="${marks>80}">B Grade</c:when>
<c:when test="${marks>70}">C Grade</c:when>

Page 48 Prof. Patil R. M


<c:when test="${marks>60}">D Grade</c:when>
<c:when test="${marks>50}">E Grade</c:when>
<c:otherwise>Not satisfactory</c:otherwise>
</c:choose>

</h1>
</body>
</html>

Output:
A Grade

11) c:url
It is used to create a formatted url along with parameters using a nested <c:param>
tag.
 Tag handler class: org.apache.taglibs.standard.tag.rt.core.UrlTag
 Body content: jsp
 Attributes:
 var: It is used to provide the variable that holds the url.
 scope: It is used to set the scope.
 value: It is used to provide the url to be formatted.
Example:
<%@ 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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Url Tag</title>
</head>
<body>
<h1>
<a href = "
<c:url value = "/jsp/welcome.jsp"/>
">Click here</a>
</h1>
</body>
</html>
Page 49 Prof. Patil R. M
Output:
Click here

 Advantages of JSTL
Below are the advantages of JSTL:

1. Standard Tag: It provides a rich layer of the portable functionality of JSP pages. It’s easy for a
developer to understand the code.
2. Code Neat and Clean: As scriplets confuse developer, the usage of JSTL makes the code neat
and clean.
3. Automatic Java beans Interospection Support: It has an advantage of JSTL over JSP
scriptlets. JSTL Expression language handles JavaBean code very easily. We don’t need to
downcast the objects, which has been retrieved as scoped attributes. Using JSP scriptlets code
will be complicated, and JSTL has simplified that purpose.
4. Easier for humans to read: JSTL is based on XML, which is very similar to HTML. Hence, it
is easy for the developers to understand.
5. Easier for computers to understand: Tools such as Dreamweaver and front page are
generating more and more HTML code. HTML tools do a great job of formatting HTML code.
The HTML code is mixed with the scriplet code. As JSTL is expressed as XML compliant tags,
it is easy for HTML generation to parse the JSTL code within the document.

Page 50 Prof. Patil R. M

You might also like