JSP Complete Notes
JSP Complete Notes
JSP Complete Notes
1. Introduction
2.EL Implicit Object
3.EL Operators
4.EL Functions
9. JSTL
1.Introduction
2.General Purpose Tags
3.Conditional Tags
4.Iteration Tags
5.URL-Related Tag
1. Introduction
2. Example on Custom Tags
3. Attributes
4. Iteration
5. Custom URI
JSP API Introduction
1. Every class which is generated for the JSP must implement
eitherjavax.servlet.jsp.JspPage or javax.servlet.jsp.HttpJspPage Interface
either directly or indirectly.
2. Tomcat people provided a base
classorg.apache.jasper.runtime.HttpJspBase for implementing the above
two interfaces.
3. Hence any servlet which is generated by Tomcat is extending
theHttpJspBase class.
1. javax.servlet.jsp
2. javax.servlet.jsp.tagext(used for custom tag API)
1. JspPage
2. HttpJspPage
JspWriter
PageContext
JspFactory
JspEngineInfo
JspException
JspError
JspPage
======
javax.servlet.jsp.JspPage:
Introduction:
1.jspInit() :
This method will be executed only once at the time of first request to perform
initialization activities.Web container always calls init(ServletConfig
config) present in HttpJspBase class which intern calls jspInit() method
present in our JSP .
Test.jsp:
<%!
public void jspInit()
{
System.out.println (“my own initialization activities”);
}
%>
HttpJspBase:
<%!
public final void init(serveletconfig config)
{
System.out.println (“my own initialization activities”)’
}
%>
CE-
Cannot override the final method from HttpJspBase.
2. jspDestroy():
This method will be executed only once to perform cleanup activities just
before taking JSP from out of service.
Web container always calls destroy() method present in HttpJspBase class
which intern calls JspDestroy().
Test.jsp:
<%!
Public void jspDestroy(){
// put your custom code here
// to clean up resources
}
%>
HttpJspPage
PKG- javax.servlet.jsp.HttpJspPage
This interface defines only one method :
1. _jspService( )
Syntax:
Public abstract void_jspService(javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response)throws
javax.servlet.ServletException, java.io.IOException
1. This method will be executed for each client request.
2. Web container always calls service () method available in HttpJspBase class
which intern calls _jspService() .
3. We can’t override service () method in our jsp, because it is declared as final
in HtpJspBase class.
4. Web container will always generate _jspService() in the generated servlet at
the time of translation page.
5. If we are placing _jspService() method explicitly in jsp then generated
servlet class contains two _jspService() methods which causes compile time
error and a java class never allow to contain more than one method an same
signature. Hence we can’t over ride _ JspService() method explicitly in the
jsp.
Note:The following three methods are considered as life cycle methods of the
jsp.
1. jspInit()
2. jspDestroy()
3. _jspService()
PRECOMPILATION
How to pre-compile JSP?
Add jsp_precompile as a request parameter and send a request to the JSP file.
This will make the jsp pre-compile. Why it is mentioned as pre compile
instead of compilation is that, the request is not served. That is, the JSP will
not be executed and the request will not be serviced. Just it will be compiled
and the implementation class will be generated.
The jsp_precompile parameter may have no value, or may have values true or
false. It should not have any other values like ?jsp_precompile=yes – this will
result in HTTP error 500.
So the example for query strings to pre compile jsp files are
?jsp_precompile
?jsp_precompile=true
?jsp_precompile=false
?foobar=foobaz&jsp_precompile=true
?foobar=foobaz&jsp_precompile=false
How to do pre compile for a bunch of JSP files? for all JSPs
in a folder or application?
There are no special features available for this in the JSP specification. But
the application servers (JSP containers) provide methods to do this on their
own way.
But if you want to pre compile in server independent manner you have to use
jsp_precompile request parameter and no other option available. To do it for
the whole application, you can custome write a servlet or jsp file which will
raise a request for all the JSPs available with jsp_precompile added as
parameter.
Object Class
1. request javax.servlet.ServletRequest
2. response javax.servlet.ServletResponse
3. application javax.servlet.ServletContext
4. session javax.servlet.http.HttpSession
5. page java.lang.Object
6. config javax.servlet.ServletConfig
7. exception java.lang.Throwable
8. pageContext javax.servlet.jsp.PageContext
9. out javax.servlet.jsp.JspWriter
Note : out & pageContext implicit objects are specially designed for Jsp’s
Implicit objects summary :
1. Except session and exception implicit objects all are by default available
to every Jsp.
2. We can’t make them unavailable.
3. But session objects are always available to every Jsp. But we can make it
unavailable by using session attribute of page directive.
<%@ page session = “false” %>
4. Exception implicit object is not available by default but we can make it
available by using isErrorPage of the page directive.
<%@ page isErrorPage = “true” %>
5. Among all 9 Jsp implicit objects the most powerful object is pageContext.
The most rarely used implicit object is page.
REQUEST OBJECT
=================
1. request object
1. For each request the JSP engine creates a new object to represents
that request called request object.
2. The request object is an instance of class
javax.servlet.http.HttpServletRequest .
3. The request object contains all information about
the HTTP header, query string, cookies
4. Be noted that request object only available in a scope of the current
request. It is re-created each time new request is made.
Example:
Test.jsp:
Introduction:
1. response is an instance of class javax.servlet.http.HttpServletResponse.
The response object represents the response to the client.
2. By using this object you can add new cookies, change content type of the
page and redirect the response.
Example: test.jsp
APPLICATION OBJECT
=====================
Introduction:
1. The JSP implicit application object is an instance of a java class that
implements thejavax.servlet.ServletContext interface.
2. It gives facility for a JSP page to obtain and set information about the web
application in which it is running.
There are numerous methods available for Application object. Some of the
methods of Application object are:
Example:
<context-param>
<param-name>user</param-name>
<param-value>ank567</param-value>
</context-param>
Test.jsp
application.setAttribute("SITE", "hftech.com");
%>
<table border= 2>
<%
out.println("<tr><td>Major version: </td><td>" +
application.getMajorVersion()+"</td></tr>");
out.println("<tr><td>Minor version:</td><td> " +
application.getMinorVersion()+"</td></tr>");
out.println("<tr><td>Servlet engine version </td><td>" +
application.getServerInfo()+"</td></tr>");
out.println("<tr><td>User init parameter:
</td><td>" +application.getInitParameter("user")+"</td></tr>");
out.println("<tr><td>SITE </td><td>" + application.getAttribute("SITE")+"</td></tr>");
%>
</table>
Methods:
Example: test.jsp
%>
<table border= 2>
<%
out.println("<tr><td>Created Time of Session is: </td><td>" +
session.getCreationTime()+"</td></tr>");
out.println("<tr><td>Last Accessed Time of Session is:</td><td> " +
session.getLastAccessedTime()+"</td></tr>");
out.println("<tr><td>The Session ID is: </td><td>" + session.getId()+"</td></tr>");
out.println("<tr><td>Maximum Inactive Interval of Session in Seconds is :
</td><td>"+session.getMaxInactiveInterval()+"</td></tr>");
out.println("<tr><td>SITE </td><td>" + session.getAttribute("SITE")+"</td></tr>");
%>
</table>
JSP Implicit object OUT
OUT OBJECT
Introduction:
There are numerous methods available for out Object, such as:
1.clear As the name implies, the clear method of out object is used
to clear the output buffer. An exception is thrown by this
method if the buffer was flushed.
2.clearBuffer The clearBuffer method of out object is used to clear the
output buffer. clearBuffer method does not throw an
exception when the buffer is flushed.
3.flush Two methods of out object, clear and clearBuffer are used
to clear the output buffer without writing any contents to
the client.
4.isAutoFlush The isAutoFlush method of out object returns a true value
if the output buffer is automatically flushed.
5.getBufferSize The getBufferSize method of out object is used to return
the size of the buffer. The returned value of the size of the
buffer is in bytes. If the output is not buffered, then the
getBufferSize method returns a 0 byte.
6.getRemaining The getRemaining method of out object is used to return
the number of empty bytes in the buffer.
7.newLine As the name implies, the newLine method of out object is
used to write a newline character to the output.
8.print The print method of out object writes the value to the
output without a newline character.
9.println The println method of out object is used to write the value
to the output, including the newline character.
Example: test.jsp
EXCEPTION OBJECT
exception implicit objects
Methods:
Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.
Returns the name of the class concatenated with the result of getMessage()
Prints the result of toString() along with the stack trace to System.err, the
error output stream.
Returns an array containing each element on the stack trace. The element at
index 0 represents the top of the call stack, and the last element in the array
represents the method at the bottom of the call stack.
Fills the stack trace of this Throwable object with the current stack trace,
adding to any previous information in the stack trace.
Example: main.jsp
ShowError.jsp
Output:
Opps...
Sorry, an error occurred.
EXCEPTION HANDLING
We can configure error page in jsp’s by using the following two approaches:
1. Declarative Approach
2. Programmatic Approach
1. Declarative Approach:
<web-app>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/generalError.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/exp404.html </location>
</error-page>
</web-app>
2. Programmatic Approach
We can configure error page for a particular Jsp by using error page attribute
of page Directive.
Test.jsp
Error.jsp
If the jsp is not declared as error page then exception implicit object is not
available. if we are trying to use we will get compile time error saying
Exception cannot be resolved.
If we are accessing error page directly without any exception hence exception
implicit object refers null.
ShowError.jsp
Output:
PAGECONTEXT OBJECT
7.pageContext :
request getRequest ( )
response getResponse ( )
config getServletConfig ( )
application getServletContext ( )
session getSession ( )
out getOut ()
page getPage ( )
exception getException ( )
These methods are not useful within the Jsp because all implicit objects are
available in every Jsp. But these methods are useful outside the Jsp mostly
in custom tag handlers.
1. page
2. request
3. session
4. application
Example:
pageContext.setAttribute("user","hftech.com",PageContext.SESSION_SCOP
E);
page.getServletInfo()
Error because page is java.lang.Object type
((servlet)page).getServletInfo()
this.getServletInfo()
1. The config object allows you to access the initialization parameters for
the Servlet and JSP engine.
2. The config object is an instance of the class javax.servlet.ServletConfig.
3. all methods of ServletConfig interface we can apply on config also
following is the list of applicable methods.
getInitParameter ( )
getInitParameterNames()
getServlerName()
Example: index.html
<html>
<body>
<input type = "text" name = 'uname'/>
<input type = "submit" name = 'go'/>
</body>
</html>
Web.xml
<web-app>
<servlet>
<servlet-name>action</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver. </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Welcome.jsp
<html>
<body>
<%
out.print("welcome"+request.getParameter("uname"));
String driver = config.getParameter("dname");
out.print("driver name is ="+driver);
%>
</body>
</html>
JSP Scopes: page scope
Jsp Scopes
Introduction:
1. Request Scope
2. Session Scope
3. Application Scope
In addition to these 3 scopes we have page scope is available in jsp’s.
Page Scope
==========
1. This scope is applicable only for jsp’s but not for servlet.
2. This scope is maintained by pageContext implicit object.
3. An object with this scope can be accessed by invoking the getAttribute
( ) method on the implicit page Context object. The object is created
and destroyed for each client request to the page.
4. This is the default scope for objects used with the jsp:useBean action.
5. The JSP object can be accessed only from within the same page where
it was created. JSP implicit objects out, exception, response,
pageContext, config and page have page scope.
6. Page scope in the most commonly used scope to share information
between tag handler class.
PageContext class defines the following methods to perform attribute
management in page scope.
Methods:
PageContext.PAGE-SCOPE = 1
PageContext.REQUEST-SCOPE = 2
PageContext.SESSION-SCOPE = 3
PageContext.APPLICATION-SCOPE = 4
Example:
setAttribute(“uname”,”ank567”,1)
Example: UsingBeanScopePage.java
package Mybean;
public class UsingBeanScopePage{
private static int counter = 0;
public void setCounter(int counter) {
this.counter = counter;
}
public int getCounter(){
return counter;
}
}
Index.jsp
<html>
<head>
<title>Using Beans and Page Scope</title>
</head>
<body>
<h1>Using Beans and Page Scope</h1>
<jsp:useBean id="pageScopeBean"
class="Mybean.UsingBeanScopePage" scope="page" />
<%
pageScopeBean.setCounter(pageScopeBean.getCounter() + 1);
%>
Counter value is <%= pageScopeBean.getCounter() %>
</body>
</html>
Methods:
Methods:
Introduction:
The directive tag gives special information about the page to JSP Engine.
This changes the way JSP Engine processes the page. Using directive tag,
user can import packages, define error handling pages or session information
of JSP page.
Directives provide general information about our Jsp to the Jsp engine These
are Translation time instructions to the Jsp engine.
Syntax:
1. Page
2. Include
3. Tag Lib
jsp page directive with import,session,Content Type,isELIgnored
Attributes
PAGE DIRECTIVE
Definition: The page Directive Specifies the overall properties of Jsp page to
the Jsp engine.
Syntax:
<%@ page [AttributeName = value ] %>
1. Import:
Introduction: We can use import attribute for importing classes & interfaces
present in a package. This is similar to Core java import statement.
Case 1:
Output:
Case 2 :
Case 3 :
Within the same Jsp we are not allowed to take any attribute except import
multiple times with different values. But we can take multiple times with
same value.
Output:
In Invalid case we will get Translation time error saying page directive:
illegal to have multiple occurrences of session with different values.
Case 4:
Inside Jsp it is not required to import the following packages because these
are available by default in every Jsp.
1. javax. servlet
2. javax. servlet.http
3. javax. servlet.jsp
4. java.lang.*
Note: Static import Concept is not applicable to the Jsp.
2. Session
Syntax:
<%@ page session = “true” %>
Description:
1. The session attribute indicates whether or not the JSP page uses HTTP
sessions.
2. In every Jsp session implicit object is by default available.
3. A value of true means that the JSP page has access to a built-
in session object
4. A value of false means that the JSP page cannot access the built-in session
object.
5. If we don’t want, we can make it unavailable by declaring page directives as
follows.
<%@ page session = “false” %>
If we are not declaring session attribute explicitly then the jsp engine
explicitly place below code in _jspService() method in the jsp engine
generated servlet class
HttpSession session = null;
session = pageContext.getSession ( )
If we are declaring session attribute with false value then the above lines
won’t be generated.
Session attribute values are not case sensitive. The allowed values for the
session attribute are
TRUE
True
FALSE
False
3. Content Type
Definition : We can use this attribute to specify content type and character set
of the response
Description : The default value of the content type attribute is “text/html” and
Charest is ISO-8859-1
Possible values for content Type
1. application/msword - msword
2. text/HTML HTML file
3. text/xml XML file
4. text/plain text file
4. isELIgnored
Introduction :
Note : In Jsp 1.2 version the default value of isELIgnored is true, but Jsp 2.0
version on wards the default value us false.
Syntax: <%@page isELIgnored="true"%>
test.jsp
<%@page isELIgnored="false"%>
Additon : ${2+3}
Output:
test.jsp:
<%@page isELIgnored="false"%>
Additon : ${2+3}
Output:
jsp page directive with isThreadSafe,isErrorPage,errorPage,language,extends
5. isThreadSafe
Introduction :
1. The isThreadSafe attribute of page directive informs the JSP container how
the JSP page should behave if multiple requests are received at the same
time.
2. It takes boolean values true or false.
Syntax :
<%@page isThreadSafe="true"%>
If the value of this attribute is set to true. It implies that the JSP container can
handle or send multiple concurrent client requests to the JSP page by
starting a new thread.
If the value of this attribute is set to false, then the JSP container sends client
requests only one at a time to the JSP page.
6. isErrorPage
Introduction:
1. The isErrorPage attribute of page directive is used to specify that the page
may be used as an error page.
2. It takes boolean value true or false.
7.errorPage
Introduction:
1. If the programmer wants to place errors in a different page then the URL
to the error page can be mentioned in this attribute as errorPage.
Syntax :
Example:
8. language
Introduction:
1. JSP containers may support languages other than Java. However most
popular JSP container support only Java.
2. The language attribute of page directive is used to specify the scripting
language.
Syntax :
<%@ page language="java" %>
Description:
1. The language attribute is set to java by default. So most JSP programs do not
specify the language attribute of page directive.
9. extends
Introduction:
The extends attribute specifies a super class that the generated servlet must
extend.
Syntax:
Example:
For example, the following page directive indicate the JSP translator to
generate the servlet with extendshftech/test
1. By using this buffer attribute we can set the buffer size or we can disable
buffer future.
2. The default size of buffer is 8KB
In this case all the servlet output write into the buffer before writing to the
response object.
You may code a buffer value of "none" to specify no buffering so that all
servlet output is immediately write into the response object .
11. autoFlush
Introduction:
If autoflush is set to false, if the buffer gets full, JSP container will raise an
exception.
12. info
Introduction:
Example:
13. pageEncoding
This attribute specifies the language that the page uses when the page is sent
to the browser. This attribute works like the meta tag of the HTML markup
language.
Advantages:
1. It promotes reusability.
2. Enhancement will become very easy.
3. It improves maintainability.
Disadvantage:
1. The JSP compilation procedure is that, the source JSP page gets compiled
only if that page has changed. If there is a change in the included JSP file, the
source JSP file will not be compiled and therefore the modification will not
get reflected in the output
Example:
first.jsp:
second.jsp
Output:
jsp Taglib Directive
Taglib Directive
Introduction:
The JavaServer Pages API allows you to define custom JSP tags that look
like HTML or XML tags and a tag library is a set of user-defined tags that
implement custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides a means for identifying the
custom tags in your JSP page.
Syntax
Attributes:
1.prefix : prefix attribute informs a container what bits of markup are custom
actions.
Example:
1. JSP actions are special XML tags which control the behavior of servlet
engine.
2. JSP actions allow you to insert a file dynamically, reuse external Java Bean
components, forward the request to the other page and generate HTML
for Java Applet plug-in.
1. JSP actions are special XML tags which control the behavior of servlet
engine.
2. JSP actions allow you to insert a file dynamically, reuse external Java Bean
components, forward the request to the other page and generate HTML
for Java Applet plug-in.
What is java bean ?
A Java Bean is a java class that should follow following conventions:
Employee.java
1. package mypack;
2. public class Employee implements java.io.Serializable{
3. private int id;
4. private String name;
5.
6. public Employee(){}
7.
8. public void setId(int id){this.id=id;}
9.
10. public int getId(){return id;}
11.
12. public void setName(String name){this.name=name;}
13.
14. public String getName(){return name;}
15.
16. }
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.
1. <jsp: useBean>
Introduction:
SimpleBean.java
package com.hftech;
test.jsp
<jsp:useBean id="b" class="com.hftech.SimpleBean"></jsp:useBean>
<%
b.setMail("hftech @gmail.com");
b.setMobileno("9999999999");
b.setPassword("hftech ");
b.setUname("hftech ");
%>
<table border=2>
<tr><td><h2>property</h2></td><td><h2>value</h2></td></tr>
<tr><td><h2>User Name</h2></td><td><h2><%= b.getUname()%></h2></td></tr>
<tr><td><h2>Password</h2></td><td><h2><%= b.getPassword()%></h2></td></tr>
<tr><td><h2>Mail Id</h2></td><td><h2><%= b.getMail()%></h2></td></tr>
<tr><td><h2>Mobile Num</h2></td><td><h2><%= b.getMobileno()%></h2></td></tr>
</table>
Advantages:
Separation of responsibilities
Java developer can concentrate on business logic where as html page
designer can concentrate on presentation logic. As both can work
simultaneously, we can reduce development time.
<jsp: useBean>
We can use this standard action to make java bean object available to the
Jsp.
There are two forms of <jsp: useBean>
Without Body
<jsp:useBean id="b" class="com. hftech.SimpleBean"/>
With Body
Note : The main objective of body is to perform initialization for the newly
created bean object.
If the bean object is already available then <jsp:useBean> tag won’t create
any new object it will use existing object only.
In this case body won’t be executed.
id
class
type
scope
beanName
1. id
It represents the name of the reference variable of the bean object. And by
using this reference variable only we can access bean in rest of the jsp.
This attribute is mandatory attribute.
2. class Attribute
3. type Attribute
This attribute can be used to specify the type of the reference variable.
The value of the type attribute can be Concrete class (or) Abstract class (or)
Interface.
class attribute is optional but we have to specify either class attribute or type
attribute is mandatory
4.scope Attribute
This attribute specifies jsp engine in which scope has to search for the
required bean object.if the java bean object is not available in that scope jsp
engine create a new bean and object and store in specified scope for the
future purpose.
The allowed values for the scope attribute are
page
request
session
application
5. Bean Name
There may be a chance of using serialized bean object from local file system.
In that case we have to use bean name attribute.
Note :If we are using only type attribute without class then compulsory the
specified type bean object should be available otherwise Jsp engine won’t
create any new bean object and raises instantiation exception.
Jsp engine searches for Runnable type object with “c” name in session
scope. If it is not available then it raises runtime exception.
1. The <jsp:getProperty> action are used to retrieve data from the bean as
a String object.
2. You must create or locate a Bean with <jsp:useBean> before you use
<jsp:getProperty>.
Limitations:
Attributes:
<jsp: getProperty> tag contains the following 2 attributes
1. Name :
The name of the bean object from which the required property is obtained.
It is exactly same as id attribute of jsp:useBean.
Test.jsp
Student.java
package pack1;
Public class StudentBean
{
private String name= “hftech”
private String mail=” [email protected]”;
public String getName ( )
{
return name;
}
public String getMail ( )
{
return mail;
}
}
Output:
Syntax:
Description:
2. . It retrieves the value of request parameter and assign it to the specified bean
property.
<jsp:setProperty property="uname" name="b" param="username" />
3. If the request parameter Name matches with bean property Name then it is
not required to use param attribute
<jsp:setProperty property="uname" name="b" />
Note: It iterates through all request parameters and it any parameter name
matched with bean property name then assigns request parameter value
through the bean property.
Attributes:
1. Name:
It represents the name of the bean object whose property has to set.This is
exactly same as id attribute <jsp:useBean>,It is the mandatory attribute.
2. Property:
The name of the java bean property which has to set.It is the mandatory
attribute.
3. Value:
It specifies the value which has to set to the java bean property.It is optional
attribute and never becomes in combination with param attribute.
4. Param:
It represents the name of the request parameter whose value has to set to the
bean property. It is optional attribute and never comes in combination with
value attribute.
Example: login.jsp
<body >
<form action = "/Scwcd_jsp/test.jsp">
Enter name: <input type = 'text' name = "uname"> <br>
Enter mail : <input type = 'text' name = "mail"> <br>
Enter age: <input type = 'text' name = "age"><br>
<input type = "submit">
</form>
</body>
test.jsp
SimpleBean.java
package com.hftech;
Note: All the required type conversions will take care by automatically by
the <jsp:setProperty> :(string to int).
Syntax:
flush : It specifies whether the response will be flushed before inclusion (or)
not. it is optional attribute. The default value is false.
Example: first.jsp
second.jsp
Output:
Include Action
<jsp:include page= “header.jsp” %>
By using RequestDispatcher
<%
RequestDispatcher rd= request.getRequestDispatcher (“header.jsp”);
rd.include(request, response);
%>
Note:You can pass parameter names and values to the target file by using a
<jsp:param> clause. If you use <jsp:param>, the target file should be a
dynamic file that can handle the parameters.
Ex: first.jsp
second.jsp
Output: http://localhost:8080/Scwcd_jsp/first.jsp
1. Forward Standard Action
<jsp: forward page= “/second.jsp>
3. By Using RequestDispatcher
<%
RequestDispatcher rd=request.getRequestDispatcher (“second.jsp”);
rd.forward (req., resp);
%>
Syntax:
Attributes:
first.jsp
second.jsp
Output: http://localhost:8080/Scwcd_jsp/first.jsp
<jsp:plugin
type="bean|applet"
code="classFileName"
codebase="classFileDirectoryName"
</jsp:plugin>
Description
Attributes:
1. type="bean|applet"
The type of object the plugin will execute. You must specify either bean or
applet, as this attribute has no default value.
2. code="classFileName"
The name of the Java class file that the plugin will execute. You must include
the .class extension in the name following code. The filename is relative to
the directory named in the codebase attribute.
3. codebase="classFileDirectoryName"
The absolute or relative path to the directory that contains the applet's code. If
you do not supply a value, the path of the JSP file that calls <jsp:plugin> is
used.
4. name="instanceName"
A name for the Bean or applet instance, which makes it possible for applets
or Beans called by the same JSP file to communicate with each other.
Example:
pluginstandardaction.jsp
<html>
<title> Plugin example </title>
<body bgcolor="white">
<h3> The given below applet is imported to this file : </h3>
<jsp:plugin type="applet" code="Pluginexample.class" codebase="applet"
height="300" width="300">
<jsp:fallback>
Plugin tag not supported by browser.
</jsp:fallback>
</jsp:plugin>
<h4><font color=red>
The above applet is loaded using the Java Plugin from a jsp page using the
plugin tag.
</font>
</h4>
</body>
</html>
Pluginexample.java (Applet)
import java.awt.*;
import java.applet.*;
public class Pluginexample extends Applet
{
// Specify variables that will be needed everywhere, anytime here
// The font variable
Font bigFont;
// The colors you will use
Color redColor;
Color weirdColor;
Color bgColor;
public void init()
{
// Here we will define the varibles further
// Will use Arial as type, 16 as size and bold as style
// Italic and Plain are also available
bigFont = new Font("Arial",Font.BOLD,16);
// Standard colors can be named like this
redColor = Color.red;
// lesser known colors can be made with R(ed)G(reen)B(lue).
weirdColor = new Color(60,60,122);
bgColor = Color.blue;
// this will set the backgroundcolor of the applet
setBackground(bgColor);
}
public void stop()
{
}
// now lets draw things on screen
public void paint(Graphics g)
{
// tell g to use your font
g.setFont(bigFont);
g.drawString("PLUGIN example",80,20);
// Now we tell g to change the color
g.setColor(redColor);
// This will draw a rectangle (xco,yco,xwidth,height);
g.drawRect(100,100,100,100);
// This will fill a rectangle
g.fillRect(110,110,80,80);
// change colors again
g.setColor(weirdColor);
// a circle (int x, int y, int width, int height,int startAngle, int arcAngle);
// ovals are also possible this way.
g.fillArc(120,120,60,60,0,360);
g.setColor(Color.yellow);
// Draw a line (int x1, int y1, int x2, int y2)
g.drawLine(140,140,160,160);
// reset the color to the standard color for the next time the applets paints
// an applet is repainted when a part was'nt visible anymore
// happens most often because of browser minimizing or scrolling.
g.setColor(Color. black);}
}
Output:
The value of file and page attribute should be Relative path only, we are not
allow to provide complete URL which includes host name, server port etc.
These standard actions are designed to work within the web applications.
i.e. outside the web application communication purpose we can’t use these
tags.
Case 2:
In the case of forward & include page attributes are pointing to servlet. But
in the case of include directive file attribute can’t pointing to a servlet. It
can point to any Jsp (or) html (or) xml or xhtml etc.
Case 3:
Expression tag is used to display java expression output of any data on the
generated page.
The data placed in Expression tag prints on the output stream and
automatically converts data into string.
The Expression tag can contain any Java expression used for printing output
equivalent to out.println().
Syntax :
Test.jsp Test_java.java
Ex: <%= 10 %> out.println(10)
Case 1:
In side expression we can’t take semicolon otherwise we will get http status
500.
Ex1 : test.jsp
Output:
Ex2 : test.jsp
Output:
Case 2:
Within the expression we can take method calls also but void return type
method calls are not allowed.
Ex:
Output:
Case 3:
We can’t place space between percentage and equal inside expression tag
otherwise compile time error with 500 status code (because it is treated as
scriptlet.
Ex:
<% = 10 %>
It treated as scriptlet code so “= 10 ” is not a valid java statement.
Output:
JSP Scripting element Scriptlet
Scriptlet
Definition: Scriptlet is similar to the Expression without the equal sign
"=". You can insert any plain Java code inside the scriptlet. Because of
mixing between Java code and HTML is difficult to maintain so scriptlet is
not recommended to use anymore. Here is the syntax of the scriptlet:
Syntax :
Description:
Test.jsp
<%!
int count=0;
%>
<%
count ++;
out.println("<h2>The hit count is : :"+count+"</h2>");
%>
Output:
Request 1: http://localhost:8080/Scwcd_jsp/test.jsp
Request2: http://localhost:8080/Scwcd_jsp/test.jsp
Request3: http://localhost:8080/Scwcd_jsp/test.jsp
We can use this tag to declare class level declarations like static members,
instance members, inner classes and static, instance method etc.
If you want to define methods or fields you can use JSP declaration. The JSP
declaration is surrounded by the sign <%! and %>.
Syntax:
Description:
Example:test.jsp
<%!
Date d = new Date();
public Date getDate()
{
System.out.println( "In getDate() method" );
return d;
}
%>
Output: http://localhost:8080/Scwcd_jsp/test.jsp
1. Jsp Comments:
Syntax :
Description :
1. This JSP comment tag tells the JSP container to ignore the comment part
from compilation. That is, the commented part of source code is not
considered for the content parsed for ‘response’.
2. Also known as hidden comments because there are not visible in the
remaining phages of jsp life cycle because jsp comments data ignored by java
compiler at compilation time.
3. It is highly recommended to use jsp comments
Example :
Syntax:
Description:
1. The JSP container treats this HTML comment tag as equal as any other
HTML tags.
2. When ever we got the response right click on browser window and click on
view page source, the content given between this html/xm comment tag is
visible.
3. This is not anyway related to the JSP container, it is the expected behaviour
of this HTML tag and Hence these are not recommended to use.
3. Java Comments:
Syntax:
Description:
Example:
<%
String s = "hftech";
//printing string value
out.println("<h2>"+s+"</h2>");
/* jsp implicit objects are not available for declarative tag */
%>
Output: http://localhost:8080/Scwcd_jsp/test.jsp
hftech
Note:
Among expression, declaration, scriptlet and Jsp comments we can’t use one
inside another i.e. Nesting of the scripting elements is not allowed otherwise
we will get compile time error with 500 status code.
Example: test.jsp
<%
Out. Println(<%= 2*3 %>);
%>
<%!
Public void m1 ( )
{
<%
out.println("Hello");
%>
}
%>
<%!
<%-- This method is very useful --%>
public void m1 ( )
{
System.out.println("Hello");
}
%>
<%!
public void m1( )
{
System.out.println(<%= new Date( ) %>)
}
%>
Output:
Expression Language Introduction
Expression Language
1. Introduction:
Description:
1. In the syntax above, expr is an expression. When the Java compiler sees
the sign ${}, it process the expression and replace the result in the place
where ${expr} is called.
Note:
It prints the value of x attribute and if there is no such attribute then we will
get blank space but not null. (In standard syntax we will get null) but
ExpressionLanguage suppresses null and doesn’t print anything.
Expression Language ( EL ) pageScope, requestScope,
sessionScope, and applicationScope
Expression Language implicit objects
EL contains 11 implicit objects.
The power of EL is just because of these implicit objects only.
The following is the list of all EL implicit objects.
Ex:2 ${x}
Jsp container first checks in page scope for the attribute x .if it is available it
prints attribute value. If it is not available then it will check in request scope
followed by session and application scope. It simply acts
aspageContext.findAttribute(String name); method.
Test.jsp
<%
%>
Ex: 1 ${param.x}
Ex:2 $ {paramValues.x[0] }
It prints first value.
$ {paramValues. x[1]}
It prints second value.
login.jsp
<body >
<form action = "/Scwcd_jsp/test.jsp">
Enter name: <input type = 'text' name = "name"> <br>
Enter mail : <input type = 'text' name = "mail"> <br>
Enter Food1: <input type = 'text' name = "food"><br>
Enter Food2: <input type = text name = "food"><br>
<input type = "submit">
</form>
</body>
test.jsp
Case 1: http://localhost:8080/Scwcd_jsp/login.jsp
Case 2: Enter name, mail id,food1 and food2 and click on submit
Note:
${header.accept}
${headerValues.accept[0]}
test.jsp
Example :${cookie.JSESSIONID}
${cookie.JSESSIONID.name}
${cooke.JSESSIONID.value}
test.jsp
SecondRequest:
<context-param>
<param-name>user</param-name>
<param-value>chamu0001</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>myjavahub</param-value>
</context-param>
test.jsp
Output: http://localhost:8080/Scwcd_jsp/test.jsp
1. This is the only one EL implicit object which matches with Jsp implicit
objects.
2. By using this implicit object we can bring all other implicit objects into EL
and accessing servlet and JSP properties, such as a request's protocol or
server port, or the major and minor versions of the servlet API your container
supports.
3. You can find out that information and much more with the pageContext
implicit object, which gives you access to the request, response, session, and
application (also known as the servlet context).
4. Useful properties for the pageContext implicit object are listed in Table 2.6.
Property Type Description
Ex: 1.${pageContext.request.method}
2.${pageContext.session.id}
Expression Language (EL) contains its own set of operators the following is
the list of all available operators in Expression Language (EL) .
Syntax:
Ex- ${param.uname}
Map key
Ex: ${initParam.password}
Map key
Ex: ${customer.age}
Bean property
$ {initParam[“mail”]}
$ {customer [“name”]}
Note:
Ex:
1. ${2+3} Output: 5
2. ${“2”+ ‘3’} Output: 5
3. ${“2” + ‘3’} Output: 5
4. ${abc+ ‘3’} Output: 3
5. ${null+ “3”} Output: 3
6. ${“abc” + “3”} Output: NumberFormatException
7. ${“abc” + “3”} Output: NumberFormatException
Subtraction - :
Ex:
1. ${10-3} Output : 7
2. ${“abc”-3} Output : NumberFormatException.
3. ${abc-3} Output 3
Multiplication * :
Ex:
1. $ {10*3} Output: 30
2. ${“abc”*3} Output: NumberFormatException.
Ex:
Note : Division operator always follows floating point arithmetic but not
integral arithmetic.
Ex:
1. $ {10%3} Output : 1
2. $ {10%0} Output : ArithmeticException
3. $ {10.0%0} Output : NaN
1. Equal ( == or eq)
2. Not Equal (!= or ne)
3. Less than (< or lt)
4. Less than or equal (<= or le)
5. Greater than (> or gt)
6. Greater than or equal (>= or ge)
Examples:
Conditional Operator
Ex:
empty Operator :
$ {empty object}
EL Operator Precedence
EL Reserved Words
tue, false, null, empty, instanceOf, it, lt, ge, le, ne, eq,and,or,not,mod,div.
EL Vs Number
For Expression Language functions tld file provides mapping between Jsp
[where functionality is required] and java class [where functionality is
avialble].tld file is an xml file.
We can configure Expression Language (EL) function by using function tag
in this tld. This tag defines the following four child tags.
1. <description>
2. <name>
By means of this name only we can call EL functionality in the Jsp.
3. <function-class>
It defines fully qualified name of java class name where Expression
Language (EL) function is available.
4. <function-signature>
Signature of the method .
Example:
<function>
<name>upper</name>
<function-class>StrMethods</function-class>
<function-signature>java.lang.String upper(java.lang.String)</function-
signature>
</function>
4.Invoking EL Functions:
${myString:upper(param.name)}
EL Function Flow:
1. Where Jsp engine encounters EL functions call with prefix and EL function
name then it checks for corresponding taglib directive with matched prefix.
2. From taglib directive Jsp engine identifies uri and checks for tld file with
matched uri.
3. From the tld file Jsp engine checks for corresponding class and required
method.
4. Jsp engine executes that method and return its result to the Jsp.
Example: TestELServlet.java
Package com.hftech;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
result.jsp
index.html
<html>
<body>
<h1 align="CENTER">Test Expression Language</h1><br><br>
<form method="GET" action="MyTestEL.do">
Name: <input type="text" name="name"/><br>
<input type="submit" name="command" value="submit"/>
</form></body></html>
My.tld
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-
app_2_5.xsd"
version="2.5">
<tlib-version>1.2</tlib-version>
<uri>StringOperations</uri>
<function>
<name>upper</name>
<function-class>StrMethods</function-class>
<function-signature>java.lang.String upper(java.lang.String)</function-signature>
</function>
</taglib>
Xml Library:
The JSTL XML tags provide a JSP-centric way of creating and manipulating
XML documents. Following is the syntax to include JSTL XML library in
your JSP.
The JSTL XML tag library has custom tags for interacting with XML data.
This includes parsing XML, transforming XML data, and flow control based
on XPath expressions.
Syntax:
Before you proceed with the examples, you would need to copy following
two XML and XPath related libraries into your <Tomcat Installation
Directory>\lib:
XercesImpl.jar: Download it from http://www.apache.org/dist/xerces/j/
xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html
It defines several standard actions which can be used for writing, and
formatting xml data.
Sql Library:
It defines several standard actions which can be used for data base
operation
Syntax:
JSTL Functions:
Formatting tags:
The JSTL formatting tags are used to format and display text, the date, the
time, and numbers for internationalized Web sites. Following is the syntax to
include Formatting library in your JSP:
Syntax:
jstl-core_Library-Introduction
Core Library
Installing JSTL :
By default JSTL functionality is not available to the Jsp. We can provide
JSTL functionality by placing the following jar files in web applications lib
folder.
1) jstl.jar
Defines several API classes which are defined by sun people.
2) standard.jar
Provides Library implementation classes by vendor.
It is recommended to place these two jar in tomcat lib folder for application
level use.To make core Library available to the Jsp we have to declare taglib
directive as follows.
Syntax:
1. <c: out>
One of the general purpose core library tag is <c: out>. The main function of
the this tag is to display the output to the user. It works like expression tag in
jsp <%= ---%>.
Form1:
Form2:
Attributes:
test.jsp
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1> WELCOME TO :::
<c:out value="${param.uname}" default="hftech "></c:out>
</h1>
Case1: http://localhost:8080/Scwcd_jsp/test.jsp
Case2
: http://localhost:8080/Scwcd_jsp/test.jsp?uname=JAVA%20PORTAL
Attributes :
Syntax:
Note : var and value attributes are mandatory but scope attribute is optional.
default scope is page.
test.jsp
Output: http://localhost:8080/Scwcd_jsp/test.jsp
Form 2:
We can use <c: set> even for setting map (or) bean properties.
We can specify map (or) bean by target attribute.
Syntax:
Note : If the scope is not specify then the container will search in page scope
first for the required attribute. If it is available it will remove that attribute.
If it is not available then it will search in request scope followed by session
and Application scopes.
Examples:
test.jsp:
Output: http://localhost:8080/Scwcd_jsp/test.jsp
jstl General Purpose Tags: c:catch
<c: catch>
.<c: catch>
This can be used to catch an Exception within the Jsp instead of forwarding
to the error page.
The Risky code we have to place as the body of <c:catch>
Syntax:
<c:catch>
Risky Code
</c:catch>
With in Risky code if any exception raised then Jsp engine suppresses that
exception and rest of the Jsp will be executed normally.
If an exception is raised we can hold that exception by using var attribute
which is a page scoped attribute.
test.jsp
Case 1: http://localhost:8080/Scwcd_jsp/test.jsp?uname=chamu&age=0
Case 2: http://localhost:8080/Scwcd_jsp/test.jsp?uname=chamu&age=35
Syntax:
Explanation :
In this case test-condition will be processed and stores in request scope as a
“x” attribute,. In the rest of the page where ever the same test-condition is
required. We can use directly its value. Without evaluating this value.
In this case test & var attributes are mandatory where as scope attribute is
optional default scope is page.
In this case first test condition will be processes if it is true then the body will
be executed otherwise without execution of the body rest of the Jsp will be
continued.
In this case also we can save test result into a var attribute.
Here both var & scope are optional but test attribute is mandatory.
Example:
Case 1: http://localhost:8080/Scwcd_jsp/test.jsp
jstl Conditional Tags c:choose,c:when,c:otherwise
We can use these tags for implementing if-else and switch statements.
If you have a set of mutually conditions you can use <c:choose><c:when>
and <c:otherwise> instead of using multiple <c:if>.
In a range of conditions, if one of them is evaluated as true, the body content
of that <c:when> branch will process and output to the current JspWriter and
then no processing is performed. If none of conditions in <c:when> branch is
true, the body content of <c:otherwise> branch will process and output to the
current JspWriter. The combination of <c:choose><c:when> and
<c:otherwise> actions works like if elseif and else condition.
Implementing if-else:
JSTL doesn’t contain any tag for else we can implement if-else by the above
tags.
<c:choose>
Syntax:
<c:choose>
<c: otherwise>
Action 2
</c: otherwise>
</c: choose>
Case 1: http://localhost:8080/Scwcd_jsp/jstl_exp1.jsp?sal=200
Case 2: http://localhost:8080/Scwcd_jsp/jstl_exp1.jsp?sal=5000
jstl Conditional Tags switch implementation
JSTL-SWITCH
Implementing Swtich Statement
Conditions:
Syntax:
<c: choose>
</c: choose>
Example:
Switch.jsp
<h1>
Select the Number:</h1>
<form action ='/Scwcd_jsp/jstl_exp1.jsp' method="get">
<select name = 'combo'>
<option value = '1'> 1 </option>
<option value = '2'> 2 </option>
<option value = '3'> 3 </option>
<option value = '4'> 4 </option>
<option value = '5'> 5 </option>
<option value = '6'> 6 </option>
<option value = '7'> 7 </option>
</select>
<Input type = 'submit'/>
</form>
<c:set var="s" value="${param.combo}" scope="session"></c:set>
Today is:
<c:choose>
<c:when test = '${s==1}'> Sunday </c:when>
<c:when test = '${s==2}'> Monday </c:when>
<c:when test = '${s==3}'> Tuesday </c:when>
<c:when test = '${s==4}'> Wednesday </c:when>
<c:when test = '${$==5}'> Thursday </c:when>
<c:otherwise> select only 1 to 5 numbers </c:otherwise>
</c:choose>
Case 1: http://localhost:8080/Scwcd_jsp/jstl_exp1.jsp
Case 2: Select one option between 1 to 5
1. These tags exist as a good alternative to embedding a Java for, while, or do-
while loop via a scriptlet.
2. The <c:forEach> tag is the more commonly used tag because it iterates over
a collection of objects.
Syntax:
1. begin: The “begin” attribute specify the index where the loop has to start.
2. end: “end” index specifies where the loop has to terminate
3. step: “step” attribute specifies incremental value.
The default value of step attribute is “1” and it is optional attribute.
4. items: Information to loop over
5. var : Name of the variable to expose the current item
6. varStatus: Name of the variable to expose the loop status
1.<c:forEach>
Examples:
test.jsp:
Output: http://localhost:8080/Scwcd_jsp/test.jsp
Output: http://localhost:8080/Scwcd_jsp/test.jsp
jstl Iteration Tags c:forEach
<c:forEach> with items attribute
Form 3: <c:forEach> with items attribute
Example 1: test.jsp
Output: http://localhost:8080/Scwcd_jsp/test.jsp
Items attribute should contain either collection object (or) Array. This action
will iterate over each item in the collection until all elements completion.
Example 2: test.jsp
Output: http://localhost:8080/Scwcd_jsp/jstl_exp1.jsp
Example 3: test.jsp
Output: http://localhost:8080/Scwcd_jsp/test.jsp
If we are replace ${header} with $ {param} then all form parameter names &
value will be displayed.
FORM 4: <c:forEach>with varStatus attribute
varStatus attribute describe the status of Iteration like, Current Iteration
number, is it first Iteration (or) not etc.
This attribute is of type javax.servelet.jsp.core.TagLoopStatus.
This class defines several methods which are useful during iteration.
Methods:
1. Object getCurrent( )
Returns the current Item.
2. int getIndex( )
Returns the current index (current value)
3. int getCount( )
Returns the no. of iterations that have already performed including
current iteration.
4. boolean isFirst( )
Returns true if the current iteration is first Iteration.
5. boolean isLast( )
6. Integer getBegin( )
Return begin index on start index.
7. Integer getEnd( )
Returns the last index.
8. Integer getStep( )
Returns step value.
Example:
Output: http://localhost:8080/Scwcd_jsp/test.jsp
Note: The StringTokennizer class is use to split a String object into different
tokens by certain delimiter. (space is the default delimiter)
Syntax:
Example: http://localhost:8080/Scwcd_jsp/test.jsp
test.jsp
Output:
Attributes:
1. begin: The “begin” attribute specify the index where the loop has to start.
2. end: “end” index specifies where the loop has to terminate
3. step: “step” attribute specifies incremental value.
The default value of step attribute is “1” and it is optional attribute.
4. items: Information to loop over
5. var : Name of the variable to expose the current item
6. varStatus: Name of the variable to expose the loop status
7. delims: delims which specifies characters to use as delimiters.
This is used for importing the response of other pages into current page at
request processing time (dynamic include).
Form 1:
Example:
first.jsp
second .jsp:
We can import the resources from outside of current application also i.e
(cross context communication is also possible).
Syntax:
FORM 3 :
We can store the result of imported page into a variable specified by var
attribute.
In the rest of JSP where ever the result is required we can use directly the
variable without performing import once again.
Syntax:
Example:
first.jsp
second.jsp
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1> WELCOME TO HFTECH </h1>
FORM4:
While performing import we can send parameters also to the target JSP. For
this we have to use <c:param>
These parameters are available as form parameters in target Jsp.
Example:
first.jsp
second.jsp
FORM1:
<c:redirect url= ”second.jsp” />
FORM2: We can redirect the request to some other web application resource
also.
Syntax :
first.jsp
second.jsp
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Output:
Introduction:
The <c:url> tag formats a URL into a string and stores it into a
variable. This tag automatically performs URL rewriting when
necessary.
The var attribute specifies the variable that will contain the formatted
URL.
The JSTL url tag is just an alternative method of writing the call to the
response.encodeURL() method.
The only real advantage the url tag provides is proper URL encoding,
including any parameters specified by children param tag.
FORM 1:
We can use this standard action to append session information and form
parameters to the url in URL Redirecting process.
Syntax:
Example:
FORM 2 :
Syntax:
FORM 3:
While formatting the URL we can pass parameters also to the target
resource.
Syntax:
first.jsp
second.jsp
Output:
JspTag interface
The JspTag is the root interface for all the interfaces and classes used
in custom tag. It is a marker interface.
Tag interface
The Tag interface is the sub interface of JspTag interface. It provides
methods to perform action at the start and end of the tag.
Fields of Tag interface
There are four fields defined in the Tag interface. They are:
Field Name Description
public static int it evaluates the body content.
EVAL_BODY_INCLUDE
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.
Methods of Tag interface
The methods of the Tag interface are as follows:
Method Name Description
public void it sets the given PageContext
setPageContext(PageContext object.
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 it is invoked by the JSP page
doStartTag()throws implementation object. The JSP
JspException programmer should override this
method and define the business
logic to be performed at the start
of the tag.
public int it is invoked by the JSP page
doEndTag()throws implementation object. The JSP
JspException programmer should override this
method and define the business
logic to be performed at the end
of the tag.
public void release() it is invoked by the JSP page
implementation object to release
the state.
IterationTag interface
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.
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.
public int doAfterBody()throws JspException it is invoked by
the JSP page implementation object after the evaluation of the body. If
this method returns EVAL_BODY_INCLUDE, body content will be
reevaluated, if it returns SKIP_BODY, no more body cotent will be
evaluated.
TagSupport class
The TagSupport class implements the IterationTag interface. It acts as
the base class for new Tag Handlers. It provides some additional
methods also.
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
To create the Tag Handler, we are inheriting the TagSupport class and
overriding its methoddoStartTag().To write data for the jsp, we need
to use the JspWriter class.
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. } }
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
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/>
Output
There can be defined too many attributes for any custom tag. To define
the attribute, you need to perform two tasks:
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:
index.jsp
CubeNumber.java
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
Output
1. Cube of 4 is: 64
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
index.jsp
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_AGAINconstant in the doAfterBody() method.
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
index.jsp
PowerNumber.java
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
Let's create a loop tag that iterates the body content of this tag.
File: index.jsp
File: mytags.tld
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
Output
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.
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.
index.jsp
web.xml
mytags.tld
PrintDate.java
index.jsp
1. <%@ taglib uri="mytags" prefix="m" %>
2. Today is: <m:today></m:today>
web.xml
mytags.tld
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. }
MVC in JSP
Model 1 and Model 2 (MVC) Architecture
1. Model 1 Architecture
2. Model 2 (MVC) Architecture
Model 1 Architecture
Servlet and JSP are the main technologies to develop the web
applications.
Servlet was considered superior to CGI. Servlet technology doesn't
create process, rather it creates thread to handle request. The
advantage of creating thread over process is that it doesn't allocate
separate memory area. Thus many subsequent requests can be easily
handled by servlet.
As you can see in the above figure, there is picture which show the flow
of the model1 architecture.
Model represents the state of the application i.e. data. It can also have
business logic.
File: ControllerServlet
1. package com.hftech;
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 response)
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>