Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 191

JSP NOTES

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.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

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.

3) Fast Development: No need to recompile and redeploy

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.

4) Less code than Servlet

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.

The Lifecycle of a JSP Page


The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

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.

Creating a simple JSP Page


To create the first JSP page, write some HTML code as given below, and save it
by .jsp extension. We have saved this file as index.jsp. Put it in a folder and paste the
folder in the web-apps directory in apache tomcat to run the JSP page.

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>

It will print 10 on the browser.

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for
example, http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a


simple JSP?
No, there is no need of directory structure if you don't have class files or TLD files.
For example, put JSP files in a folder directly and deploy that folder. It will be running
fine. However, if you are using Bean class, Servlet or TLD file, the directory structure is
required.

The Directory structure of JSP


The directory structure of JSP page is same as Servlet. We contain the JSP page
outside the WEB-INF folder or in any directory.
The JSP API
1. The JSP API
2. javax.servlet.jsp package
3. The JspPage interface
4. The HttpJspPage interface

The JSP API consists of two packages:

1. javax.servlet.jsp
2. javax.servlet.jsp.tagext

javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as
follows:

1. JspPage
2. HttpJspPage

The classes are as follows:

o JspWriter
o PageContext
o JspFactory
o JspEngineInfo
o JspException
o JspError

The JspPage interface


According to the JSP specification, all the generated servlet classes must implement
the JspPage interface. It extends the Servlet interface. It provides two life cycle
methods.

Methods of JspPage interface

1. public void jspInit(): It is invoked only once during the life cycle of the JSP when JSP
page is requested firstly. It is used to perform initialization. It is same as the init()
method of Servlet interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP
before the JSP page is destroyed. It can be used to perform some clean up operation.

The HttpJspPage interface


The HttpJspPage interface provides the one life cycle method of JSP. It extends the
JspPage interface.

Method of HttpJspPage interface:

1. public void _jspService(): It is invoked each time when request for the JSP page
comes to the container. It is used to process the request. The underscore _ signifies
that you cannot override this method.
JSP Scriptlet tag (Scripting
elements)
1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name

In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see
what are the scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:

o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.

1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp. The
index.html file gets the username from the user and the welcome.jsp file prints the
username with the welcome message.

File: index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

File: welcome.jsp

1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>
JSP expression tag
The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print the
values of variable or method.

Syntax of JSP expression tag

1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>

Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints


current time
To display the current time, we have used the getTime() method of Calendar class.
The getTime() is an instance method of Calendar class, so we have called it after
getting the instance of Calendar class by the getInstance() method.

index.jsp

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print the
values of variable or method.

Syntax of JSP expression tag

1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>

Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints


current time
To display the current time, we have used the getTime() method of Calendar class.
The getTime() is an instance method of Calendar class, so we have called it after
getting the instance of Calendar class by the getInstance() method.

index.jsp
JSP Declaration Tag
1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method

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.

So it doesn't get memory at each request.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>

Difference between JSP Scriptlet tag and


Declaration tag

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as w
not methods. as methods.
The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is plac
the _jspService() method. outside the _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the
value of the declared field using the jsp expression tag.

index.jsp

1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the
cube of given number and calling this method from the jsp expression tag. But we
can also use jsp scriptlet tag to call the declared method.

index.jsp

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>
JSP Implicit Objects
1. JSP Implicit Objects
2. out implicit object
3. Example of out implicit object

There are 9 jsp implicit objects. These objects are created by the web container that
are available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession
pageContext PageContext

page Object

exception Throwable

1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter. In case of servlet you need to write:

1. PrintWriter out=response.getWriter();

But in JSP, you don't need to write this code.

Example of out implicit object


In this example we are simply displaying date and time.

index.jsp

1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>

Output
JSP request implicit object
The JSP request is an implicit object of type HttpServletRequest i.e. created for each
jsp request by the web container. It can be used to get request information such as
parameter, header information, remote address, server name, server port, content
type, character encoding etc.

It can also be used to set, get and remove attributes from the jsp request scope.

Let's see the simple example of request implicit object where we are printing the
name of the user with welcome message.

Example of JSP request implicit object


index.html

1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>

welcome.jsp

1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>

Output
3) JSP response implicit object
In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.

It can be used to add or manipulate response such as redirect response to another


resource, send error etc.

Let's see the example of response implicit object where we are redirecting the
response to the Google.

Example of response implicit object


index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. response.sendRedirect("http://www.google.com");
3. %>

Output
4) JSP config implicit object
In JSP, config is an implicit object of type ServletConfig. This object can be used to
get initialization parameter for a particular JSP page. The config object is created by
the web container for each jsp page.

Generally, it is used to get initialization parameter from the web.xml file.

Example of config implicit object:


index.html
1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6.
7. <init-param>
8. <param-name>dname</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>sonoojaiswal</servlet-name>
16. <url-pattern>/welcome</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>
welcome.jsp
1. <%
2. out.print("Welcome "+request.getParameter("uname"));
3.
4. String driver=config.getInitParameter("dname");
5. out.print("driver name is="+driver);
6. %>

Output
5) JSP application implicit object
In JSP, application is an implicit object of type ServletContext.

The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.

This object can be used to get initialization parameter from configuaration file
(web.xml). It can also be used to get, set or remove attribute from the application
scope.

This initialization parameter can be used by all jsp pages.

Example of application implicit object:


index.html
1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
web.xml file
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. <context-param>
14. <param-name>dname</param-name>
15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
16. </context-param>
17.
18. </web-app>
welcome.jsp
1. <%
2.
3. out.print("Welcome "+request.getParameter("uname"));
4.
5. String driver=application.getInitParameter("dname");
6. out.print("driver name is="+driver);
7.
8. %>

Output
6) session implicit object
In JSP, session is an implicit object of type HttpSession.The Java developer can use this
object to set,get or remove attribute or to get session information.

Example of session implicit object


index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

welcome.jsp

1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>

second.jsp

1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>

Output
6) session implicit object
In JSP, session is an implicit object of type HttpSession.The Java developer can use this object to se
or remove attribute or to get session information.

Example of session implicit object


index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>

welcome.jsp

1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>

second.jsp

1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>

Output
8) page implicit object:
In JSP, page is an implicit object of type Object class.This object is assigned to the reference
of auto generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For example:
<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object directly in jsp.For
example:
<% this.log("message"); %>

9) exception implicit object


In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to p
the exception. But it can only be used in error pages.It is better to learn it after page directive. Let's
a simple example:

Example of exception implicit object:


error.jsp

1. <%@ page isErrorPage="true" %>


2. <html>
3. <body>
4.
5. Sorry following exception occured:<%= exception %>
6.
7. </body>
8. </html>
JSP directives
1. JSP directives
1. page directive
2. Attributes of page directive

The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive

1. <%@ directive attribute="value" %>

JSP page directive


The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

1. <%@ page attribute="value" %>

Attributes of JSP page directive

o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

1)import

The import attribute is used to import class,interface or all the members of a package.It is simila
import keyword in java class or interface.

Example of import attribute

1. <html>
2. <body>
3.
4. <%@ page import="java.util.Date" %>
5. Today is: <%= new Date() %>
6.
7. </body>
8. </html>

2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute

1. <html>
2. <body>
3.
4. <%@ page contentType=application/msword %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>
3)extends
The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.

4)info
This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.

Example of info attribute

1. <html>
2. <body>
3.
4. <%@ page info="composed by Sonoo Jaiswal" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

The web container will create a method getServletInfo() in the resulting servlet.For
example:

1. public String getServletInfo() {


2. return "composed by Sonoo Jaiswal";
3. }

5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by
the JSP page.The default size of the buffer is 8Kb.

Example of buffer attribute

1. <html>
2. <body>
3.
4. <%@ page buffer="16kb" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

6)language
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".

7)isELIgnored

We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its valu
false i.e. Expression Language is enabled by default. We see Expression Language later.
1. <%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe

Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false,
web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding
request before passing another request to it.If you make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

1. public class SimplePage_jsp extends HttpJspBase


2. implements SingleThreadModel{
3. .......
4. }

9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.

Example of errorPage attribute

1. //index.jsp
2. <html>
3. <body>
4.
5. <%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9. </body>
10. </html>

10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.

Note: The exception object can only be used in the error page.

Example of isErrorPage attribute

1. //myerrorpage.jsp
2. <html>
3. <body>
4.
5. <%@ page isErrorPage="true" %>
6.
7. Sorry an exception occured!<br/>
8. The exception is: <%= exception %>
9.
10. </body>
11. </html>
Jsp Include Directive
1. Include directive
2. Advantage of Include directive
3. Example of include directive

The include directive is used to include the contents of any resource it may be jsp
file, html file or text file. The include directive includes the original content of the
included resource at page translation time (the jsp page is translated only once so it
will be better to include static resource).

Advantage of Include directive


Code Reusability

Syntax of include directive

1. <%@ include file="resourceName" %>

Example of include directive


In this example, we are including the content of the header.html file. To run this
example you must create an header.html file.

1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>
JSP Taglib directive
1. JSP Taglib directive
2. Example of JSP Taglib directive

The JSP taglib directive is used to define a tag library that defines many tags. We use
the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we
will use this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

1. <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive


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.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>
Exception Handling in JSP
1. Exception Handling in JSP
2. Example of exception handling in jsp by the elements of page directive
3. Example of exception handling in jsp by specifying the error-page element in web.xml
file

The exception is normally an object that is thrown at runtime. Exception Handling is


the process to handle the runtime errors. There may occur exception any time in your
web application. So handling exceptions is a safer side for the web developer. In JSP,
there are two ways to perform exception handling:

1. By errorPage and isErrorPage attributes of page directive


2. By <error-page> element in web.xml file

Example of exception handling in jsp by the elements of page


directive
In this case, you must define and create a page to handle the exceptions, as in the
error.jsp page. The pages where may occur exception, define the errorPage attribute
of page directive, as in the process.jsp page.

There are 3 files:

o index.jsp for input values


o process.jsp for dividing the two numbers and displaying the result
o error.jsp for handling the 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>

process.jsp

1. <%@ page errorPage="error.jsp" %>


2. <%
3.
4. String num1=request.getParameter("n1");
5. String num2=request.getParameter("n2");
6.
7. int a=Integer.parseInt(num1);
8. int b=Integer.parseInt(num2);
9. int c=a/b;
10. out.print("division of numbers is: "+c);
11.
12. %>

error.jsp

1. <%@ page isErrorPage="true" %>


2.
3. <h3>Sorry an exception occured!</h3>
4.
5. Exception is: <%= exception %>
download this example

Output of this example:


Example of exception handling in jsp by specifying the error-
page element in web.xml file
This approach is better because you don't need to specify the errorPage attribute in
each jsp page. Specifying the single entry in the web.xml file will handle the
exception. In this case, either specify exception-type or error-code with the location
element. If you want to handle all the exception, you will have to specify the
java.lang.Exception in the exception-type element. Let's see the simple example

There are 4 files:

o web.xml file for specifying the error-page element


o index.jsp for input values
o process.jsp for dividing the two numbers and displaying the result
o error.jsp for displaying the exception

1) web.xml file if you want to handle any exception

1. <web-app>
2.
3. <error-page>
4. <exception-type>java.lang.Exception</exception-type>
5. <location>/error.jsp</location>
6. </error-page>
7.
8. </web-app>

This approach is better if you want to handle any exception. If you know any specific
error code and you want to handle that exception, specify the error-code element
instead of exception-type as given below:
1) web.xml file if you want to handle the exception for a
specific error code

1. <web-app>
2.
3. <error-page>
4. <error-code>500</error-code>
5. <location>/error.jsp</location>
6. </error-page>
7.
8. </web-app>

2) index.jsp file is same as in the above example

3) process.jsp

Now, you don't need to specify the errorPage attribute of page directive in the jsp page.
1. <%@ page errorPage="error.jsp" %>
2. <%
3.
4. String num1=request.getParameter("n1");
5. String num2=request.getParameter("n2");
6.
7. int a=Integer.parseInt(num1);
8. int b=Integer.parseInt(num2);
9. int c=a/b;
10. out.print("division of numbers is: "+c);
11.
12. %>

4) error.jsp file is same as in the above example


JSP Action Tags
1. JSP Action Tags
2. jsp:forward action tag
3. Example of jsp:forward action tag without parameter
4. Example of jsp:forward action tag with parameter

There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks.

The action tags are used to control the flow between pages and to use Java Bean.
The Jsp action tags are given below.

JSP Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include mostly.

jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean
development. So we will see these tags in bean developement.

jsp:forward action tag


The jsp:forward action tag is used to forward the request to another resource it may
be jsp, html or another resource.

Syntax of jsp:forward action tag without parameter

1. <jsp:forward page="relativeURL | <%= expression %>" />

Syntax of jsp:forward action tag with parameter

1. <jsp:forward page="relativeURL | <%= expression %>">


2. <jsp:param name="parametername" value="parametervalue | <%=expression
%>" />
3. </jsp:forward>

Example of jsp:forward action tag without parameter


In this example, we are simply forwarding the request to the printdate.jsp file.

index.jsp

1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" />
6. </body>
7. </html>

printdate.jsp

1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>

Example of jsp:forward action tag with parameter


In this example, we are forwarding the request to the printdate.jsp file with
parameter and printdate.jsp file prints the parameter value with date and time.

index.jsp

1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" >
6. <jsp:param name="name" value="javatpoint.com" />
7. </jsp:forward>
8.
9. </body>
10. </html>

printdate.jsp

1. <html>
2. <body>
3.
4. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
5. <%= request.getParameter("name") %>
6.
7. </body>
8. </html>
jsp:include action tag
1. jsp:include action tag
2. Syntax of jsp:include action tag
3. Example of jsp:include action tag without parameter

The jsp:include action tag is used to include the content of another resource it may
be jsp, html or servlet.

The jsp include action tag includes the resource at request time so it is better for
dynamic pages because there might be changes in future.

The jsp:include tag can be used to include static as well as dynamic pages.

Advantage of jsp:include action tag


Code reusability : We can use a page many times such as including header and
footer pages in all pages. So it saves a lot of time.

Difference between jsp include directive


and include action

JSP include directive JSP include action

includes resource at translation time. includes resource at request time.


better for static pages. better for dynamic pages.

includes the original content in the generated servlet. calls the include method.

Syntax of jsp:include action tag without parameter

1. <jsp:include page="relativeURL | <%= expression %>" />

Syntax of jsp:include action tag with parameter

1. <jsp:include page="relativeURL | <%= expression %>">


2. <jsp:param name="parametername" value="parametervalue | <%=expression
%>" />
3. </jsp:include>

Example of jsp:include action tag without parameter


In this example, index.jsp file includes the content of the printdate.jsp file.

File: index.jsp
1. <h2>this is index page</h2>
2.
3. <jsp:include page="printdate.jsp" />
4.
5. <h2>end section of index page</h2>
File: printdate.jsp
1. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
download this example
JavaBean
A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as
getter and setter methods.

Why use JavaBean?


According to Java white paper, it is a reusable software component. A bean
encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.

Simple example of JavaBean class


1. //Employee.java
2.
3. package mypack;
4. public class Employee implements java.io.Serializable{
5. private int id;
6. private String name;
7. public Employee(){}
8. public void setId(int id){this.id=id;}
9. public int getId(){return id;}
10. public void setName(String name){this.name=name;}
11. public String getName(){return name;}
12. }
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.

1. package mypack;
2. public class Test{
3. public static void main(String args[]){
4. Employee e=new Employee();//object is created
5. e.setName("Arjun");//setting value to the object
6. System.out.println(e.getName());
7. }}

Note: There are two ways to provide values to the object. One way is by constructor and
second is by setter method.

JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the
object. The feature can be of any Java data type, containing the classes that you
define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features


are accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.

Advantages of JavaBean
The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another application.


o It provides an easiness to reuse the software components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.

o Creating the setter and getter method for each property separately may lead
to the boilerplate code.The JavaBean properties and methods can be exposed
to another application.
o It provides an easiness to reuse the software components.

Disadvantages of JavaBean
The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead
to the boilerplate code.

jsp:useBean action tag


1. jsp:useBean action tag
2. Syntax of jsp:useBean action tag
3. Attributes and Usage of jsp:useBean action tag
4. Simple example of jsp:useBean action tag

The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object
of the Bean class is already created, it doesn't create the bean depending on the
scope. But if object of bean is not created, it instantiates the bean.

Syntax of jsp:useBean action tag


1. <jsp:useBean id= "instanceName" scope= "page | request | session | applicatio
n"
2. class= "packageName.className" type= "packageName.className"
3. beanName="packageName.className | <%= expression >" >
4. </jsp:useBean>

Attributes and Usage of jsp:useBean action tag

1. id: is used to identify the bean in the specified scope.


2. scope: represents the scope of the bean. It may be page, request, session or
application. The default scope is page.
o page: specifies that you can use this bean within the JSP page. The default
scope is page.
o request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
o session: specifies that you can use this bean from any JSP page in the same
session whether processes the same request or not. It has wider scope than
request.
o application: specifies that you can use this bean from any JSP page in the
same application. It has wider scope than session.
3. class: instantiates the specified bean class (i.e. creates an object of the bean class) but
it must have no-arg or no constructor and must not be abstract.
4. type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName attribute. If you use it without class or
beanName, no bean is instantiated.
5. beanName: instantiates the bean using the java.beans.Beans.instantiate() method.

Simple example of jsp:useBean action tag


In this example, we are simply invoking the method of the Bean class.

For the example of setProperty, getProperty and useBean tags, visit next page.

Calculator.java (a simple Bean class)

1. package com.javatpoint;
2. public class Calculator{
3.
4. public int cube(int n){return n*n*n;}
5.
6. }

index.jsp file

1. <jsp:useBean id="obj" class="com.javatpoint.Calculator"/>


2.
3. <%
4. int m=obj.cube(5);
5. out.print("cube of 5 is "+m);
6. %>
jsp:setProperty and jsp:getProperty
action tags
1. jsp:setProperty and jsp:getProperty action tags
2. Syntax of jsp:setProperty action tag
3. Example of jsp:setProperty
4. jsp:getProperty action tag
5. Syntax of jsp:getProperty action tag
6. Example of jsp:getProperty action tag
7. Example of bean development in JSP

The setProperty and getProperty action tags are used for developing web application
with Java Bean. In web devlopment, bean class is mostly used because it is a reusable
software component that represents data.

The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.
Syntax of jsp:setProperty action tag
1. <jsp:setProperty name="instanceOfBean" property= "*" |
2. property="propertyName" param="parameterName" |
3. property="propertyName" value="{ string | <%= expression %>}"
4. />

Example of jsp:setProperty action tag if you have to set all the


values of incoming request in the bean

1. <jsp:setProperty name="bean" property="*" />

Example of jsp:setProperty action tag if you have to set value


of the incoming specific property

1. <jsp:setProperty name="bean" property="username" />

Example of jsp:setProperty action tag if you have to set a


specific value in the property

1. <jsp:setProperty name="bean" property="username" value="Kumar" />

jsp:getProperty action tag


The jsp:getProperty action tag returns the value of the property.

Syntax of jsp:getProperty action tag

1. <jsp:getProperty name="instanceOfBean" property="propertyName" />

Simple example of jsp:getProperty action tag

1. <jsp:getProperty name="obj" property="name" />

Example of bean development in JSP


In this example there are 3 pages:

o index.html for input of values


o welocme.jsp file that sets the incoming values to the bean object and prints
the one value
o User.java bean class that have setter and getter methods

index.html

1. <form action="process.jsp" method="post">


2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. Email:<input type="text" name="email"><br>
5. <input type="submit" value="register">
6. </form>

process.jsp

1. <jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>


2. <jsp:setProperty property="*" name="u"/>
3.
4. Record:<br>
5. <jsp:getProperty property="name" name="u"/><br>
6. <jsp:getProperty property="password" name="u"/><br>
7. <jsp:getProperty property="email" name="u" /><br>

User.java

1. package org.sssit;
2.
3. public class User {
4. private String name,password,email;
5. //setters and getters
6. }
download this example
Reusing Bean in Multiple Jsp Pages
Let's see the simple example, that prints the data of bean object in two jsp pages.

index.jsp

Same as above.

User.java

Same as above.

process.jsp

1. <jsp:useBean id="u" class="org.sssit.User" scope="session"></jsp:useBean>


2. <jsp:setProperty property="*" name="u"/>
3.
4. Record:<br>
5. <jsp:getProperty property="name" name="u"/><br>
6. <jsp:getProperty property="password" name="u"/><br>
7. <jsp:getProperty property="email" name="u" /><br>
8.
9. <a href="second.jsp">Visit Page</a>

second.jsp

1. <jsp:useBean id="u" class="org.sssit.User" scope="session"></jsp:useBean>


2. Record:<br>
3. <jsp:getProperty property="name" name="u"/><br>
4. <jsp:getProperty property="password" name="u"/><br>
5. <jsp:getProperty property="email" name="u" /><br>

Using variable value in setProperty tag


In some case, you may get some value from the database, that is to be set in the
bean object, in such case, you need to use expression tag. For example:

process.jsp

1. <jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>


2. <%
3. String name="arjun";
4. %>
5. <jsp:setProperty property="name" name="u" value="<%=name %>"/>
6.
7. Record:<br>
8. <jsp:getProperty property="name" name="u"/><br>

Displaying applet in JSP (jsp:plugin action


tag)
1. Displaying applet in JSP
2. Syntax of jsp:plugin action tag
3. Example of displaying applet in JSP

The jsp:plugin action tag is used to embed applet in the jsp file. The jsp:plugin action
tag downloads plugin at client side to execute an applet or bean.

Syntax of jsp:plugin action tag


1. <jsp:plugin type= "applet | bean" code= "nameOfClassFile"
2. codebase= "directoryNameOfClassFile"
3. </jsp:plugin>

Example of displaying applet in JSP


In this example, we are simply displaying applet in jsp using the jsp:plugin tag. You must have MouseDrag.
file (an applet class file) in the current folder where jsp file resides. You may simply download this program
contains index.jsp, MouseDrag.java and MouseDrag.class files to run this application.

index.jsp

1. <html>
2. <head>
3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
4. <title>Mouse Drag</title>
5. </head>
6. <body bgcolor="khaki">
7. <h1>Mouse Drag Example</h1>
8.
9. <jsp:plugin align="middle" height="500" width="500"
10. type="applet" code="MouseDrag.class" name="clock" codebase="."/>
11.
12. </body>
13. </html>

Expression Language (EL) in JSP


1. Expression Language (EL) in JSP
2. Implicit Objects in Expression Language
3. Simple example of Expression Language that prints the name of the user
4. Example of Expression Language that prints the value set in the session scope
5. Precedence of Operators in EL
6. Reserve words in EL

The Expression Language (EL) simplifies the accessibility of data stored in the Java
Bean component, and other objects like request, session, application etc.

There are many implicit objects, operators and reserve words in EL.

It is the newly added feature in JSP technology version 2.0.

Syntax for Expression Language (EL)

1. ${ expression }

Implicit Objects in Expression Language


(EL)
There are many implicit objects in the Expression Language. They are as follows:

Implicit Objects 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

param it maps the request parameter to the single value

paramValues it maps the request parameter to an array of values

header it maps the request header name to the single value

headerValues it maps the request header name to an array of values

cookie it maps the given cookie name to the cookie value

initParam it maps the initialization parameter


pageContext it provides access to many objects request, session etc.

EL param example
In this example, we have created two files index.jsp and process.jsp. The index.jsp file
gets input from the user and sends the request to the process.jsp which in turn prints
the name of the user using EL.

index.jsp

1. <form action="process.jsp">
2. Enter Name:<input type="text" name="name" /><br/><br/>
3. <input type="submit" value="go"/>
4. </form>

process.jsp

1. Welcome, ${ param.name }
download this example

EL sessionScope example
In this example, we printing the data stored in the session scope using EL. For this
purpose, we have used sessionScope object.

index.jsp

1. <h3>welcome to index page</h3>


2. <%
3. session.setAttribute("user","sonoo");
4. %>
5.
6. <a href="process.jsp">visit</a>

process.jsp

1. Value is ${ sessionScope.user }
download this example

EL cookie example
index.jsp

1. <h1>First JSP</h1>
2. <%
3. Cookie ck=new Cookie("name","abhishek");
4. response.addCookie(ck);
5. %>
6. <a href="process.jsp">click</a>

process.jsp

1. Hello, ${cookie.name.value}

Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their
precedence are as follows:

[] .

()

-(unary) not ! empty

* / div % mod

+ - (binary)

< <= > >= lt le gt ge

== != eq ne

&& and

|| or

?:

Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:

lt le gt ge

eq ne true false

and or not instanceof

div mod empty null


MVC in JSP
1. MVC in JSP
2. Example of following MVC in JSP

MVC stands for Model View and Controller. It is a design pattern that separates the
business logic, presentation logic and data.

Controller acts as an interface between View and Model. Controller intercepts all the
incoming requests.

Model represents the state of the application i.e. data. It can also have business
logic.

View represents the presentaion i.e. UI(User Interface).

Advantage of MVC (Model 2) Architecture

1. Navigation Control is centralized


2. Easy to maintain the large application

MVC Example in JSP


In this example, we are using servlet as a controller, jsp as a view component, Java
Bean class as a model.

In this example, we have created 5 pages:

o index.jsp a page that gets input from the user.


o ControllerServlet.java a servlet that acts as a controller.
o login-success.jsp and login-error.jsp files acts as view components.
o web.xml file for mapping the servlet.

File: index.jsp
1. <form action="ControllerServlet" method="post">
2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
5. </form>
File: ControllerServlet
1. package com.javatpoint;
2. import java.io.IOException;
3. import java.io.PrintWriter;
4. import javax.servlet.RequestDispatcher;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9. public class ControllerServlet extends HttpServlet {
10. protected void doPost(HttpServletRequest request, HttpServletResponse r
esponse)
11. throws ServletException, IOException {
12. response.setContentType("text/html");
13. PrintWriter out=response.getWriter();
14.
15. String name=request.getParameter("name");
16. String password=request.getParameter("password");
17.
18. LoginBean bean=new LoginBean();
19. bean.setName(name);
20. bean.setPassword(password);
21. request.setAttribute("bean",bean);
22.
23. boolean status=bean.validate();
24.
25. if(status){
26. RequestDispatcher rd=request.getRequestDispatcher("login-
success.jsp");
27. rd.forward(request, response);
28. }
29. else{
30. RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
31. rd.forward(request, response);
32. }
33.
34. }
35.
36. @Override
37. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
38. throws ServletException, IOException {
39. doPost(req, resp);
40. }
41. }
File: LoginBean.java
1. package com.javatpoint;
2. public class LoginBean {
3. private String name,password;
4.
5. public String getName() {
6. return name;
7. }
8. public void setName(String name) {
9. this.name = name;
10. }
11. public String getPassword() {
12. return password;
13. }
14. public void setPassword(String password) {
15. this.password = password;
16. }
17. public boolean validate(){
18. if(password.equals("admin")){
19. return true;
20. }
21. else{
22. return false;
23. }
24. }
25. }
File: login-success.jsp
1. <%@page import="com.javatpoint.LoginBean"%>
2.
3. <p>You are successfully logged in!</p>
4. <%
5. LoginBean bean=(LoginBean)request.getAttribute("bean");
6. out.print("Welcome, "+bean.getName());
7. %>
File: login-error.jsp
1. <p>Sorry! username or password error</p>
2. <%@ include file="index.jsp" %>
File: web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/
xml/ns/javaee/web-app_2_5.xsd"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/
xml/ns/javaee/web-app_3_0.xsd"
5. id="WebApp_ID" version="3.0">
6.
7. <servlet>
8. <servlet-name>s1</servlet-name>
9. <servlet-class>com.javatpoint.ControllerServlet</servlet-class>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>s1</servlet-name>
13. <url-pattern>/ControllerServlet</url-pattern>
14. </servlet-mapping>
15. </web-app>

Output
STL (JSP Standard Tag Library)
The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP
development.

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

JSTL Tags
There JSTL mainly provides five types of tags:

Tag Name Description

Core tags The JSTL core tag provide variable support, URL management, flow control, etc. The URL for
core tag is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.

Function The functions tags provide support for string manipulation and string length. The URL for
tags functions tags is http://java.sun.com/jsp/jstl/functions and prefix is fn.

Formatting The Formatting tags provide support for message formatting, number and date formatting,
tags The URL for the Formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc. The URL for the XML t
is http://java.sun.com/jsp/jstl/xml and prefix is x.

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL t
is http://java.sun.com/jsp/jstl/sql and prefix is sql.

For creating JSTL application, you need to load the jstl.jar file.

Download the jstl.jar file


Download the jstl1.2.jar file
JSTL Core Tags
The JSTL core tag provides variable support, URL management, flow control etc. The
syntax used for including JSTL core library in your JSP is:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

JSTL Core Tags 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
'var',a Reader in 'varReader' or the page.

c:set It sets the result of an expression under evaluation in a 'scope' variable.

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 o
if the expression evaluates is true.

c:choose, c:when, It is the simple conditional tag that includes its body content if the evalua
c:otherwise condition is true.

c:forEach It is the basic iteration tag. It repeats the nested body content for fixed numbe
times or over collection.

c:forTokens It iterates over tokens which is separated by the supplied delimeters.

c:param It adds a parameter in a containing 'import' tag's URL.

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.


JSTL Core <c:out> Tag
The <c:out> tag is similar to JSP expression tag, but it can only be used with expression. It
will display the result of an expression, similar to the way < %=...% > work.

The < c:out > tag automatically escape the XML tags. Hence they aren't evaluated as actual
tags.

Let's see the simple example of c:out tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Tag Example</title>
5. </head>
6. <body>
7. <c:out value="${'Welcome to javaTpoint'}"/>
8. </body>
9. </html>

Output:
JSTL Core <c:import> Tag
The <c:import> is similar to jsp 'include', with an additional feature of including the
content of any resource either within server or outside the server.

This tag provides all the functionality of the <include > action and it also allows the
inclusion of absolute URLs.

For example: Using an import tag the content from a different FTP server and website
can be accessed.

Let's see the simple example of c:import tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Tag Example</title>
5. </head>
6. <body>
7. <c:import var="data" url="http://www.javatpoint.com"/>
8. <c:out value="${data}"/>
9. </body>
10. </html>

Above example would fetch the complete content from javatpoint.com and would
store in a variable "data" which will printed eventually.
JSTL Core <c:set> Tag
It is used to set the result of an expression evaluated in a 'scope'. The <c:set> tag is
helpful because it evaluates the expression and use the result to set a value of
java.util.Map or JavaBean.

This tag is similar to jsp:setProperty action tag.

Let's see the simple example of <c:set> tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:set var="Income" scope="session" value="${4000*4}"/>
8. <c:out value="${Income}"/>
9. </body>
10. </html>

Output:
JSTL Core <c:remove> Tag
It is used for removing the specified variable from a particular scope. This action is not
particularly helpful, but it can be used for ensuring that a JSP can also clean up any scope
resources.

The <c:remove > tag removes the variable from either a first scope or a specified scope.

Let's see the simple example of c:remove tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:set var="income" scope="session" value="${4000*4}"/>
8. <p>Before Remove Value is: <c:out value="${income}"/></p>
9. <c:remove var="income"/>
10. <p>After Remove Value is: <c:out value="${income}"/></p>
11. </body>
12. </html>

Output:
JSTL Core <c:catch> Tag
It is used for Catches any Throwable exceptions that occurs in the body and optionally
exposes it. In general it is used for error handling and to deal more easily with the problem
occur in program.

The < c:catch > tag catches any exceptions that occurs in a program body.

Let's see the simple example of c:catch tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7.
8. <c:catch var ="catchtheException">
9. <% int x = 2/0;%>
10. </c:catch>
11.
12. <c:if test = "${catchtheException != null}">
13. <p>The type of exception is : ${catchtheException} <br />
14. There is an exception: ${catchtheException.message}</p>
15. </c:if>
16.
17. </body>
18. </html>

Output:
JSTL Core <c:if> Tag
The < c:if > tag is used for testing the condition and it display the body content, if
the expression evaluated is true.

It is a simple conditional tag which is used for evaluating the body content, if the
supplied condition is true.

Let's see the simple example of c:if tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:set var="income" scope="session" value="${4000*4}"/>
8. <c:if test="${income > 8000}">
9. <p>My income is: <c:out value="${income}"/><p>
10. </c:if>
11. </body>
12. </html>

Output:
JSTL Core <c:choose>, <c:when>,
<c:otherwise> Tag
The < c:choose > tag is a conditional tag that establish a context for mutually
exclusive conditional operations. It works like a Java switch statement in which we
choose between a numbers of alternatives.

The <c:when > is subtag of <choose > that will include its body if the condition
evaluated be 'true'.

The < c:otherwise > is also subtag of < choose > it follows &l;twhen > tags and runs
only if all the prior condition evaluated is 'false'.

The c:when and c:otherwise works like if-else statement. But it must be placed inside
c:choose tag.

JSTL Core <c:choose>, <c:when>,


<c:otherwise> Example
Let's see the simple example of < c:choose >, < c:when > < c:otherwise > tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:set var="income" scope="session" value="${4000*4}"/>
8. <p>Your income is : <c:out value="${income}"/></p>
9. <c:choose>
10. <c:when test="${income <= 1000}">
11. Income is not good.
12. </c:when>
13. <c:when test="${income > 10000}">
14. Income is very good.
15. </c:when>
16. <c:otherwise>
17. Income is undetermined...
18. </c:otherwise>
19. </c:choose>
20. </body>
21. </html>

This will produce the following result:

1. Your income is : 16000


2. Income is very good.

Even/Odd Example using c:when and


c:otherwise
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <h1>JSTL c:when, c:otherwise, c:choose</h1>
8.
9. <c:set value="10" var="num"></c:set>
10. <c:choose>
11. <c:when test="${num%2==0}">
12. <c:out value="${num} is even number"></c:out>
13. </c:when>
14. <c:otherwise>
15. <c:out value="${num} is odd number"></c:out>
16. </c:otherwise>
17. </c:choose>
18.
19. </body>
20. </html>

Output:

1. 10 is even number
JSTL Core <c:forEach> Tag
The <c:for each > is an iteration tag used for repeating the nested body content for
fixed number of times or over the collection.

These tag used as a good alternative for embedding a Java while, do-while, or
for loop via a scriptlet. The < c:for each > tag is most commonly used tag because it
iterates over a collection of object.

Let's see the simple example of tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:forEach var="j" begin="1" end="3">
8. Item <c:out value="${j}"/><p>
9. </c:forEach>
10. </body>
11. </html>

Output:
JSTL Core <c:forTokens> Tag
The < c:forTokens > tag iterates over tokens which is separated by the supplied
delimeters. It is used for break a string into tokens and iterate through each of the
tokens to generate output.

This tag has similar attributes as < c:forEach > tag except one additional
attributes delims which is used for specifying the characters to be used as delimiters.

Let's see the simple example of < c:forTokens > tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:forTokens items="Rahul-Nakul-Rajesh" delims="-" var="name">
8. <c:out value="${name}"/><p>
9. </c:forTokens>
10. </body>
11. </html>

Output:
JSTL Core <c:param> Tag
The < c:param > tag add the parameter in a containing 'import' tag's URL. It allow
the proper URL request parameter to be specified within URL and it automatically
perform any necessary URL encoding.

Inside < c:param > tag, the value attribute indicates the parameter value and name
attribute indicates the parameter name.

Let's see the simple example of tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:url value="/index1.jsp" var="completeURL"/>
8. <c:param name="trackingId" value="786"/>
9. <c:param name="user" value="Nakul"/>
10. </c:url>
11. ${completeURL}
12. </body>
13. </html>

Output:
JSTL Core <c:redirect> Tag
The < c:redirect > tag redirects the browser to a new URL. It supports the context-relative
URLs, and the < c:param > tag.

It is used for redirecting the browser to an alternate URL by using automatic URL rewriting.

Let's see the simple example of < c:redirect > tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:set var="url" value="0" scope="request"/>
8. <c:if test="${url<1}">
9. <c:redirect url="http://javatpoint.com"/>
10. </c:if>
11. <c:if test="${url>1}">
12. <c:redirect url="http://facebook.com"/>
13. </c:if>
14. </body>
15. </html>

Output:

Since the value of the variable 'url' is 0 the page gets directed to
the http://javatpoint.com .
JSTL Core <c:url> Tag
The < c:url > tag creates a URL with optional query parameter. It is used for url encoding or
url formatting. This tag automatically performs the URL rewriting operation.

The JSTL url tag is used as an alternative method of writing call to the
response.encodeURL() method. The advantage of url tag is proper URL encoding and
including the parameters specified by children. param tag.

Let's see the simple example of < c:url > tag:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <html>
3. <head>
4. <title>Core Tag Example</title>
5. </head>
6. <body>
7. <c:url value="/RegisterDao.jsp"/>
8. </body>
9. </html>

Output:

1. /CRUD/RegisterDao.jsp

Note: CRUD is my project name in other words JSP application name.


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:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

JSTL Function Tags List


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 c


insensitive way.

fn:endsWith() It is used to test if an input string ends with the specified suffix.

fn:escapeXml() It escapes the characters that would be interpreted as XML markup.

fn:indexOf() It returns an index within a string of first occurrence of a specified substring.

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 str
value.

fn:split() It splits the string into an array of substrings.

fn:toLowerCase() It converts all the characters of a string to lower case.

fn:toUpperCase() It converts all the characters of a string to upper case.

fn:substring() It returns the subset of a string according to the given start and end position.
fn:substringAfter() It returns the subset of string after a specific substring.

fn:substringBefore() It returns the subset of string before a specific substring.

fn:length() It returns the number of characters inside a string, or the number of items i
collection.

fn:replace() It replaces all the occurrence of a string with another string sequence.

STL fn:contains() Function


The fn:contains() is used for testing if the string containing the specified substring. If
the specified substring is found in the string, it returns true otherwise false.

The syntax used for including the fn:contains() function is:

1. boolean contains(java.lang.String, java.lang.String)

Let's see the simple example to understand the functionality of fn:contains() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Functions</title>
6. </head>
7. <body>
8.
9. <c:set var="String" value="Welcome to javatpoint"/>
10.
11. <c:if test="${fn:contains(String, 'javatpoint')}">
12. <p>Found javatpoint string<p>
13. </c:if>
14.
15. <c:if test="${fn:contains(String, 'JAVATPOINT')}">
16. <p>Found JAVATPOINT string<p>
17. </c:if>
18.
19. </body>
20. </html>

Output:
b

JSTL fn:containsIgnoreCase()
Function
The fn:containsIgnoreCase() function is used to test if an input string contains the specified
substring as a case insensitive way. During searching the specified substring it ignores the
case

The syntax used for including the fn:containsIgnoreCase() function is:

1. boolean containsIgnoreCase(java.lang.String, java.lang.String)

Let's see the simple example to understand the functionality of fn:containsIgnoreCase()


function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Functions</title>
6. </head>
7. <body>
8.
9. <c:set var="String" value="Welcome to javatpoint"/>
10.
11. <c:if test="${fn:containsIgnoreCase(String, 'javatpoint')}">
12. <p>Found javatpoint string<p>
13. </c:if>
14.
15. <c:if test="${fn:containsIgnoreCase(String, 'JAVATPOINT')}">
16. <p>Found JAVATPOINT string<p>
17. </c:if>
18.
19. </body>
20. </html>
Output:

JSTL fn:endsWith() Function


The fn:endsWith() function is used for testing if an input string ends with the specified suffix.
If the string ends with a specified suffix, it returns true otherwise false.

The syntax used for including the fn:endsWith() function is:

1. boolean endsWith(java.lang.String, java.lang.String)

Let's see the simple example to understand the functionality of fn:endsWith() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Functions</title>
6. </head>
7. <body>
8.
9. <c:set var="String" value="Welcome to JSP programming"/>
10.
11. <c:if test="${fn:endsWith(String, 'programming')}">
12. <p>String ends with programming<p>
13. </c:if>
14.
15. <c:if test="${fn:endsWith(String, 'JSP')}">
16. <p>String ends with JSP<p>
17. </c:if>
18.
19. </body>
20. </html>
Output:

JSTL fn:escapeXml() Function


The fn:escapeXml() function escapes the characters that would be interpreted as XML
markup. It is used for escaping the character in XML markup language.

The syntax used for including the fn:escapeXml() function is:

1. java.lang.String escapeXml(java.lang.String)

Let's see the simple example to understand the functionality of fn:escapeXml()


function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Functions</title>
6. </head>
7. <body>
8.
9. <c:set var="string1" value="It is first String."/>
10. <c:set var="string2" value="It is <xyz>second String.</xyz>"/>
11.
12. <p>With escapeXml() Function:</p>
13. <p>string-1 : ${fn:escapeXml(string1)}</p>
14. <p>string-2 : ${fn:escapeXml(string2)}</p>
15.
16. <p>Without escapeXml() Function:</p>
17. <p>string-1 : ${string1}</p>
18. <p>string-2 : ${string2}</p>
19.
20. </body>
21. </html>

Output:

JSTL fn:indexOf() Function


The fn:indexOf() function return an index of string. It is used for determining the index of
string specified in substring.

The syntax used for including the fn:indexOf() function is:

1. int indexOf(java.lang.String, java.lang.String)

Let's see the simple example to understand the functionality of fn:indexOf() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Functions</title>
6. </head>
7. <body>
8.
9. <c:set var="string1" value="It is first String."/>
10. <c:set var="string2" value="It is <xyz>second String.</xyz>"/>
11.
12. <p>Index-1 : ${fn:indexOf(string1, "first")}</p>
13. <p>Index-2 : ${fn:indexOf(string2, "second")}</p>
14.
15. </body>
16. </html>

Output:
JSTL fn:trim() Function
The fn:trim() function removes the blank spaces from both the ends of a string. It
mainly used for ignoring the blank spaces from both the ends of string.

The syntax used for including the fn:trim() function is:

1. java.lang.String trim(java.lang.String)

Let's see the simple example to understand the functionality of fn:trim() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Functions</title>
6. </head>
7. <body>
8.
9. <c:set var="str1" value="Welcome to JSP programming "/>
10. <p>String-1 Length is : ${fn:length(str1)}</p>
11.
12. <c:set var="str2" value="${fn:trim(str1)}" />
13. <p>String-2 Length is : ${fn:length(str2)}</p>
14. <p>Final value of string is : ${str2}</p>
15.
16. </body>
17. </html>
Output:

JSTL fn:startsWith() Function


The fn:startsWith() function test if an input string is started with the specified
substring.

The syntax used for including the fn:startsWith() function is:

1. boolean fn:startsWith(String input, String prefix)

This function is used for returning a boolean value. It gives the true result when the
string is started with the given prefix otherwise it returns a false result.

Let's see the simple example to understand the functionality of fn:startsWith()


function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Function</title>
6. </head>
7. <body>
8. <c:set var="msg" value="The Example of JSTL fn:startsWith() Function"/>
9. The string starts with "The": ${fn:startsWith(msg, 'The')}
10. <br>The string starts with "Example": ${fn:startsWith(msg, 'Example')}
11. </body>
12. </html>

Output:
1. The string starts with "The": true
2. The string starts with "Example": false

JSTL fn:split() Function


The fn:split() function splits the string into an array of substrings. It is used for
splitting the string into an array based on a delimiter string.

The syntax used for including the fn:split() function is:

1. java.lang.String[] split(java.lang.String, java.lang.String)

Let's see the simple example to understand the functionality of fn:split() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Functions</title>
6. </head>
7. <body>
8.
9. <c:set var="str1" value="Welcome-to-JSP-Programming."/>
10. <c:set var="str2" value="${fn:split(str1, '-')}" />
11. <c:set var="str3" value="${fn:join(str2, ' ')}" />
12.
13. <p>String-3 : ${str3}</p>
14. <c:set var="str4" value="${fn:split(str3, ' ')}" />
15. <c:set var="str5" value="${fn:join(str4, '-')}" />
16.
17. <p>String-5 : ${str5}</p>
18.
19. </body>
20. </html>

Output:

JSTL fn:toLowerCase() Function


The fn:toLowerCase() function converts all the characters of a string to lower case. It is used
for replacing any upper case character in the input string with the corresponding lowercase
character.

The syntax used for including the fn:toLowerCase() function is:

1. String fn:toLowerCase(String input)

Let's see the simple example to understand the functionality of fn:toLowerCase() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title> Using JSTL Function </title>
6. </head>
7. <body>
8. <c:set var="string" value="Welcome to JSP Programming"/>
9. ${fn:toLowerCase("HELLO,")}
10. ${fn:toLowerCase(string)}
11. </body>
12. </html>

Output:
JSTL fn:toUpperCase() Function
The fn:toUpperCase() function converts all the characters of a string to upper case. It
is used for replacing any lower case character in the input string with the
corresponding upper case character.

The syntax used for including the fn:toUpperCase() function is:

1. String fn:toUpperCase(String input)

It returns the string value after converting the input string to uppercase.

Let's see the simple example to understand the functionality of fn:toUpperCase()


function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Function </title>
6. </head>
7. <body>
8. <c:set var="site" value="javatpoint.com"/>
9. <c:set var="author" value="Sonoo Jaiswal"/>
10. Hi, This is ${fn:toUpperCase(site)} developed by ${fn:toUpperCase(author)}.
11. </body>
12. </html>

Output:

1. Hi, This is JAVATPOINT.COM developed by SONOO JAISWAL.

JSTL fn:substring() Function


The fn:substring() function returns the subset of a string. It is used to return the
substring of given input string according to specified start and end position.

The syntax used for including the fn:substring() function is:

1. String fn:substring(String inputstring, int start, int end)


o start: It is starting position of substring
o end: It is end position of substring
o inputstring: It is string from which a substring needed to be taken
o Return type of the function: String

Let's see the simple example to understand the functionality of fn:substring() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Function </title>
6. </head>
7. <body>
8. <c:set var="string" value="This is the first string."/>
9. ${fn:substring(string, 5, 17)}
10. </body>
11. </html>

Output:

JSTL fn:substringAfter() Function


The fn:substringAfter() function returns the subset of string followed by a specific
substring. It returns the part of string which lies after the provided string value.

The syntax used for including the fn:substringAfter() function is:

1. String fn:substringAfter(String input, String afterstring)

Let's see the simple example to understand the functionality of fn:substringAfter()


function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Function </title>
6. </head>
7. <body>
8. <c:set var="string" value="Nakul Jain"/>
9. ${fn:substringAfter(string, "Nakul")}
10. </body>
11. </html>

Output:
JSTL fn:substringBefore() Function
The fn:substringBefore() function returns the subset of string before a specific substring. It is
used for returning a part of original string which lies before the specified string value.

The syntax used for including the fn:substringBefore() function is:

1. String fn:substringBefore(String input, String beforestring)

Let's see the simple example to understand the functionality of fn:substringBefore() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Function </title>
6. </head>
7. <body>
8. <c:set var="string" value="Hi, This is JAVATPOINT.COM developed by SONOO J
AISWAL."/>
9. ${fn:substringBefore(string, "developed")}
10. </body>
11. </html>

Output:
JSTL fn:length() Function
The fn:length() function returns the number of characters inside a string, or the
number of items in a collection. It is used for calculating the length of string and to
find out the number of elements in a collection.

The syntax used for including the fn:length() function is:

1. int length(java.lang.Object)

It returns the length of object. The return type of this function is int .

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>JSTL fn:length() example</title>
6. </head>
7. <body>
8. <c:set var="str1" value="This is first string"/>
9. <c:set var="str2" value="Hello"/>
10. Length of the String-1 is: ${fn:length(str1)}<br>
11. Length of the String-2 is: ${fn:length(str2)}
12. </body>
13. </html>

Output:

1. Length of the String-1 is: 20


2. Length of the String-2 is: 5

JSTL fn:replace() Function


The fn:replace() function replaces all the occurrence of a string with another string
sequence. It search in an input string and replace it with the provided string.

The syntax used for including the fn:replace() function is:

1. String fn:replace(String input, String search_for, String replace_with)

It searches the search_for string in the input and replaces it with replace_with string.
In function three strings argument is used whose return type is also string.

Note: It performs case sensitive processing.

Let's see the simple example to understand the functionality of fn:replace() function:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
3. <html>
4. <head>
5. <title>Using JSTL Function </title>
6. </head>
7. <body>
8. <c:set var="author" value="Ramesh Kumar"/>
9. <c:set var="string" value="pqr xyz abc PQR"/>
10. ${fn:replace(author, "Ramesh", "Suresh")}
11. ${fn:replace(string, "pqr", "hello")}
12. </body>
13. </html>

Output:

1. Suresh Kumar hello xyz abc PQR

JSTL Formatting tags


The formatting tags provide support for message formatting, number and date
formatting etc. The url for the formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

The JSTL formatting tags are used for internationalized web sites to display and
format text, the time, the date and numbers. The syntax used for including JSTL
formatting library in your JSP is:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

Formatting Tags Descriptions

fmt:parseNumber It is used to Parses the string representation of a currency, percentage


number.

fmt:timeZone It specifies a parsing action nested in its body or the time zone for any ti
formatting.

fmt:formatNumber It is used to format the numerical value with specific format or precision.

fmt:parseDate It parses the string representation of a time and date.

fmt:bundle It is used for creating the ResourceBundle objects which will be used by th
tag body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.

fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable
the named scoped variable.

fmt:message It display an internationalized message.

fmt:formatDate It formats the time and/or date using the supplied pattern and styles.

JSTL XML tags


The JSTL XML tags are used for providing a JSP-centric way of manipulating and
creating XML documents.

The xml tags provide flow control, transformation etc. The url for the xml tags
is http://java.sun.com/jsp/jstl/xml and prefix is x. The JSTL XML tag library has
custom tags used for interacting with XML data. The syntax used for including JSTL
XML tags library in your JSP is:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

Before you proceed further with the examples, you need to copy the two XML and
XPath related libraries into the <Tomcat Installation Directory>\lib:

Xalan.jar: Download this jar file from the link:

1. http://xml.apache.org/xalan-j/index.html

XercesImpl.jar: Download this jar file from the link:

1. http://www.apache.org/dist/xerces/j/
JSTL XML tags List
XML Descriptions
Tags

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:set It is used to sets a variable to the value of an XPath expression.

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 bo
content.

x:transform It is used in a XML document for providing the XSL(Extensible Stylesheet Langua
transformation.

x:param It is used along with the transform tag for setting the parameter in the XSLT style sheet.

JSTL XML <x:out> Tag


The <x:out> tag is used for displaying the result of an xml Path expression and writes
the result to JSP writer object. It is similar to the scriptlet tag <%= %> used in JSP.

The syntax used for including the <x:out> tag is:

1. <x:out attributes/>

Let's see the simple example to understand the xml <x:out> tag:

1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


2. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
3.
4. <html>
5. <head>
6. <title>XML Tags</title>
7. </head>
8. <body>
9. <h2>Vegetable Information:</h2>
10. <c:set var="vegetable">
11. <vegetables>
12. <vegetable>
13. <name>onion</name>
14. <price>40/kg</price>
15. </vegetable>
16. <vegetable>
17. <name>Potato</name>
18. <price>30/kg</price>
19. </vegetable>
20. <vegetable>
21. <name>Tomato</name>
22. <price>90/kg</price>
23. </vegetable>
24. </vegetables>
25. </c:set>
26. <x:parse xml="${vegetable}" var="output"/>
27. <b>Name of the vegetable is</b>:
28. <x:out select="$output/vegetables/vegetable[1]/name" /><br>
29. <b>Price of the Potato is</b>:
30. <x:out select="$output/vegetables/vegetable[2]/price" />
31. </body>
32. </html>

Output:

Vegetable Information:
Name of the vegetable is: onion

Price of the Potato is: 30/kg


JSTL XML <x:parse> Tag
The <x:parse> tag is used for parse the XML data specified either in the tag body or
an attribute. It is used for parse the xml content and the result will stored inside
specified variable.

The syntax used for including the <x:parse> tag is:

1. <x:parse attributes> body content </x:parse>

Let's see the simple example to understand the xml <x:parse> tag:

Below examples represent how parse can be used for reading the external XML file
and it can be parsed from the body of given document.

Let us put the following content in novels.xml file:

1. <books>
2. <book>
3. <name>Three mistakes of my life</name>
4. <author>Chetan Bhagat</author>
5. <price>200</price>
6. </book>
7. <book>
8. <name>Tomorrow land</name>
9. <author>NUHA</author>
10. <price>2000</price>
11. </book>
12. </books>

Now put the following content in index.jsp, keeping in the same directory:

1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


2. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
3.
4. <html>
5. <head>
6. <title>x:parse Tag</title>
7. </head>
8. <body>
9. <h2>Books Info:</h2>
10. <c:import var="bookInfo" url="novels.xml"/>
11.
12. <x:parse xml="${bookInfo}" var="output"/>
13. <p>First Book title: <x:out select="$output/books/book[1]/name" /></p>
14. <p>First Book price: <x:out select="$output/books/book[1]/price" /></p>
15. <p>Second Book title: <x:out select="$output/books/book[2]/name" /
></p>
16. <p>Second Book price: <x:out select="$output/books/book[2]/price" /></p>
17.
18. </body>
19. </html>

Output:

Books Info:

First Book title: Three mistakes of my life

First Book price: 200

Second Book title: Tomorrow land


Second Book price: 2000

JSTL XML <x:set> Tag


The <x:set> tag is used to set a variable with the value of an XPath expression. It is
used to store the result of xml path expression in a scoped variable.

The syntax used for including the <x:set> tag is:

1. <x:set attributes/>

Let's see the simple example to understand the xml <x:set > tag is:

1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


2. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
3. <html>
4. <head>
5. <title>x:set Tag</title>
6. </head>
7. <body>
8. <h3>Books Information:</h3>
9. <c:set var="book">
10. <books>
11. <book>
12. <name>Three mistakes of my life</name>
13. <author>Chetan Bhagat</author>
14. <price>200</price>
15. </book>
16. <book>
17. <name>Tomorrow land</name>
18. <author>Brad Bird</author>
19. <price>2000</price>
20. </book>
21. </books>
22. </c:set>
23. <x:parse xml="${book}" var="output"/>
24. <x:set var="fragment" select="$output/books/book[2]/price"/>
25. <b>The price of the Tomorrow land book</b>:
26. <x:out select="$fragment" />
27. </body>
28. </html>

Output:
JSTL XML <x:choose>, <x:when>,
<x:otherwise> Tags
The <x:choose> tag is a conditional tag that establish a context for mutually
exclusive conditional operations. It works like a Java switch statement in which we
choose between a numbers of alternatives.

The <x:when> is subtag of <x:choose> that will include its body if the condition
evaluated be 'true'.

The <x:otherwise> is also subtag of <x:choose> it follows <x:when> tags and runs
only if all the prior condition evaluated is 'false'.

The <x:when> and <x:otherwise> works like if-else statement. But it must be placed
inside <x:choose> tag.
The syntax used for including the <x:choose;> tag is:

1. <x:choose> body content </x:choose>

The syntax used for including the <x:when> tag is:

1. <x:when attribute> body content </x:when>

The syntax used for including the < x:otherwise > tag is:

1. <x:otherwise> body content </x:otherwise>

Let's see the simple example to understand the xml <x:choose>, <x:when>,
<x:otherwise> tag:

1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


2. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
3.
4. <html>
5. <head>
6. <title>x:choose Tag</title>
7. </head>
8. <body>
9. <h3>Books Information:</h3>
10.
11. <c:set var="xmltext">
12. <books>
13. <book>
14. <name>Three mistakes of my life</name>
15. <author>Chetan Bhagat</author>
16. <price>200</price>
17. </book>
18. <book>
19. <name>Tomorrow land</name>
20. <author>Brad Bird</author>
21. <price>2000</price>
22. </book>
23. </books>
24. </c:set>
25.
26. <x:parse xml="${xmltext}" var="output"/>
27. <x:choose>
28. <x:when select="$output//book/author = 'Chetan bhagat'">
29. Book is written by Chetan bhagat
30. </x:when>
31. <x:when select="$output//book/author = 'Brad Bird'">
32. Book is written by Brad Bird
33. </x:when>
34. <x:otherwise>
35. The author is unknown...
36. </x:otherwise>
37. </x:choose>
38.
39. </body>
40. </html>

Output:

Books Information:

Book is written by Brad Bird


JSTL XML <x:if> Tag
The <x:if> tag is used for evaluating the test XPath expression. It is a simple conditional tag
which is used for evaluating its body if the supplied condition is true.

The syntax used for including the <x:if> tag is:

1. <x:if attributes> body content </x:if>

Let's see the simple example to understand the xml <x:if> tag:

1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


2. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
3. <html>
4. <head>
5. <title>x:if Tags</title>
6. </head>
7. <body>
8. <h2>Vegetable Information:</h2>
9. <c:set var="vegetables">
10. <vegetables>
11. <vegetable>
12. <name>onion</name>
13. <price>40</price>
14. </vegetable>
15. <vegetable>
16. <name>Potato</name>
17. <price>30</price>
18. </vegetable>
19. <vegetable>
20. <name>Tomato</name>
21. <price>90</price>
22. </vegetable>
23. </vegetables>
24. </c:set>
25. <x:parse xml="${vegetables}" var="output"/>
26. <x:if select="$output/vegetables/vegetable/price < 100">
27. Vegetables prices are very low.
28. </x:if>
29. </body>
30. </html>

Output:
JSTL XML <x:transform> Tag
The <x:transform> tag is used in a XML document for providing the XSL (Extensible
Stylesheet Language) transformation. It is used for transforming xml data based on
XSLT script.

The syntax used for including the <x:transform> tag is:

1. <x:transform attributes> body content </x:transform>

Let's see the simple example to understand the xml <x:transform> tag:

Let us put the following program in transfer.xsl file:

1. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/


Transform">
2. <xsl:param name="doc"/>
3. <xsl:template match="/">
4. <html>
5. <body>
6. <h2>Company's Employee detail</h2>
7. <table border="2">
8. <tr>
9. <th align="left">Name
10. </th>
11. <th align="left">Designation
12. </th>
13. <th align="left">Age
14. </th>
15. </tr>
16. <xsl:for-each select="organisation/company/emp">
17. <tr>
18. <td>
19. <xsl:value-of select="name"/>
20. </td>
21. <td>
22. <xsl:value-of select="designation"/>
23. </td>
24. <td>
25. <xsl:value-of select="age"/>
26. </td>
27. </tr>
28. </xsl:for-each>
29. </table>
30. </body>
31. </html>
32. </xsl:template>
33. </xsl:stylesheet>

Now put the following program in transfer.xml, keeping in the same directory:

1. <?xml version="1.0" encoding="UTF-8"?>


2. <organisation>
3. <company>
4. <emp>
5. <name>Rajan Singh</name>
6. <designation>Bussiness Developer</designation>
7. <age>40</age>
8. </emp>
9.
10. <emp>
11. <name>Supriya Gaur</name>
12. <designation>HR Executive</designation>
13. <age>22</age>
14. </emp>
15. </company>
16.
17. <company>
18. <emp>
19. <name>Shashnak Singhal</name>
20. <designation>Sr. Java Programmer</designation>
21. <age>26</age>
22. </emp>
23.
24. <emp>
25. <name>Hemant Kishor</name>
26. <designation>Sr. PHP Programmer</designation>
27. <age>23</age>
28. </emp></company></organisation>

Now put the following program in index.jsp, keeping in the same directory:

1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


2. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
3. <html>
4. <head>
5. <title>x:transform Tag</title>
6. </head>
7. </html>
8. <c:import var="xml" url="transfer.xml" />
9. <c:import var="xsl" url="transfer.xsl" />
10. <x:transform xml="${xml}" xslt="${xsl}" />

Output:
JSTL XML <x:param> Tag
The <x:param> tag is used to set the parameter in the XSLT style sheet. It use along
with the transform tag for sending parameter along with the value.

The syntax used for including the < x:param > tag is:

1. <x:param name="name" value="value"></x:param>

Let's see the simple example to understand the xml < x:param > tag:

Let us put the following program in transfer.xsl file:

1. <?xml version="1.0"?>
2. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" versio
n="1.0">
3. <xsl:output method="html" indent="yes"/>
4. <xsl:param name="bgColor"/>
5.
6. <xsl:template match="/">
7. <html>
8. <body>
9. <xsl:apply-templates/>
10. </body>
11. </html>
12. </xsl:template>
13.
14. <xsl:template match="books">
15. <table border="1" width="60%" bgColor="{$bgColor}">
16. <xsl:for-each select="book">
17. <tr>
18. <td>
19. <b><xsl:value-of select="name"/></b>
20. </td>
21. <td>
22. <xsl:value-of select="author"/>
23. </td>
24. <td>
25. <xsl:value-of select="price"/>
26. </td>
27. </tr>
28. </xsl:for-each>
29. </table>
30. </xsl:template>
31. </xsl:stylesheet>

Now put the following program in index.jsp , keeping in the same directory:

1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


2. <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
3.
4. <html>
5. <head>
6. <title>x:transform Tag</title>
7. </head>
8. <body>
9. <h3>Novels Information:</h3>
10. <c:set var="xmltext">
11. <books>
12. <book>
13. <name>Three mistakes of my life</name>
14. <author>Chetan Bhagat</author>
15. <price>200</price>
16. </book>
17. <book>
18. <name>Tomorrow land</name>
19. <author>Brad Bird</author>
20. <price>1000</price>
21. </book>
22. <book>
23. <name>Wings of fire</name>
24. <author>Dr. APJ Abdul Kalam</author>
25. <price>500</price>
26. </book>
27. </books>
28. </c:set>
29.
30. <c:import url="transfer.xsl" var="xslt"/>
31. <x:transform xml="${xmltext}" xslt="${xslt}">
32. <x:param name="bgColor" value="yellow"/>
33. </x:transform>
34.
35. </body>
36. </html>

Output:
JSTL SQL Tags
The JSTL sql tags provide SQL support. The url for the sql tags
is http://java.sun.com/jsp/jstl/sql and prefix is sql.

The SQL tag library allows the tag to interact with RDBMSs (Relational Databases)
such as Microsoft SQL Server, mySQL, or Oracle. The syntax used for including JSTL
SQL tags library in your JSP is:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

JSTL SQL Tags List


SQL Tags Descriptions

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.
JSTL SQL <sql:setDataSource> Tag
The <sql:setDataSource> tag is used for creating a simple data source suitable only
for prototyping.

It is used to create the data source variable directly from JSP and it is stored inside a
scoped variable. It can be used as input for other database actions.

Example:

Consider the below information about your MySQL database setup:

o We are using the JDBC MySQL driver


o We are using the test database on local machine
o We are using the "root" as username and "1234" as password to access the
test database.

Let's see the simple example to understand the xml <sql:setDataSource> tag is:

1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>


2. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
3. <html>
4. <head>
5. <title>sql:setDataSource Tag</title>
6. </head>
7. <body>
8.
9. <sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
10. url="jdbc:mysql://localhost/test"
11. user="root" password="1234"/>
12. </body>
13. </html>

The above code is used as input for other database actions. It is used for setting the
connection with database server. Therefore you will start using the
<sql:setDataSource> in subsequent SQL tags.

JSTL SQL <sql:query> Tag


The <sql:query> tag is used for executing the SQL query defined in its sql attribute
or the body. It is used to execute an SQL SELECT statement and saves the result in
scoped variable.

Example:

1. <sql:query dataSource="${db}" var="rs">


2. SELECT * from Students;
3. </sql:query>

JSTL SQL <sql:query> Complete Example


Consider the below information about your MySQL database setup:

o We are using the JDBC MySQL driver


o We are using the test database on local machine
o We are using the "root" as username and "1234" as password to access the
test database.

To understand the basic concept, let us create a simple table Students in the test
database and creates the few records in that table using command prompts as
follows:

Step-1: Open the command prompt and change to the installation directory as
follows:
1. C:\Users\javatpoint>
2. C:\Users\javatpoint>cd C:\Program Files\MySQL\MySQL Server 5.7\bin
3. C:\Program Files\MySQL\MySQL Server 5.7\bin>

It will look like this:

Step-2: Login to the database using command prompt as shown below:

1. C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p


2. Enter password: ****
3. mysql>

It will look like this:

Step-3: Create the table Students in test database as shown below:

1. mysql> use test;


2. mysql> create table Students
3. (
4. id int not null,
5. First_Name varchar (255),
6. Last_Name varchar (255),
7. Age int not null
8. );
9. Query OK, 0 rows affected (0.08 sec)
10. mysql>

It will look like this:

Step 4: In final step you need to create few data records in Students table as shown
below:

1. mysql> INSERT INTO Students VALUES (150, 'Nakul', 'Jain', 22);


2. Query OK, 1 row affected (0.05 sec)
3.
4. mysql> INSERT INTO Students VALUES (151, 'Ramesh', 'Kumar', 20);
5. Query OK, 1 row affected (0.00 sec)
6.
7. mysql> INSERT INTO Students VALUES (152, 'Ajeet', 'Singhal', 22);
8. Query OK, 1 row affected (0.00 sec)
9.
10. mysql> INSERT INTO Students VALUES (153, 'Hamza', 'Hussain', 22);
11. Query OK, 1 row affected (0.00 sec)
12.
13. mysql>

It will look like this:


Let's see the simple JSP example to understand the use of <sql:query> tag is:

1. <%@ page import="java.io.*,java.util.*,java.sql.*"%>


2. <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
4. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
5.
6. <html>
7. <head>
8. <title>sql:query Tag</title>
9. </head>
10. <body>
11.
12. <sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
13. url="jdbc:mysql://localhost/test"
14. user="root" password="1234"/>
15.
16. <sql:query dataSource="${db}" var="rs">
17. SELECT * from Students;
18. </sql:query>
19.
20. <table border="2" width="100%">
21. <tr>
22. <th>Student ID</th>
23. <th>First Name</th>
24. <th>Last Name</th>
25. <th>Age</th>
26. </tr>
27. <c:forEach var="table" items="${rs.rows}">
28. <tr>
29. <td><c:out value="${table.id}"/></td>
30. <td><c:out value="${table.First_Name}"/></td>
31. <td><c:out value="${table.Last_Name}"/></td>
32. <td><c:out value="${table.Age}"/></td>
33. </tr>
34. </c:forEach>
35. </table>
36.
37. </body>
38. </html>

This will produce the following result:


JSTL SQL <sql:update> Tag
The <sql:update> tag is used for executing the SQL DML query defined in its sql
attribute or in the tag body. It may be SQL UPDATE, INSERT or DELETE statements.

Example:

1. <sql:update dataSource="${db}" var="count">


2. INSERT INTO Students VALUES (154,'Nasreen', 'jaha', 25);
3. </sql:update>

JSTL SQL <sql:update> Complete Example


Consider the below information about your MySQL database setup:

o We are using the JDBC MySQL driver


o We are using the test database on local machine
o We are using the "root" as username and "1234" as password to access the
test database.

To understand the basic concept, let us create a simple table Students in the test
database and creates the few records in that table using command prompts as
follows:

Step-1: Open the command prompt and change to the installation directory as
follows:

1. C:\Users\javatpoint>
2. C:\Users\javatpoint>cd C:\Program Files\MySQL\MySQL Server 5.7\bin
3. C:\Program Files\MySQL\MySQL Server 5.7\bin>

It will look like this:


Step-2: Login to the database using command prompt as shown below:

1. C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p


2. Enter password: ****
3. mysql>

It will look like this:

Step-3: Create the table Students in test database as shown below:

1. mysql> use test;


2. mysql> create table Students
3. (
4. id int not null,
5. First_Name varchar (255),
6. Last_Name varchar (255),
7. Age int not null
8. );
9. Query OK, 0 rows affected (0.08 sec)
10. mysql>

It will look like this:


Step 4: In final step you need to create few data records in Students table as shown
below:

1. mysql> INSERT INTO Students VALUES (150, 'Nakul', 'Jain', 22);


2. Query OK, 1 row affected (0.05 sec)
3.
4. mysql> INSERT INTO Students VALUES (151, 'Ramesh', 'Kumar', 20);
5. Query OK, 1 row affected (0.00 sec)
6.
7. mysql> INSERT INTO Students VALUES (152, 'Ajeet', 'Singhal', 22);
8. Query OK, 1 row affected (0.00 sec)
9.
10. mysql> INSERT INTO Students VALUES (153, 'Hamza', 'Hussain', 22);
11. Query OK, 1 row affected (0.00 sec)
12.
13. mysql>

It will look like this:


Let's see the simple JSP example to understand the use of <sql:update> tag is:

1. <%@ page import="java.io.*,java.util.*,java.sql.*"%>


2. <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
4. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
5.
6. <html>
7. <head>
8. <title>sql:update Tag</title>
9. </head>
10. <body>
11.
12. <sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
13. url="jdbc:mysql://localhost/test"
14. user="root" password="1234"/>
15. <sql:update dataSource="${db}" var="count">
16. INSERT INTO Students VALUES (154,'Nasreen', 'jaha', 25);
17. </sql:update>
18.
19. <sql:query dataSource="${db}" var="rs">
20. SELECT * from Students;
21. </sql:query>
22.
23. <table border="2" width="100%">
24. <tr>
25. <th>Student ID</th>
26. <th>First Name</th>
27. <th>Last Name</th>
28. <th>Age</th>
29. </tr>
30. <c:forEach var="table" items="${rs.rows}">
31. <tr>
32. <td><c:out value="${table.id}"/></td>
33. <td><c:out value="${table.First_Name}"/></td>
34. <td><c:out value="${table.Last_Name}"/></td>
35. <td><c:out value="${table.Age}"/></td>
36. </tr>
37. </c:forEach>
38. </table>
39.
40. </body>
41. </html>

This will produce the following result:


JSTL SQL <sql:param> Tag
The <sql:param> tag sets the parameter value in SQL statement.

It is used as nested tag for <sql:update> and <sql:query> to provide the value in SQL query
parameter. If null value is provided, the value is set at SQL NULL for value attribute.

Example:

1. <c:set var="StudentId" value="152"/>


2. <sql:update dataSource="${db}" var="count">
3. DELETE FROM Students WHERE Id = ?
4. <sql:param value="${StudentId}" />
5. </sql:update>

JSTL SQL <sql:param> Complete Example


Consider the below information about your MySQL database setup:

o We are using the JDBC MySQL driver


o We are using the test database on local machine
o We are using the "root" as username and "1234" as password to access the
test database.

To understand the basic concept, let us create a simple table Students in the test
database and creates the few records in that table using command prompts as
follows:

Step-1: Open the command prompt and change to the installation directory as
follows:

1. C:\Users\javatpoint>
2. C:\Users\javatpoint>cd C:\Program Files\MySQL\MySQL Server 5.7\bin
3. C:\Program Files\MySQL\MySQL Server 5.7\bin>

It will look like this:


Step-2: Login to the database using command prompt as shown below:

1. C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p


2. Enter password: ****
3. mysql>

It will look like this:

Step-3: Create the table Students in test database as shown below:

1. mysql> use test;


2. mysql> create table Students
3. (
4. id int not null,
5. First_Name varchar (255),
6. Last_Name varchar (255),
7. Age int not null
8. );
9. Query OK, 0 rows affected (0.08 sec)
10. mysql>

It will look like this:

Step 4: In final step you need to create few data records in Students table as shown
below:

1. mysql> INSERT INTO Students VALUES (150, 'Nakul', 'Jain', 22);


2. Query OK, 1 row affected (0.05 sec)
3.
4. mysql> INSERT INTO Students VALUES (151, 'Ramesh', 'Kumar', 20);
5. Query OK, 1 row affected (0.00 sec)
6.
7. mysql> INSERT INTO Students VALUES (152, 'Ajeet', 'Singhal', 22);
8. Query OK, 1 row affected (0.00 sec)
9.
10. mysql> INSERT INTO Students VALUES (153, 'Hamza', 'Hussain', 22);
11. Query OK, 1 row affected (0.00 sec)
12.
13. mysql>

It will look like this:


Let's see the simple JSP example to understand the use of < sql:param > tag is:

1. <%@ page import="java.io.*,java.util.*,java.sql.*"%>


2. <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
4. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
5.
6. <html>
7. <head>
8. <title>sql:update Tag</title>
9. </head>
10. <body>
11. <sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
12. url="jdbc:mysql://localhost/test"
13. user="root" password="1234"/>
14. <c:set var="StudentId" value="152"/>
15. <sql:update dataSource="${db}" var="count">
16. DELETE FROM Students WHERE Id = ?
17. <sql:param value="${StudentId}" />
18. </sql:update>
19.
20. <sql:query dataSource="${db}" var="rs">
21. SELECT * from Students;
22. </sql:query>
23. <table border="2" width="100%">
24. <tr>
25. <th>Student ID</th>
26. <th>First Name</th>
27. <th>Last Name</th>
28. <th>Age</th>
29. </tr>
30. <c:forEach var="table" items="${rs.rows}">
31. <tr>
32. <td><c:out value="${table.id}"/></td>
33. <td><c:out value="${table.First_Name}"/></td>
34. <td><c:out value="${table.Last_Name}"/></td>
35. <td><c:out value="${table.Age}"/></td>
36. </tr>
37. </c:forEach>
38. </table>
39.
40. </body>
41. </html>

This will produce the following result:


JSTL SQL <sql:dateParam> Tag
The <sql:dateParam> is used to set the specified date for SQL query parameter.

It is used as nested tag for <sql:update> and <sql:query> to provide the date and
time value for SQL query parameter. If null value is provided, the value is set at SQL
NULL.

Example:

1. <%
2. Date DoB = new Date("2000/10/16");
3. int studentId = 151;
4. %>
5. <sql:update dataSource="${db}" var="count">
6. UPDATE Student SET dob = ? WHERE Id = ?
7. <sql:dateParam value="<%=DoB%>" type="DATE" />
8. <sql:param value="<%=studentId%>" />
9. </sql:update>

JSTL SQL <sql:dateParam> Complete


Example
Consider the below information about your MySQL database setup:

JSTL SQL <sql:dateParam> Tag


The <sql:dateParam> is used to set the specified date for SQL query parameter.

It is used as nested tag for <sql:update> and <sql:query> to provide the date and
time value for SQL query parameter. If null value is provided, the value is set at SQL
NULL.

Example:

1. <%
2. Date DoB = new Date("2000/10/16");
3. int studentId = 151;
4. %>
5. <sql:update dataSource="${db}" var="count">
6. UPDATE Student SET dob = ? WHERE Id = ?
7. <sql:dateParam value="<%=DoB%>" type="DATE" />
8. <sql:param value="<%=studentId%>" />
9. </sql:update>
JSTL SQL <sql:dateParam> Complete
Example
Consider the below information about your MySQL database setup:

o We are using the JDBC MySQL driver


o We are using the test database on local machine
o We are using the "root" as username and "1234" as password to access the
test database.

To understand the basic concept, let us create a simple table Student in the test
database and creates the few records in that table using command prompts as
follows:

Step-1: Open the command prompt and change to the installation directory as
follows:

1. C:\Users\javatpoint>
2. C:\Users\javatpoint>cd C:\Program Files\MySQL\MySQL Server 5.7\bin
3. C:\Program Files\MySQL\MySQL Server 5.7\bin>

It will look like this:

Step-2: Login to the database using command prompt as shown below:

1. C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p


2. Enter password: ****
3. mysql>

It will look like this:


Step-3: Create the table Students in test database as shown below:

1. mysql> use test;


2. mysql> create table Student
3. (
4. id int not null,
5. First_Name varchar (255),
6. Last_Name varchar (255),
7. dob date
8. );
9. Query OK, 0 rows affected (0.08 sec)
10. mysql>

It will look like this:


Step 4: In final step you need to create few data records in Students table as shown
below:

1. mysql> INSERT INTO student VALUES (150, 'Nakul', 'Jain', '1994/07/19' );


2. Query OK, 1 row affected (0.05 sec)
3.
4. mysql> INSERT INTO Student VALUES (151, 'Ramesh', 'Kumar', '1992/03/9');
5. Query OK, 1 row affected (0.00 sec)
6.
7. mysql> INSERT INTO Student VALUES (152, 'Ajeet', 'Singhal', '1992/01/23' );
8. Query OK, 1 row affected (0.00 sec)
9.
10. mysql> INSERT INTO Student VALUES (153, 'Hamza', 'Hussain', '1992/01/9');
11. Query OK, 1 row affected (0.00 sec)
12.
13. mysql>

It will look like this:

Let's see the simple JSP example to understand the use of <sql:dateParam> tag:

1. <%@ page import="java.io.*,java.util.*,java.sql.*"%>


2. <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
3. <%@ page import="java.util.Date,java.text.*" %>
4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
5. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
6.
7. <html>
8. <head>
9. <title>sql:dateParam Tag</title>
10. </head>
11. <body>
12.
13. <sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
14. url="jdbc:mysql://localhost/test"
15. user="root" password="1234"/>
16.
17. <%
18. Date DoB = new Date("2000/10/16");
19. int studentId = 151;
20. %>
21.
22. <sql:update dataSource="${db}" var="count">
23. UPDATE Student SET dob = ? WHERE Id = ?
24. <sql:dateParam value="<%=DoB%>" type="DATE" />
25. <sql:param value="<%=studentId%>" />
26. </sql:update>
27.
28. <sql:query dataSource="${db}" var="rs">
29. SELECT * from Student;
30. </sql:query>
31.
32. <table border="2" width="100%">
33. <tr>
34. <th>Emp ID</th>
35. <th>First Name</th>
36. <th>Last Name</th>
37. <th>DoB</th>
38. </tr>
39. <c:forEach var="table" items="${rs.rows}">
40. <tr>
41. <td><c:out value="${table.id}"/></td>
42. <td><c:out value="${table.First_Name}"/></td>
43. <td><c:out value="${table.Last_Name}"/></td>
44. <td><c:out value="${table.dob}"/></td>
45. </tr>
46. </c:forEach>
47. </table>
48.
49. </body>
50. </html>

Output:
JSTL SQL <sql:transaction> Tag
The <sql:transaction> tag is used for transaction management. It is used to group
multiple <sql:update> into common transaction. If you group multiple SQL queries in
a single transaction, database is hit only once.

It is used for ensuring that the database modifications are performed by the nested
actions which can be either rolled back or committed.

Example:

1. <%
2. Date DoB = new Date("2000/10/16");
3. int studentId = 151;
4. %>
5. <sql:transaction dataSource="${db}">
6. <sql:update var="count">
7. UPDATE Student SET First_Name = 'Suraj' WHERE Id = 150
8. </sql:update>
9. <sql:update var="count">
10. UPDATE Student SET Last_Name= 'Saifi' WHERE Id = 153
11. </sql:update>
12. <sql:update var="count">
13. INSERT INTO Student
14. VALUES (154,'Supriya', 'Jaiswal', '1995/10/6');
15. </sql:update>
16. </sql:transaction>

JSTL SQL <sql:transaction> Complete


Example
Consider the below information about your MySQL database setup:

o We are using the JDBC MySQL driver


o We are using the test database on local machine
o We are using the "root" as username and "1234" as password to access the
test database.

To understand the basic concept, let us create a simple table Student in the test
database and creates the few records in that table using command prompts as
follows:

Step-1: Open the command prompt and change to the installation directory as
follows:
1. C:\Users\javatpoint>
2. C:\Users\javatpoint>cd C:\Program Files\MySQL\MySQL Server 5.7\bin
3. C:\Program Files\MySQL\MySQL Server 5.7\bin>
4. C:\Users\javatpoint>
5. C:\Users\javatpoint>cd C:\Program Files\MySQL\MySQL Server 5.7\bin
6. C:\Program Files\MySQL\MySQL Server 5.7\bin>

Step-2: Login to the database using command prompt as shown below:

1. C:\Program Files\MySQL\MySQL Server 5.7\bin>mysql -u root -p


2. Enter password: ****
3. mysql>

It will look like this:

Step-3: Create the table Students in test database as shown below:/p>


1. mysql> use test;
2. mysql> create table Student
3. (
4. id int not null,
5. First_Name varchar (255),
6. Last_Name varchar (255),
7. dob date
8. );
9. Query OK, 0 rows affected (0.08 sec)
10. mysql>

It will look like this:

Step 4: In final step you need to create few data records in Students table as shown
below:

1. mysql> INSERT INTO student VALUES (150, 'Nakul', 'Jain', '1994/07/19' );


2. Query OK, 1 row affected (0.05 sec)
3.
4. mysql> INSERT INTO Student VALUES (151, 'Simran', 'Kumar', '1992/03/9');
5. Query OK, 1 row affected (0.00 sec)
6.
7. mysql> INSERT INTO Student VALUES (152, 'Ajeet', 'Singhal', '1992/01/23' );
8. Query OK, 1 row affected (0.00 sec)
9.
10. mysql> INSERT INTO Student VALUES (153, 'Hamza', 'Hussain', '1992/01/9');
11. Query OK, 1 row affected (0.00 sec)
12.
13. mysql>
It will look like this:

Let's see the simple JSP example to understand the use of <sql:transaction> tag:

1. <%@ page import="java.io.*,java.util.*,java.sql.*"%>


2. <%@ page import="javax.servlet.http.*,javax.servlet.*" %>
3. <%@ page import="java.util.Date,java.text.*" %>
4. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
5. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
6.
7. <html>
8. <head>
9. <title>sql:transaction Tag</title>
10. </head>
11. <body>
12.
13. <sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
14. url="jdbc:mysql://localhost/test"
15. user="root" password="1234"/>
16.
17. <%
18. Date DoB = new Date("2000/10/16");
19. int studentId = 151;
20. %>
21.
22. <sql:transaction dataSource="${db}">
23. <sql:update var="count">
24. UPDATE Student SET First_Name = 'Suraj' WHERE Id = 150
25. </sql:update>
26. <sql:update var="count">
27. UPDATE Student SET Last_Name= 'Saifi' WHERE Id = 153
28. </sql:update>
29. <sql:update var="count">
30. INSERT INTO Student
31. VALUES (154,'Supriya', 'Jaiswal', '1995/10/6');
32. </sql:update>
33. </sql:transaction>
34.
35. <sql:query dataSource="${db}" var="rs">
36. SELECT * from Student;
37. </sql:query>
38.
39. <table border="2" width="100%">
40. <tr>
41. <th>Emp ID</th>
42. <th>First Name</th>
43. <th>Last Name</th>
44. <th>DoB</th>
45. </tr>
46. <c:forEach var="table" items="${rs.rows}">
47. <tr>
48. <td><c:out value="${table.id}"/></td>
49. <td><c:out value="${table.First_Name}"/></td>
50. <td><c:out value="${table.Last_Name}"/></td>
51. <td><c:out value="${table.dob}"/></td>
52. </tr>
53. </c:forEach>
54. </table>
55.
56. </body>
57. </html>

Output:
Custom Tags in JSP
1. Custom Tags in JSP
2. Advantages of Custom Tags
3. Syntax to use custom tag
4. JSP Custom Tag API
1. JspTag interface
2. Tag interface
3. IteratorTag interface
4. TagSupport class

Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag
and separates the business logic from the JSP page.

The same business logic can be used many times by the use of custom tag.

Advantages of Custom Tags

The key advantages of Custom tags are as follows:

1. Eliminates the need of scriptlet tag The custom tags eliminates the need of
scriptlet tag which is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the
business logic from the JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same
business logic again and again.

Syntax to use custom tag

There are two ways to use the custom tag. They are given below:

1. <prefix:tagname attr1=value1....attrn=valuen />

1. <prefix:tagname attr1=value1....attrn=valuen >


2. body code
3. </prefix:tagname>

4. JSP Custom Tag API


5. The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom
tag API. The JspTag is the root interface in the Custom Tag hierarchy.
6.

7.

8. JspTag interface
9. The JspTag is the root interface for all the interfaces and classes used in custom tag. It
is a marker interface.
10.

11. Tag interface


12. The Tag interface is the sub interface of JspTag interface. It provides methods to
perform action at the start and end of the tag.
13. Fields of Tag interface
14. There are four fields defined in the Tag interface. They are:

Field Name Description

public static int EVAL_BODY_INCLUDE it evaluates the body content.

public static int EVAL_PAGE it evaluates the JSP page content after the custom tag

public static int SKIP_BODY it skips the body content of the tag.

public static int SKIP_PAGE it skips the JSP page content after the custom tag.

15. Methods of Tag interface


16. The methods of the Tag interface are as follows:

Method Name Description


public void it sets the given PageContext object.
setPageContext(PageContext pc)

public void setParent(Tag t) it sets the parent of the tag handler.

public Tag getParent() it returns the parent tag handler object.

public int doStartTag()throws it is invoked by the JSP page implementation object. The
JspException programmer should override this method and define
business logic to be performed at the start of the tag.

public int doEndTag()throws it is invoked by the JSP page implementation object. The
JspException programmer should override this method and define
business logic to be performed at the end of the tag.

public void release() it is invoked by the JSP page implementation object to rele
the state.
17.
18. IterationTag interface
19. The IterationTag interface is the sub interface of the Tag interface. It provides
an additional method to reevaluate the body.

Field of IterationTag interface

There is only one field defined in the IterationTag interface.

o public static int EVAL_BODY_AGAIN it reevaluates the body content.

Method of Tag interface

There is only one method defined in the IterationTag interface.


Example of JSP Custom Tag
1. Example of JSP Custom Tag
1. Create the Tag handler class
2. Create the TLD file
3. Create the JSP file

In this example, we are going to create a custom tag that prints the current date
and time. We are performing action at the start of tag.

For creating any custom tag, we need to follow following steps:

1. Create the Tag handler class and perform action at the start or at the end of
the tag.
2. Create the Tag Library Descriptor (TLD) file and define tags
3. Create the JSP file that uses the Custom tag defined in the TLD file

Understanding flow of custom tag in jsp

1) Create the Tag handler class

To create the Tag Handler, we are inheriting the TagSupport class and overriding its
method doStartTag().To write data for the jsp, we need to use the JspWriter class.

The PageContext class provides getOut() method that returns the instance of
JspWriter class. TagSupport class provides instance of pageContext bydefault.

File: MyTagHandler.java
1. package com.javatpoint.sonoo;
2. import java.util.Calendar;
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6. public class MyTagHandler extends TagSupport{
7.
8. public int doStartTag() throws JspException {
9. JspWriter out=pageContext.getOut();//returns the instance of JspWriter
10. try{
11. out.print(Calendar.getInstance().getTime());//printing date and time using J
spWriter
12. }catch(Exception e){System.out.println(e);}
13. return SKIP_BODY;//will not evaluate the body content of the tag
14. }
15. }

2) Create the TLD file

Tag Library Descriptor (TLD) file contains information of tag and Tag Hander
classes. It must be contained inside the WEB-INF directory.

File: mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7.
8. <tlib-version>1.0</tlib-version>
9. <jsp-version>1.2</jsp-version>
10. <short-name>simple</short-name>
11. <uri>http://tomcat.apache.org/example-taglib</uri>
12.
13. <tag>
14. <name>today</name>
15. <tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
16. </tag>
17. </taglib>

3) Create the JSP file


Let's use the tag in our jsp file. Here, we are specifying the path of tld file directly. But
it is recommended to use the uri name instead of full path of tld file. We will learn
about uri later.

It uses taglib directive to use the tags defined in the tld file.

File: index.jsp
1. <%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
2. Current Date and Time is: <m:today/>
download this example

Output
Attributes in JSP Custom Tag
1. Attributes in JSP Custom Tag
2. Example to use attribute in JSP Custom Tag

There can be defined too many attributes for any custom tag. To define the attribute,
you need to perform two task

o Define the property in the TagHandler class with the attribute name and
define the setter method
o define the attribute element inside the tag element in the TLD file

Let's understand the attribute by the tag given below:

1. <m:cube number="4"></m:cube>

Here m is the prefix, cube is the tag name and number is the attribute.

Simple example of attribute in JSP Custom Tag


In this example, we are going to use the cube tag which return the cube of any given
number. Here, we are defining the number attribute for the cube tag. We are using
the three file here:

o index.jsp
o CubeNumber.java
o mytags.tld

index.jsp
1. <%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
2. Cube of 4 is: <m:cube number="4"></m:cube>
CubeNumber.java
1. package com.javatpoint.taghandler;
2. import javax.servlet.jsp.JspException;
3. import javax.servlet.jsp.JspWriter;
4. import javax.servlet.jsp.tagext.TagSupport;
5.
6. public class CubeNumber extends TagSupport{
7. private int number;
8.
9. public void setNumber(int number) {
10. this.number = number;
11. }
12.
13. public int doStartTag() throws JspException {
14. JspWriter out=pageContext.getOut();
15. try{
16. out.print(number*number*number);
17. }catch(Exception e){e.printStackTrace();}
18.
19. return SKIP_BODY;
20. }
21. }
mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>http://tomcat.apache.org/example-taglib</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>cube</name>
15. <tag-class>com.javatpoint.taghandler.CubeNumber</tag-class>
16. <attribute>
17. <name>number</name>
18. <required>true</required>
19. </attribute>
20. </tag>
21. </taglib>

Output
1. Cube of 4 is: 64

JSP Custom Tag attribute example with


database
Let's create a custom tag that prints a particular record of table for the given table
name and id.

So, you have to have two properties in the tag handler class.

PrintRecord.java

1. package com.javatpoint;
2. import javax.servlet.jsp.JspException;
3. import javax.servlet.jsp.JspWriter;
4. import javax.servlet.jsp.tagext.TagSupport;
5. import java.sql.*;
6.
7. public class PrintRecord extends TagSupport{
8. private String id;
9. private String table;
10.
11. public void setId(String id) {
12. this.id = id;
13. }
14. public void setTable(String table) {
15. this.table = table;
16. }
17.
18. public int doStartTag()throws JspException{
19. JspWriter out=pageContext.getOut();
20. try{
21. Class.forName("oracle.jdbc.driver.OracleDriver");
22. Connection con=DriverManager.getConnection(
23. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
24. PreparedStatement ps=con.prepareStatement("select * from "+table+" where id
=?");
25. ps.setInt(1,Integer.parseInt(id));
26. ResultSet rs=ps.executeQuery();
27. if(rs!=null){
28. ResultSetMetaData rsmd=rs.getMetaData();
29. int totalcols=rsmd.getColumnCount();
30. //column name
31. out.write("<table border='1'>");
32. out.write("<tr>");
33. for(int i=1;i<=totalcols;i++){
34. out.write("<th>"+rsmd.getColumnName(i)+"</th>");
35. }
36. out.write("</tr>");
37. //column value
38.
39. if(rs.next()){
40. out.write("<tr>");
41. for(int i=1;i<=totalcols;i++){
42. out.write("<td>"+rs.getString(i)+"</td>");
43. }
44. out.write("</tr>");
45.
46. }else{
47. out.write("Table or Id doesn't exist");
48. }
49. out.write("</table>");
50.
51. }
52. con.close();
53. }catch(Exception e){System.out.println(e);}
54. return SKIP_BODY;
55. }
56. }
m.tld

1. <?xml version="1.0" encoding="ISO-8859-1" ?>


2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7.
8. <tlib-version>1.2</tlib-version>
9. <jsp-version>2.0</jsp-version>
10. <short-name>c</short-name>
11. <uri>javatpoint</uri>
12.
13. <tag>
14. <name>printRecord</name>
15. <tag-class>com.javatpoint.PrintRecord</tag-class>
16. <attribute>
17. <name>id</name>
18. <required>true</required>
19. </attribute>
20. <attribute>
21. <name>table</name>
22. <required>true</required>
23. </attribute>
24.
25. </tag>
26. </taglib>
index.jsp

1. <%@ taglib uri="javatpoint" prefix="j" %>


2. <j:printRecord table="user874" id="1"></j:printRecord>

Output
Iteration using JSP Custom Tag
1. Iteration using JSP Custom Tag
2. Example of Iteration using JSP Custom Tag

We can iterate the body content of any tag using the doAfterBody() method
of IterationTag interface.

Here we are going to use the TagSupport class which implements the IterationTag
interface. For iterating the body content, we need to use
the EVAL_BODY_AGAIN constant in the doAfterBody() method.

Example of Iteration using JSP Custom Tag


In this example, we are going to use the attribute in the custom tag, which returns
the power of any given number. We have created three files here

o index.jsp
o PowerNumber.java
o mytags.tld

index.jsp
1. <%@ taglib uri="WEB-INF/mytags.tld" prefix="m" %>
2.
3. 3 ^ 5 = <m:power number="3" power="5">
4. body
5. </m:power>

PowerNumber.java
1. package com.javatpoint.taghandler;
2.
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6.
7. public class PowerNumber extends TagSupport{
8. private int number;
9. private int power;
10. private static int counter;
11. private static int result=1;
12.
13. public void setPower(int power) {
14. this.power = power;
15. }
16.
17. public void setNumber(int number) {
18. this.number = number;
19. }
20.
21. public int doStartTag() throws JspException {
22. return EVAL_BODY_INCLUDE;
23. }
24.
25. public int doAfterBody() {
26. counter++;
27. result *= number;
28. if (counter==power)
29. return SKIP_BODY;
30. else
31. return EVAL_BODY_AGAIN;
32. }
33.
34. public int doEndTag() throws JspException {
35. JspWriter out=pageContext.getOut();
36. try{
37. out.print(result);
38. }catch(Exception e){e.printStackTrace();}
39.
40. return EVAL_PAGE;
41. }
42. }

mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>http://tomcat.apache.org/example-taglib</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>power</name>
15. <tag-class>com.javatpoint.taghandler.PowerNumber</tag-class>
16.
17. <attribute>
18. <name>number</name>
19. <required>true</required>
20. </attribute>
21.
22. <attribute>
23. <name>power</name>
24. <required>true</required>
25. </attribute>
26.
27. </tag>
28. </taglib>

Looping using Iteration Tag (creating tag for loop)


Let's create a loop tag that iterates the body content of this tag.

File: index.jsp
1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://
www.w3.org/TR/html4/loose.dtd">
2. <html>
3. <head>
4. <title>Insert title here</title>
5. </head>
6. <body>
7.
8. <%@taglib prefix="m" uri="sssuri" %>
9. <m:loop end="5" start="1">
10. <p>My Name is khan</p>
11. </m:loop>
12.
13. </body>
14. </html>
File: mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5. <taglib>
6. <tlib-version>1.0</tlib-version>
7. <jsp-version>1.2</jsp-version>
8. <short-name>abc</short-name>
9.
10. <uri>sssuri</uri>
11. <tag>
12. <name>loop</name>
13. <tag-class>com.javatpoint.customtag.Loop</tag-class>
14.
15. <attribute>
16. <name>start</name>
17. <required>true</required>
18. </attribute>
19.
20. <attribute>
21. <name>end</name>
22. <required>true</required>
23. </attribute>
24. </tag>
25.
26. </taglib>
File: Loop.java
1. package com.javatpoint.customtag;
2. import javax.servlet.jsp.JspException;
3. import javax.servlet.jsp.tagext.TagSupport;
4.
5. public class Loop extends TagSupport{
6. private int start=0;
7. private int end=0;
8.
9. public void setStart(int start) {
10. this.start = start;
11. }
12. public void setEnd(int end) {
13. this.end = end;
14. }
15.
16. @Override
17. public int doStartTag() throws JspException {
18. return EVAL_BODY_INCLUDE;
19. }
20.
21. @Override
22. public int doAfterBody() throws JspException {
23. if(start<end){
24. start++;
25. return EVAL_BODY_AGAIN;
26. }else{
27. return SKIP_BODY;
28. }
29.
30. }
31.
32.
33. }
File: web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmln
s="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/
ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/
ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" i
d="WebApp_ID" version="3.0">
3.
4. <jsp-config>
5. <taglib>
6. <taglib-uri>sssuri</taglib-uri>
7. <taglib-location>/WEB-INF/mytags.tld</taglib-location>
8. </taglib>
9. </jsp-config>
10.
11. </web-app>

Output
Custom URI in JSP Custom Tag
1. Custom URI in JSP Custom Tag
2. Example to use Custom URI in JSP Custom Tag

We can use the custom URI, to tell the web container about the tld file. In such case,
we need to define the taglib element in the web.xml. The web container gets the
information about the tld file from the web.xml file for the specified URI.

Example to use custom URI in JSP Custom Tag


In this example, we are going to use the custom uri in the JSP file. For this
application, we need to focus on 4 files.

o index.jsp
o web.xml
o mytags.tld
o PrintDate.java

index.jsp
1. <%@ taglib uri="mytags" prefix="m" %>
2. Today is: <m:today></m:today>

web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <!DOCTYPE web-app
3. PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
4. "http://java.sun.com/dtd/web-app_2_3.dtd">
5.
6. <web-app>
7.
8. <jsp-config>
9. <taglib>
10. <taglib-uri>mytags</taglib-uri>
11. <taglib-location>/WEB-INF/mytags.tld</taglib-location>
12. </taglib>
13. </jsp-config>
14.
15. </web-app>

mytags.tld
1. <?xml version="1.0" encoding="ISO-8859-1" ?>
2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>mytags</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>today</name>
15. <tag-class>com.javatpoint.taghandler.PrintDate</tag-class>
16. </tag>
17. </taglib>
PrintDate.java
1. package com.javatpoint.taghandler;
2.
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6.
7. public class PrintDate extends TagSupport{
8.
9. public int doStartTag() throws JspException {
10. JspWriter out=pageContext.getOut();
11. try{
12. out.print(java.util.Calendar.getInstance().getTime());
13. }catch(Exception e){e.printStackTrace();}
14.
15. return SKIP_BODY;
16. }
17.
18.
19. }
JSP CRUD Example
We can easily create CRUD Example in JSP. Here, we are using DAO files for database
and JSTL for traversing records.

Download jstl.jar and mysql-connector.jar


Download jstl1.2.jar file
Download mysql-connector.jar

Download SQL File to Import in MySQL


Download SQL File

Download Project
download CRUD project in JSP

CRUD Example
Directory Structure in Eclipse
index.jsp

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
5. <title>JSP CRUD Example</title>
6. </head>
7. <body>
8. <h1>JSP CRUD Example</h1>
9. <a href="adduserform.jsp">Add User</a>
10. <a href="viewusers.jsp">View Users</a>
11.
12. </body>
13. </html>
adduserform.jsp

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
5. <title>Add User Form</title>
6. </head>
7. <body>
8.
9. <jsp:include page="userform.html"></jsp:include>
10.
11. </body>
12. </html>
userform.html

1. <a href="viewusers.jsp">View All Records</a><br/>


2.
3. <h1>Add New User</h1>
4. <form action="adduser.jsp" method="post">
5. <table>
6. <tr><td>Name:</td><td><input type="text" name="name"/></td></tr>
7. <tr><td>Password:</td><td>
8. <input type="password" name="password"/></td></tr>
9. <tr><td>Email:</td><td><input type="email" name="email"/></td></
tr>
10. <tr><td>Sex:</td><td>
11. <input type="radio" name="sex" value="male"/>Male
12. <input type="radio" name="sex" value="female"/>Female </td></tr>
13. <tr><td>Country:</td><td>
14. <select name="country" style="width:155px">
15. <option>India</option>
16. <option>Pakistan</option>
17. <option>Afghanistan</option>
18. <option>Berma</option>
19. <option>Other</option>
20. </select>
21. </td></tr>
22. <tr><td colspan="2"><input type="submit" value="Add User"/></td></tr>
23. </table>
24. </form>
adduser.jsp

1. <%@page import="com.javatpoint.dao.UserDao"%>
2. <jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
3. <jsp:setProperty property="*" name="u"/>
4.
5. <%
6. int i=UserDao.save(u);
7. if(i>0){
8. response.sendRedirect("adduser-success.jsp");
9. }else{
10. response.sendRedirect("adduser-error.jsp");
11. }
12. %>
User.java

1. package com.javatpoint.bean;
2. public class User {
3. private int id;
4. private String name,password,email,sex,country;
5. //generate getters and setters
6. }
UserDao.java

1. package com.javatpoint.dao;
2. import java.sql.*;
3. import java.util.ArrayList;
4. import java.util.List;
5. import com.javatpoint.bean.User;
6. public class UserDao {
7.
8. public static Connection getConnection(){
9. Connection con=null;
10. try{
11. Class.forName("com.mysql.jdbc.Driver");
12. con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
13. }catch(Exception e){System.out.println(e);}
14. return con;
15. }
16. public static int save(User u){
17. int status=0;
18. try{
19. Connection con=getConnection();
20. PreparedStatement ps=con.prepareStatement(
21. "insert into register(name,password,email,sex,country) values(?,?,?,?,?)");
22. ps.setString(1,u.getName());
23. ps.setString(2,u.getPassword());
24. ps.setString(3,u.getEmail());
25. ps.setString(4,u.getSex());
26. ps.setString(5,u.getCountry());
27. status=ps.executeUpdate();
28. }catch(Exception e){System.out.println(e);}
29. return status;
30. }
31. public static int update(User u){
32. int status=0;
33. try{
34. Connection con=getConnection();
35. PreparedStatement ps=con.prepareStatement(
36. "update register set name=?,password=?,email=?,sex=?,country=? where id=?");
37. ps.setString(1,u.getName());
38. ps.setString(2,u.getPassword());
39. ps.setString(3,u.getEmail());
40. ps.setString(4,u.getSex());
41. ps.setString(5,u.getCountry());
42. ps.setInt(6,u.getId());
43. status=ps.executeUpdate();
44. }catch(Exception e){System.out.println(e);}
45. return status;
46. }
47. public static int delete(User u){
48. int status=0;
49. try{
50. Connection con=getConnection();
51. PreparedStatement ps=con.prepareStatement("delete from register wher
e id=?");
52. ps.setInt(1,u.getId());
53. status=ps.executeUpdate();
54. }catch(Exception e){System.out.println(e);}
55.
56. return status;
57. }
58. public static List<User> getAllRecords(){
59. List<User> list=new ArrayList<User>();
60.
61. try{
62. Connection con=getConnection();
63. PreparedStatement ps=con.prepareStatement("select * from register");
64. ResultSet rs=ps.executeQuery();
65. while(rs.next()){
66. User u=new User();
67. u.setId(rs.getInt("id"));
68. u.setName(rs.getString("name"));
69. u.setPassword(rs.getString("password"));
70. u.setEmail(rs.getString("email"));
71. u.setSex(rs.getString("sex"));
72. u.setCountry(rs.getString("country"));
73. list.add(u);
74. }
75. }catch(Exception e){System.out.println(e);}
76. return list;
77. }
78. public static User getRecordById(int id){
79. User u=null;
80. try{
81. Connection con=getConnection();
82. PreparedStatement ps=con.prepareStatement("select * from register where id=?"
);
83. ps.setInt(1,id);
84. ResultSet rs=ps.executeQuery();
85. while(rs.next()){
86. u=new User();
87. u.setId(rs.getInt("id"));
88. u.setName(rs.getString("name"));
89. u.setPassword(rs.getString("password"));
90. u.setEmail(rs.getString("email"));
91. u.setSex(rs.getString("sex"));
92. u.setCountry(rs.getString("country"));
93. }
94. }catch(Exception e){System.out.println(e);}
95. return u;
96. }
97. }
adduser-success.jsp

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
5. <title>Add User Success</title>
6. </head>
7. <body>
8.
9. <p>Record successfully saved!</p>
10. <jsp:include page="userform.html"></jsp:include>
11.
12. </body>
13. </html>
adduser-error.jsp

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
5. <title>Add User Error</title>
6. </head>
7. <body>
8.
9. <p>Sorry, an error occurred!</p>
10. <jsp:include page="userform.html"></jsp:include>
11.
12. </body>
13. </html>
viewusers.jsp

1. <!DOCTYPE html>
2.
3. <html>
4. <head>
5. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
6. <title>View Users</title>
7. </head>
8. <body>
9.
10. <%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.*,java.util.*"%>
11. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
12.
13. <h1>Users List</h1>
14.
15. <%
16. List<User> list=UserDao.getAllRecords();
17. request.setAttribute("list",list);
18. %>
19.
20. <table border="1" width="90%">
21. <tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th>
22. <th>Sex</th><th>Country</th><th>Edit</th><th>Delete</th></tr>
23. <c:forEach items="${list}" var="u">
24. <tr><td>${u.getId()}</td><td>${u.getName()}</td><td>${u.getPassword()}</td>

25. <td>${u.getEmail()}</td><td>${u.getSex()}</td><td>${u.getCountry()}</
td>
26. <td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>
27. <td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td></tr>
28. </c:forEach>
29. </table>
30. <br/><a href="adduserform.jsp">Add New User</a>
31.
32. </body>
33. </html>
editform.jsp

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
5. <title>Edit Form</title>
6. </head>
7. <body>
8. <%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.User"%>
9.
10. <%
11. String id=request.getParameter("id");
12. User u=UserDao.getRecordById(Integer.parseInt(id));
13. %>
14.
15. <h1>Edit Form</h1>
16. <form action="edituser.jsp" method="post">
17. <input type="hidden" name="id" value="<%=u.getId() %>"/>
18. <table>
19. <tr><td>Name:</td><td>
20. <input type="text" name="name" value="<%= u.getName()%>"/></td></tr>
21. <tr><td>Password:</td><td>
22. <input type="password" name="password" value="<%= u.getPassword()%>"/></
td></tr>
23. <tr><td>Email:</td><td>
24. <input type="email" name="email" value="<%= u.getEmail()%>"/></td></tr>
25. <tr><td>Sex:</td><td>
26. <input type="radio" name="sex" value="male"/>Male
27. <input type="radio" name="sex" value="female"/>Female </td></tr>
28. <tr><td>Country:</td><td>
29. <select name="country">
30. <option>India</option>
31. <option>Pakistan</option>
32. <option>Afghanistan</option>
33. <option>Berma</option>
34. <option>Other</option>
35. </select>
36. </td></tr>
37. <tr><td colspan="2"><input type="submit" value="Edit User"/></td></
tr>
38. </table>
39. </form>
40.
41. </body>
42. </html>
edituser.jsp

1. <%@page import="com.javatpoint.dao.UserDao"%>
2. <jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
3. <jsp:setProperty property="*" name="u"/>
4. <%
5. int i=UserDao.update(u);
6. response.sendRedirect("viewusers.jsp");
7. %>
deleteuser.jsp

1. <%@page import="com.javatpoint.dao.UserDao"%>
2. <jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>
3. <jsp:setProperty property="*" name="u"/>
4. <%
5. UserDao.delete(u);
6. response.sendRedirect("viewusers.jsp");
7. %>

Download Project
download CRUD project in JSP

Output
Pagination in JSP
We can create pagination example in JSP easily. It is required if you have to display
many records. Displaying many records in a single page may take time, so it is better
to break the page into parts. To do so, we create pagination application.

In this pagination example, we are using MySQL database to fetch records.

We have created "emp" table in "test" database. The emp table has three fields: id,
name and salary. Either create table and insert records manually or import our sql
file.

index.jsp

1. <a href="view.jsp?page=1">View Employees</a>

view.jsp

1. <%@ page import="java.util.*,com.javatpoint.dao.*,com.javatpoint.beans.*" %


>
2. <%
3. String spageid=request.getParameter("page");
4. int pageid=Integer.parseInt(spageid);
5. int total=5;
6. if(pageid==1){}
7. else{
8. pageid=pageid-1;
9. pageid=pageid*total+1;
10. }
11. List<Emp> list=EmpDao.getRecords(pageid,total);
12.
13. out.print("<h1>Page No: "+spageid+"</h1>");
14. out.print("<table border='1' cellpadding='4' width='60%'>");
15. out.print("<tr><th>Id</th><th>Name</th><th>Salary</th>");
16. for(Emp e:list){
17. out.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td>
18. <td>"+e.getSalary()+"</td></tr>");
19. }
20. out.print("</table>");
21. %>
22. <a href="view.jsp?page=1">1</a>
23. <a href="view.jsp?page=2">2</a>
24. <a href="view.jsp?page=3">3</a>

Emp.java

1. package com.javatpoint.beans;
2.
3. public class Emp {
4. private int id;
5. private String name;
6. private float salary;
7. //getters and setters
8. }

EmpDao.java

1. package com.javatpoint.dao;
2. import com.javatpoint.beans.*;
3. import java.sql.*;
4. import java.util.ArrayList;
5. import java.util.List;
6. public class EmpDao {
7.
8. public static Connection getConnection(){
9. Connection con=null;
10. try{
11. Class.forName("com.mysql.jdbc.Driver");
12. con=DriverManager.getConnection("jdbc:mysql://localhost:3306/
test","","");
13. }catch(Exception e){System.out.println(e);}
14. return con;
15. }
16.
17. public static List<Emp> getRecords(int start,int total){
18. List<Emp> list=new ArrayList<Emp>();
19. try{
20. Connection con=getConnection();
21. PreparedStatement ps=con.prepareStatement(
22. "select * from emp limit "+(start-1)+","+total);
23. ResultSet rs=ps.executeQuery();
24. while(rs.next()){
25. Emp e=new Emp();
26. e.setId(rs.getInt(1));
27. e.setName(rs.getString(2));
28. e.setSalary(rs.getFloat(3));
29. list.add(e);
30. }
31. con.close();
32. }catch(Exception e){System.out.println(e);}
33. return list;
34. }
35. }

SQL File
-- --------------------------------------------------------

--
-- Table structure for table `emp`
--

CREATE TABLE IF NOT EXISTS `emp` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`salary` float NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;

--
-- Dumping data for table `emp`
--

INSERT INTO `emp` (`id`, `name`, `salary`) VALUES


(1, 'Amit', 30000),
(2, 'Ajeet', 40000),
(3, 'James', 50000),
(4, 'Sonoo', 60000),
(5, 'Sarfraz', 70000),
(6, 'Bob', 80000),
(7, 'Rahul', 90000),
(8, 'Rakesh', 25000),
(9, 'Udit', 35000),
(10, 'Jai', 45000),
(11, 'Nikhil', 55000),
(12, 'Somesh', 65000),
(13, 'Rajesh', 75000),
(14, 'Ankit', 85000),
(15, 'Ratan', 95000);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Download mysql-connector.jar file

Download mysql-connector.jar

Output
Registration Form in JSP
1. Registration Form in JSP
2. Example of Registration Form in JSP

For creating registration form, you must have a table in the database. You can write
the database logic in JSP file, but separating it from the JSP page is better approach.
Here, we are going to use DAO, Factory Method, DTO and Singletion design
patterns. There are many files:

o index.jsp for getting the values from the user


o User.java, a bean class that have properties and setter and getter methods.
o process.jsp, a jsp file that processes the request and calls the methods
o Provider.java, an interface that contains many constants like DRIVER_CLASS,
CONNECTION_URL, USERNAME and PASSWORD
o ConnectionProvider.java, a class that returns an object of Connection. It uses
the Singleton and factory method design pattern.
o RegisterDao.java, a DAO class that is responsible to get access to the
database

Example of Registration Form in JSP


In this example, we are using the Oracle10g database to connect with the database. Let's first cr
the table in the Oracle database:
1. CREATE TABLE "USER432"
2. ( "NAME" VARCHAR2(4000),
3. "EMAIL" VARCHAR2(4000),
4. "PASS" VARCHAR2(4000)
5. )
6. /

We have created the table named user432 here.

index.jsp

We are having only three fields here, to make the concept clear and simplify the flow
of the application. You can have other fields also like country, hobby etc. according
to your requirement.

1. <form action="process.jsp">
2. <input type="text" name="uname" value="Name..." onclick="this.value=''"/
><br/>
3. <input type="text" name="uemail" value="Email ID..." onclick="this.value=''"/
><br/>
4. <input type="password" name="upass" value="Password..." onclick="this.val
ue=''"/><br/>
5. <input type="submit" value="register"/>
6. </form>

process.jsp

This jsp file contains all the incoming values to an object of bean class which is
passed as an argument in the register method of the RegisterDao class.

1. <%@page import="bean.RegisterDao"%>
2. <jsp:useBean id="obj" class="bean.User"/>
3.
4. <jsp:setProperty property="*" name="obj"/>
5.
6. <%
7. int status=RegisterDao.register(obj);
8. if(status>0)
9. out.print("You are successfully registered");
10.
11. %>

User.java

It is the bean class that have 3 properties uname, uemail and upass with its setter and getter metho
1. package bean;
2.
3. public class User {
4. private String uname,upass,uemail;
5.
6. public String getUname() {
7. return uname;
8. }
9.
10. public void setUname(String uname) {
11. this.uname = uname;
12. }
13.
14. public String getUpass() {
15. return upass;
16. }
17.
18. public void setUpass(String upass) {
19. this.upass = upass;
20. }
21.
22. public String getUemail() {
23. return uemail;
24. }
25.
26. public void setUemail(String uemail) {
27. this.uemail = uemail;
28. }
29.
30. }

Provider.java

This interface contains four constants that can vary from database to database.

1. package bean;
2.
3. public interface Provider {
4. String DRIVER="oracle.jdbc.driver.OracleDriver";
5. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
6. String USERNAME="system";
7. String PASSWORD="oracle";
8.
9. }

ConnectionProvider.java

This class is responsible to return the object of Connection. Here, driver class is
loaded only once and connection object gets memory only once.

1. package bean;
2. import java.sql.*;
3. import static bean.Provider.*;
4.
5. public class ConnectionProvider {
6. private static Connection con=null;
7. static{
8. try{
9. Class.forName(DRIVER);
10. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWOR
D);
11. }catch(Exception e){}
12. }
13.
14. public static Connection getCon(){
15. return con;
16. }
17.
18. }

RegisterDao.java

This class inserts the values of the bean component into the database.

1. package bean;
2.
3. import java.sql.*;
4.
5. public class RegisterDao {
6.
7. public static int register(User u){
8. int status=0;
9. try{
10. Connection con=ConnectionProvider.getCon();
11. PreparedStatement ps=con.prepareStatement("insert into user432 values(?,?,?)
");
12. ps.setString(1,u.getUname());
13. ps.setString(2,u.getUemail());
14. ps.setString(3,u.getUpass());
15.
16. status=ps.executeUpdate();
17. }catch(Exception e){}
18.
19. return status;
20. }
21.
22. }

Login and Logout Example in JSP


1. Login and Logout Example in JSP
2. Example of Login Form in JSP

In this example of creating login form, we have used the DAO (Data Access Object), Factory met
and DTO (Data Transfer Object) design patterns. There are many files:
o index.jsp it provides three links for login, logout and profile
o login.jsp for getting the values from the user
o loginprocess.jsp, a jsp file that processes the request and calls the methods.
o LoginBean.java, a bean class that have properties and setter and getter methods.
o Provider.java, an interface that contains many constants like DRIVER_CL
CONNECTION_URL, USERNAME and PASSWORD
o ConnectionProvider.java, a class that is responsible to return the object of Connection. It u
the Singleton and factory method design pattern.
o LoginDao.java, a DAO class that verifies the emailId and password from the database.
o logout.jsp it invalidates the session.
o profile.jsp it provides simple message if user is logged in, otherwise forwards the request to
login.jsp page.

In this example, we are using the Oracle10g database to match the emailId and
password with the database. The table name is user432 which have many fields like
name, email, pass etc. You may use this query to create the table:

1. CREATE TABLE "USER432"


2. ( "NAME" VARCHAR2(4000),
3. "EMAIL" VARCHAR2(4000),
4. "PASS" VARCHAR2(4000)
5. )
6. /

We assume that there are many records in this table.

index.jsp

It simply provides three links for login, logout and profile.

1. <a href="login.jsp">login</a>|
2. <a href="logout.jsp">logout</a>|
3. <a href="profile.jsp">profile</a>
login.jsp

This file creates a login form for two input fields name and password. It is the simple
login form, you can change it for better look and feel. We are focusing on the
concept only.

1. <%@ include file="index.jsp" %>


2. <hr/>
3.
4. <h3>Login Form</h3>
5. <%
6. String profile_msg=(String)request.getAttribute("profile_msg");
7. if(profile_msg!=null){
8. out.print(profile_msg);
9. }
10. String login_msg=(String)request.getAttribute("login_msg");
11. if(login_msg!=null){
12. out.print(login_msg);
13. }
14. %>
15. <br/>
16. <form action="loginprocess.jsp" method="post">
17. Email:<input type="text" name="email"/><br/><br/>
18. Password:<input type="password" name="password"/><br/><br/>
19. <input type="submit" value="login"/>"
20. </form>

loginprocess.jsp

This jsp file contains all the incoming values to an object of bean class which is
passed as an argument in the validate method of the LoginDao class. If emailid and
password is correct, it displays a message you are successfully logged in! and
maintains the session so that we may recognize the user.

1. <%@page import="bean.LoginDao"%>
2. <jsp:useBean id="obj" class="bean.LoginBean"/>
3.
4. <jsp:setProperty property="*" name="obj"/>
5.
6. <%
7. boolean status=LoginDao.validate(obj);
8. if(status){
9. out.println("You r successfully logged in");
10. session.setAttribute("session","TRUE");
11. }
12. else
13. {
14. out.print("Sorry, email or password error");
15. %>
16. <jsp:include page="index.jsp"></jsp:include>
17. <%
18. }
19. %>

LoginBean.java

It is the bean class that have 2 properties email and pass with its setter and getter
methods.

1. package bean;
2.
3. public class LoginBean {
4. private String email,pass;
5.
6. public String getEmail() {
7. return email;
8. }
9.
10. public void setEmail(String email) {
11. this.email = email;
12. }
13.
14. public String getPass() {
15. return pass;
16. }
17.
18. public void setPass(String pass) {
19. this.pass = pass;
20. }
21.
22.
23. }

Provider.java
This interface contains four constants that may differ from database to database.
1. package bean;
2.
3. public interface Provider {
4. String DRIVER="oracle.jdbc.driver.OracleDriver";
5. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
6. String USERNAME="system";
7. String PASSWORD="oracle";
8.
9. }

ConnectionProvider.java

This class provides a factory method that returns the object of Connection. Here,
driver class is loaded only once and connection object gets memory only once
because it is static.

1. package bean;
2. import java.sql.*;
3. import static bean.Provider.*;
4.
5. public class ConnectionProvider {
6. private static Connection con=null;
7. static{
8. try{
9. Class.forName(DRIVER);
10. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWOR
D);
11. }catch(Exception e){}
12. }
13.
14. public static Connection getCon(){
15. return con;
16. }
17.
18. }

LoginDao.java

This class varifies the emailid and password.

1. package bean;
2. import java.sql.*;
3. public class LoginDao {
4.
5. public static boolean validate(LoginBean bean){
6. boolean status=false;
7. try{
8. Connection con=ConnectionProvider.getCon();
9.
10. PreparedStatement ps=con.prepareStatement(
11. "select * from user432 where email=? and pass=?");
12.
13. ps.setString(1,bean.getEmail());
14. ps.setString(2, bean.getPass());
15.
16. ResultSet rs=ps.executeQuery();
17. status=rs.next();
18.
19. }catch(Exception e){}
20.
21. return status;
22.
23. }
24. }
Uploading file to the server using
JSP
1. Uploading file to the server using JSP
2. MultipartRequest class
3. Constructors of MultipartRequest class
4. Example of File Upload in JSP

There are many ways to upload the file to the server. One of the way is by the
MultipartRequest class. For using this class you need to have the cos.jar file. In this
example, we are providing the cos.jar file alongwith the code.

MultipartRequest class

It is a utility class to handle the multipart/form-data request. There are many constructors define
the MultipartRequest class.

Commonly used Constructors of MultipartRequest class

o MultipartRequest(HttpServletRequest request, String


saveDirectory) uploads the file upto 1MB.
o MultipartRequest(HttpServletRequest request, String saveDirectory, int
maxPostSize) uploads the file upto specified post size.
o MultipartRequest(HttpServletRequest request, String saveDirectory, int
maxPostSize, String encoding) uploads the file upto specified post size with
given encoding.

Example of File Upload in JSP


In this example, we are creating two files only, index.jsp and fileupload.jsp.

index.jsp

To upload the file to the server, there are two requirements:

1. You must use the post request.


2. encodeType should be multipart/form-data that gives information to the
server that you are going to upload the file.

1. <form action="upload.jsp" method="post" enctype="multipart/form-data">


2. Select File:<input type="file" name="fname"/><br/>
3. <input type="image" src="MainUpload.png"/>
4. </form>
upload.jsp

We are uploading the incoming file to the location d:/new, you can specify your
location here.

1. <%@ page import="com.oreilly.servlet.MultipartRequest" %>


2. <%
3. MultipartRequest m = new MultipartRequest(request, "d:/new");
4. out.print("successfully uploaded");
5.
6. %>

If size of the file is greater than 1MB, you should specify the post size.
Example of Downloading file from the
server using JSP
In this example, we are going to download the jsp file. But you may download any
file. For downloading the file from the server, you should specify the content type
named APPLICATION/OCTET-STREAM.

index.jsp

This file provides a link to download the jsp file.

1. <a href="download.jsp">download the jsp file</a>

download.jsp

In this example, we are downloading the file home.jsp which is located in the e: drive.
You may change this location accordingly.

1. <%
2. String filename = "home.jsp";
3. String filepath = "e:\\";
4. response.setContentType("APPLICATION/OCTET-STREAM");
5. response.setHeader("Content-Disposition","attachment; filename=\"" + filena
me + "\"");
6.
7. java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath
+ filename);
8.
9. int i;
10. while ((i=fileInputStream.read()) != -1) {
11. out.write(i);
12. }
13. fileInputStream.close();
14. %>

You might also like