JSP Tutorial
JSP Tutorial
JSP technology is used to create web application just like Servlet technology. It can
be thought of as an extension to servlet because it provides more functionality than
servlet such as expression language, jstl etc.
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain
than servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tag etc.
1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of
servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In servlet technology, we mix our business logic with the
presentation logic.
If JSP page is modified, we don't need to recompile and redeploy the project. The
servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that
reduces the code. Moreover, we can use EL, implicit objects etc.
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 webserver that is responsible to
translate the JSP page into servlet. Afterthat Servlet page is compiled by the
compiler and gets converted into the class file. Moreover, all the processes that
happens in servlet is performed on JSP later like initialization, committing response
to the browser and destroy.
To create the first jsp page, write some html code as given below, and save it by .jsp
extension. We have save this file as index.jsp. Put it in a folder and paste the folder
in the web-apps directory in apache tomcat to run the jsp page.
index.jsp
Let's see the simple example of JSP, here we are using the scriptlet tag to put java
code in the JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
No, there is no need of directory structure if you don't have class files or tld files. For
example, put jsp files in a folder directly and deploy that folder.It will be running
fine.But if you are using bean class, Servlet or tld file then directory structure is
required.
The directory structure of JSP page is same as servlet. We contains the jsp page
outside the WEB-INF folder or in any directory.
o scriptlet tag
o expression tag
o declaration tag
5.[4.] Implicit Objects
o page directive
o include directive
o taglib directive
7.[6.] Exception Handling
8.[7.] Action Elements
11.[10.] JSTL
<<prevnext>>
Cassandra
JSF
Ruby
Java Date
2. javax.servlet.jsp package
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
o JspWriter
o PageContext
o JspFactory
o JspEngineInfo
o JspException
o JspError
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.
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.
<<prevnext>>
Cassandra
JSF
Ruby
Java Date
2. create a jsp
o create a jsp
For creating a dynamic web project click on File Menu -> New -> dynamic web
project -> write your project name e.g. first -> Finish.
2) Create the JSP file in eclipse IDE
For creating a jsp file explore the project by clicking the + icon -> right click on
WebContent -> New -> jsp -> write your jsp file name e.g. index -> next -> Finish.
Now JSP file is created, let's write some code.
3) Start the server and deploy the project:
For starting the server and deploying the project in one step Right click on your
project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll ->
finish.
If you are using Eclipse IDE first time, you need to configure the tomcat server First.
Click for How to configure tomcat server in eclipse IDE
Now start the tomcat server and deploy project
For starting the server and deploying the project in one step Right click on your
project -> Run As -> Run on Server -> choose tomcat server -> next -> addAll ->
finish.
Yes, Let's see JSP is successfully running now.
Next TopicJsp Scriptlet Tag
<<prevnext>>
Cassandra
JSF
Ruby
Java Date
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see
what are the scripting elements first.
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. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
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>
← prevnext →
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.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
File: index.jsp
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>
Next TopicJsp Declaration Tag
The code written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet.
The jsp scriptlet tag can only declare variables not The jsp declaration tag can
methods. methods.
The declaration of scriptlet tag is placed inside the The declaration of jsp declarat
_jspService() method. _jspService() method.
index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
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>
← prevnext →
There are 9 jsp implicit objects. These objects are created by the web container that
are available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
1. PrintWriter out=response.getWriter();
index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
Output
Upcoming topics in JSP implicit Objects
Example of Request implicit Object
Example of Response implicit Object
Example of config implicit object
Example of application implicit object
Example of session implicit object
Example of pageContext implicit object
Example of page implicit object
Example of exception implicit object
Next TopicJsp Request Implicit Object
<<prevnext>>
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.
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
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.
Output
Other topics in JSP implicit Objects
Example of outt implicit Object
Example of Request implicit Object
Example of config implicit object
Example of application implicit object
Example of session implicit object
Example of pageContext implicit object
Example of page implicit object
Example of exception implicit object
<<prev
Output
Other topics in JSP implicit Objects
Example of out implicit Object
Example of request implicit object
Example of Response implicit Object
Example of application implicit object
Example of session implicit object
Example of pageContext implicit object
Example of page implicit object
Example of exception implicit object
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.
Output
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.
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
7) pageContext implicit object
In JSP, pageContext is an implicit object of type PageContext class.The pageContext
object can be used to set,get or remove attribute from one of the following scopes:
o page
o request
o session
o application
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. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
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)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
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"); %>
To get the full example, click here full example of exception handling in jsp. But, it will
be better to learn it after the JSP Directives.
JSP directives
1. JSP directives
1. page directive
The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
o page directive
o include directive
o taglib directive
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
2)contentType
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.
The web container will create a method getServletInfo() in the resulting servlet.For
example:
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.
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 value is 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 use isThreadSafe attribute of page directive.The value of
isThreadSafe value is true.If you make it false, the web container will serialize
the multiple requests, i.e. it will wait until the JSP finishes responding to a
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:
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.
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.
<<prevnext>>
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).
1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>
Note: The include directive includes the original content, so the actual page size
grows at runtime.
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.
1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>
Next TopicException Handling In Jsp
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:
o process.jsp for dividing the two numbers and displaying the result
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
error.jsp
1. <%@ page isErrorPage="true" %>
2.
3. <h3>Sorry an exception occured!</h3>
4.
5. Exception is: <%= exception %>
o process.jsp for dividing the two numbers and displaying the result
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-app>
2.
3. <error-page>
4. <error-code>500</error-code>
5. <location>/error.jsp</location>
6. </error-page>
7.
8. </web-app>
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. %>
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: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:pl
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean
development. So we will see these tags in bean developement.
3. </jsp:forward>
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>
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>
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.
includes the original content in the generated servlet. calls the include me
3. </jsp:include>
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()); %>
<<prevnext>>
Java Bean
A Java Bean is a java class that should follow following conventions:
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.
1. //Employee.java
2.
3. package mypack;
4. public class Employee implements java.io.Serializable{
5. private int id;
6. private String name;
7.
8. public Employee(){}
9.
10.public void setId(int id){this.id=id;}
11.
12.public int getId(){return id;}
13.
14.public void setName(String name){this.name=name;}
15.
16.public String getName(){return name;}
17.
18.}
To access the java bean class, we should use getter and setter methods.
1. package mypack;
2. public class Test{
3. public static void main(String args[]){
4.
5. Employee e=new Employee();//object is created
6.
7. e.setName("Arjun");//setting value to the object
8.
9. System.out.println(e.getName());
10.
11.}}
Note: There are two ways to provide values to the object, one way is by constructor
and second is by setter method.
<<prevnext>>
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.
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.
For the example of setProperty, getProperty and useBean tags, visit next page.
1. package com.javatpoint;
2. public class Calculator{
3.
4. public int cube(int n){return n*n*n;}
5.
6. }
index.jsp file
<<prev
3. Example of jsp:setProperty
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.
o welocme.jsp file that sets the incoming values to the bean object and prints the
one value
index.html
process.jsp
User.java
1. package org.sssit;
2.
3. public class User {
4. private String name,password,email;
5. //setters and getters
6. }
index.jsp
Same as above.
User.java
Same as above.
process.jsp
second.jsp
process.jsp
<<prev
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.
1. ${ expression }
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 scop
sessionScope it maps the given attribute name with the value set in the session scop
applicationScope it maps the given attribute name with the value set in the application s
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 }
index.jsp
process.jsp
1. Value is ${ sessionScope.user }
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:
[] .
()
* / div % mod
+ - (binary)
== != 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
<<prev
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.
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
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 JspWrite
r
12. }catch(Exception e){System.out.println(e);}
13. return SKIP_BODY;//will not evaluate the body content of the tag
14. }
15. }
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>
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/>
Output
There can be defined too many attributes for any custom tag. To define the attribute,
you need to perform two tasks:
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
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
download this example
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
download this example
Next TopicIteration Using Jsp Custom Tag
<<prevnext>>
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.
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>
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 htt
p://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="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
<<prevnext>>
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>
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.}
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 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
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.value=''"/
><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 methods.
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,PASSWORD);
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. }
In this example of creating login form, we have used the DAO (Data Access Object),
Factory method and DTO (Data Transfer Object) design patterns. There are many
files:
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 LoginDao.java, a DAO class that verifies the emailId and password from the
database.
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:
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.
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,PASSWORD);
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. }
<<prevne
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
index.jsp
To upload the file to the server, there are two requirements:
upload.jsp
We are uploading the incoming file to the location d:/new, you can specify your location here.
If size of the file is greater than 1MB, you should specify the post size.
← prev
Next
<<prevnext>>
<<prevnext>>