JSP Complete Notes

You might also like

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

OM

Java Server Pages


Index
JSP API
1.Introduction
2.JspPage Interface
3.HttpJspPage Interface
4.Pre compilation
3:IMPLICIT OBJECTS
1.Introduction
2.request
3.response
4.application
5.session
6.out
7.exception
8.Exception Handling
9.page context
10.page
11.config
4. SCOPES & ATTRIBUTES
1.Page
2.Request
3.Session
4.Application
5: DIRECTIVES
1.introduction
2.page
3.include
4. taglib
6: STANDARD ACTIONS
1.Introduction
2.<jsp:useBean>
3.<jsp:getProperty>
4.<jsp:setProperty>
5.<jsp:include>
6.<jsp:forward>
7.<jsp:param>
8.<jsp:plugin>
9. conclution
7. SCRIPTING ELEMENTS
1.Expression
2.Declaration
3.Scriptlet
4.Comment
8. EXPRESSION LANGUAGE

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

10. Custom 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.

The JSP API consists of two packages:

1. javax.servlet.jsp
2. javax.servlet.jsp.tagext(used for custom tag API)

jsp API javax.servlet.jsp:

The javax.servlet.jsp package has two interfaces and classes.The two


interfaces are as follows:

1. JspPage
2. HttpJspPage

The classes are as follows:

 JspWriter
 PageContext
 JspFactory
 JspEngineInfo
 JspException
 JspError

JspPage
======
javax.servlet.jsp.JspPage:
Introduction:

This interface defines the following two life cycle methods.


1. jspInit()
2. jspDestroy()

1.jspInit() :

syntax : public void 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”);
}
%>

We can’t override init(ServletConfig config) in our JSP, because it is


declared as final in parent class (HttpJspBase).
Init() method syntax in HttpJspBase class

public final void init(javax.servlet.ServletConfig config)


throws javax.servlet.ServletException

HttpJspBase:

<%!
public final void init(serveletconfig config)
{
System.out.println (“my own initialization activities”)’
}
%>
CE-
Cannot override the final method from HttpJspBase.

2. jspDestroy():

Syntax: public void 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
}
%>

We can’t override destroy() method directly in the JSP.Because it is declared


as the final in HttpJspBase class.
Test.jsp
<%!
public void destroy( )
{
System.out.println(“my own clean up operations”);
}
%>

C.E: cannot override the final method from HttpJspBase.

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

The benefits of pre-compiling a JSP page:


It removes the start-up lag that occurs when a container must translate a JSP
page upon receipt of the first request.
Since the Java compiler is not needed, there will be a reduction of the
footprint needed to run a JSP container.
In include directives, tag library references, and translation-time actions used
in custom actions, compilation of a JSP page provides resolution of relative
URL specifications.

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.

JSP Implicit objects


Introduction

JSP Implicit objects


===============
1. JSP container provides a list of objects for you to access different kind of
data in a web application. Those objects are called implicit object because it
is automatically available to access.
2. These implicit objects are Java objects that implement interfaces in the
Servlet and JSP API.

There are nine (9) JSP implicit objects available.

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.

JSP Implicit objects REQUEST

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.

Methods of request Object:

There are numerous methods available for request Object. Some of


them are:

1.getCookies() The getCookies() method of request


object returns all cookies sent with the
request information by the client. The
cookies are returned as an array of
Cookie Objects.
2.getHeader(String name) The method getHeader(String name)
of request object is used to return the
value of the requested header.
3.getHeaderNames() The method getHeaderNames() of
request object returns all the header
names in the request.
4.getAttribute(String name) The method getAttribute() of request
object is used to return the value of the
attribute. The getAttribute() method
returns the objects associated with the
attribute.
5.getAttributeNames() The method getAttribute() of request
object is used to return the object
associated with the particular given
attribute.
6.getMethod() The getMethod() of request object is
used to return the methods GET,
POST, or PUT corresponding to the
requested HTTP method used.
7.getParameter(String name) getParameter() method of request
object is used to return the value of a
requested parameter.
8.getParameterNames() The getParameterNames() method of
request object is used to return the
names of the parameters given in the
current request.
9.getParameterValues(String The getParameter(String name)
name) method of request object was used to
return the value of a requested given
parameter.
10.getQueryString() The getQueryString() method of
request object is used to return the
query string from the request.
11.getRequestURI() The getRequestURI() method of
request object is used for returning the
URL of the current JSP page.
12.getServletPath() The getServletPath() method of
request object is used to return the
part of request URL that calls the
servlet.
13.setAttribute(String,Object) The setAttribute method of request
object is used to set object to the
named attribute.
14.removeAttribute(String) The removeAttribute method of
request object is used to remove the
object bound with specified name from
the corresponding session.

Example:
Test.jsp:

<%@ page import = " java.util.* " %>


<html>
<head>
<title>Getting a header in Jsp</title>
</head>
<body>
<%
Enumeration enumeration = request.getHeaderNames();
out.print("<table border= 2>");
while (enumeration.hasMoreElements()) {
String string = (String)enumeration.nextElement();
out.println("<tr><td><h3>" +string +":</h3></td><td><h3> "+
request.getHeader(string)+ "</h3></td></tr>");
}
out.print("</table>");
%>
</body>
</html>
Output:

JSP Implicit object RESPONSE


RESPONSE OBJECT

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.

Methods of response Object:

There are numerous methods available for response object. Some of


them are:

1.setContentType() setContentType method of response


object is used to set the MIME type and
character encoding for the page.
2.addCookie(Cookie addCookie method of response object is
cookie) used to add the specified cookie to the
response.
3.addHeader(String addHeader method of response object is
name, String value) used to write the header as a pair of name
and value to the response.
4.containsHeader(String containsHeader method of response
name) object is used to check whether the
response already includes the header
given as parameter.
5.setHeader(String name, setHeader method of response object is
String value) used to create an HTTP Header with the
name and value given as string.
6.sendRedirect(String) sendRedirect method of response object is
used to send a redirect response to the
client temporarily by making use of
redirect location URL given in parameter.
7.sendError(int sendError method of response object is
status_code) used to send an error response to the
client containing the specified status code
given in parameter.

Example: test.jsp

<%@ page language="java" %>


<%
response.setContentType("text/html");
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
out.print("Is cache-controle available :"+response.containsHeader("Cache-Control"));
%>
<html>
<head>
<title>Response object in cache controlling</title>
</head>
</html>
JSP Implicit objects APPLICATION

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.

Methods of Application Object:

There are numerous methods available for Application object. Some of the
methods of Application object are:

1.getAttribute(String name) The method getAttribute of Application


object is used to return the attribute with the
specified name.
2,getAttributeNames The method getAttributeNames of
Application object is used to return the
attribute names available within the
application.
3.setAttribute(String The method setAttribute of Application
objName, object is used to store the object with the
Object object) given object name in the application.
4.removeAttribute(String The method removeAttribute of Application
objName) object is used to remove the name of the
object mentioned in parameter of this
method from the object of the application.
5.getMinorVersion() The method getMinorVersion of
Application object is used to return the
minor version of the Servlet API for the JSP
Container.
6.getServerInfo() The method getServerInfo of Application
object is used to return the name and
version number of the JRun servlet engine.
7.getInitParameter(String The method getInitParameter of Application
name) object is used to return the value of an
initialization parameter.
8.getInitParameterNames The method getInitParameterNames of
Application object is used to return the
name of each initialization parameter.
9.getResourceAsStream(Path) The method getResourceAsStream of
Application object is used to translate the
resource URL mentioned as parameter in
the method into an input stream to read.
10.log(Message) The method log of Application object is
used to write a text string to the JSP
Container’s default log file.
11.getMajorVersion() The method getMajorVersion of
Application object is used to return the
major version of the Servlet API for the JSP
Container.

Example:

Add this piece of code in web.xml

<context-param>
<param-name>user</param-name>
<param-value>ank567</param-value>
</context-param>

Test.jsp

<%@ page session="true" %>


<%

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>

JSP Implicit objects SESSION


SESSION OBJECT
Introduction:
1. session object is an instance of class javax.servlet.http.HttpSession.
2. The session object is used to store and retrieve client information across the
multiple requests. The session object is not available if the session="false" is
used in page directive.
3. The previous two objects, request and response, are used to pass information
from web browser to server and from server to web browser respectively. The
Session Object provides the connection or association between the client and
the server.

Methods:

1.getCreationTime This method is used to return the session


created time
2. getLastAccessedTime The getLastAccessedTime method of session
object is used to return the latest time of the
client request associated with the session.
3.getId The getID method of session object is used to
return the unique identifier associated with the
session.
4.invalidate() invalidate method of session object is used to
discard the session and releases any objects
stored as attributes.

5.getMaxInactiveInterval The getMaxInactiveInterval method of session


object is used to return the maximum amount
of time the JRun keeps the session open
between client accesses.
6.setMaxInactiveInterval() This is another setMaxInactiveInterval()
method that a developer can use to set the
timeout explicitly for each session.
7.removeAttribute(String The removeAttribute method of session object
name) is used to remove the attribute and value from
the session.
8.setAttribute(String, The setAttribute method of session object is
object) used to set the object to the named attribute.

Example: test.jsp

<%@ page session="true" %>


<%
session.setMaxInactiveInterval(600);
session.setAttribute("SITE", "hftech.com");

%>
<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:

1. This implicit object is of type javax.servlet.jsp.JspWriter.


2. This class is specially designed for Jsp’s to write data to the response.
3. JspWriter object (out) maintain buffer to store response data before write
into the response object.
4. Except this buffer there is no difference between JspWriter and
PrintWriter.
5. Within the Jsp we can use either PrintWriter (or) JspWriter but not
recommended to use both simultaneously.
6. JspWwriter is the child class of Writer hence all methods of Writer class
are by default available to theJspWriter through inheritance.
7. In addition to these methods JspWriter can contain two methods print() &
printIn ( ) methods to add any type of response to the Jsp.

Methods of out Object:

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.

Note : JspWriter = PrintWriter+Buffer

Example: test.jsp

<%@ page session="true" %>


<%
application.setAttribute("SITE", "hftech.com");
%>
<table border= 2>
<%
out.println("<tr><td>Buffer Size : </td><td>" + out.getBufferSize()+"</td></tr>");
out.println("<tr><td>Is AutoFlush Enable</td><td> " +
out.isAutoFlush()+"</td></tr>");
out.println("<tr><td>Remaining Buffer Size </td><td>" +
out.getRemaining()+"</td></tr>");
out.println("<tr><td>SITE </td><td>" +
application.getAttribute("SITE")+"</td></tr>");
%>
</table>

JSP Implicit object EXCEPTION

EXCEPTION OBJECT
exception implicit objects

1. The JSP implicit exception object is an instance of


the java.lang.Throwable class.
2. JSP gives you an option to specify Error Page for each JSP. Whenever the
page throws an exception, the JSP container automatically invokes the error
page.
3. And is only available in error pages. Following is the list of important
methods available in the Throwable class..

Methods:

1.public String getMessage()

Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor.

2. public Throwable getCause()

Returns the cause of the exception as represented by a Throwable object.

3.public String toString()

Returns the name of the class concatenated with the result of getMessage()

4.public void printStackTrace()

Prints the result of toString() along with the stack trace to System.err, the
error output stream.

5.public StackTraceElement [] getStackTrace()

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.

6.public Throwable fillInStackTrace()

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

<%@ page errorPage="ShowError.jsp" %>


<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1)
{
throw new RuntimeException("Error condition!!!");
}
%>
</body>
</html>

ShowError.jsp

<%@ page isErrorPage="true" %>


<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>

Output:

java.lang.RuntimeException: Error condition!!!


......

Opps...
Sorry, an error occurred.

Here is the exception stack trace:

JSP EXCEPTION HANDLING

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:

We can configure error pages according to a particular exception (or)


according to error code in web.xml as follows.

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

If we are configuring error pages in declarative approach that error page is


applicable for entire application.

2. Programmatic Approach

We can configure error page for a particular Jsp by using error page attribute
of page Directive.
Test.jsp

<% @ page errorPage = “/Error.jsp” %>


<h1> The Result is: <% = 10/0 %>

Test.jsp if any exception (or) error occurs then error.jsp is responsible to


report this error.
Programmatic Approach error page configuration is applicable only for a
particular Jsp.
We can declare a Jsp as error page by using isErrorPage attribute of page
directive.
In this error pages only exception implicit object is available.

Error.jsp

<%@ page isErrorPage = “true” %>


<h1> can you plz provide valid input <br>
The Exception is: <% = exception %></h1>

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.

Which approach is recommended:

Declarative approach is always recommended because we can customize


error pages based on exception type (or) error code. Such type of approach is
called Declarative.
The following implicit objects are specially designed for Jsp’s.

Note : All Jsp implicit objects are available as local variables of


_jspService(). So we can use this implicit objects within _jspService( )
but outside of _jspService() we can’t use , that means we can use inside
scriptlet and expression but we can’t use inside declaration tag.
Example: main.jsp

<%@ page errorPage="ShowError.jsp" %>


<html>
<head>
<title>Error Handling Example</title>
</head>
<body>
<%
// Throw an exception to invoke the error page
int x = 1;
if (x == 1)
{
throw new RuntimeException("Error condition!!!");
}
%>
</body>
</html>

ShowError.jsp

<%@ page isErrorPage="true" %>


<html>
<head>
<title>Show Error Page</title>
</head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.</p>
<p>Here is the exception stack trace: </p>
<pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre>
</body>
</html>

Output:

java.lang.RuntimeException: Error condition!!!


......
Opps...
Sorry, an error occurred.

Here is the exception stack trace:

JSP Implicit objects pageContext

PAGECONTEXT OBJECT

7.pageContext :

1. pageContext variable is of type javax.servlet.jsp.PageContext.


2. The PageContext class is the abstract class and JSP engine vendor provides
its concrete subclass.
3. We can use pageContext implicit object for the following purpose

 To get all other jsp implicit objects


 Provide method to get and set attributes in different scopes.
 Provide convenience methods for transferring request to other resources in
web application.
PageContext.forward(“other.jsp”);

1. Getting Jsp implicit objects from pageContext

PageContext class defines the following methods for this.

 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.

2.Attribute Management in any scope

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

1. page
2. request
3. session
4. application

In JSP, page scope is the default scope.

Example:

pageContext.setAttribute("user","hftech.com",PageContext.SESSION_SCOP
E);

3.Request Dispatching by pageContext

We can perform Request Dispatching by using pageContext.


For this PageContext class defines the following methods.

1. public void forward (String target)


2. public void include (String target)

JSP Implicit object page


PAGE OBJECT
Page implicit object

1. The JSP implicit page object is an instance of the java.lang.Object class. It


represents the current JSP page.
2. That is, it serves as a reference to the java servlet object that implements the
JSP page on which it is accessed. It is not recommended to us this because it
consumes large memory.
3. The page object works like “this” key word in java.
4. In the generated servlet, the variable is declared as follows
Object page = this;
Parent reference can be used to hold child class object but, by using that
reference we are allow to call only the methods available in the parent class.

Note : page cannot be used to directly call the servlet methods

 page.getServletInfo()
Error because page is java.lang.Object type
 ((servlet)page).getServletInfo()
 this.getServletInfo()

JSP Implicit objects config


CONFIG OBJECT
config implicit object

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:

In Servlets we have the following 3 scopes for storing information in the


form of attributes.

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:

1. public void setAttribute (String name, Object value);


2. public void getAttribute (String name);
3. public void remove Attribute (String name);
Attribute Management in any scope:

PageContext class defines the following methods to perform attribute


management in any scope.
1. public void setAttribute (string name, object value, int scope);

Here scope value must be 1 to 4

PageContext.PAGE-SCOPE = 1
PageContext.REQUEST-SCOPE = 2
PageContext.SESSION-SCOPE = 3
PageContext.APPLICATION-SCOPE = 4

Example:
setAttribute(“uname”,”ank567”,1)

2. public Object getAttribute (String name, int scope);


3. public void removeAttribute (String name, int scope);
4. public Enumeration getAttribute NamesInScope(int scope);
5. public Object findAttribute (String name);
First it will search in page scope for desired attribute, if it is not available
then it will search in request scope followed by session scope and application
scope.
page – request – session – application.

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>

Using Beans and Page Scope


couter value is 3

REQUEST SCOPE IN JSP


Request Scope in JSP
1. Request Scope :

1. In Jsp request scope is maintained by request implicit object .


2. The information is stored in the request scope is available for all components
which are processing that request.
3. request scope will start at the time of of request object creation and ends at
the time of request object destroy.
4. ServletRequest interface defines the following methods to perform attribute
management in request scope.

Methods:

 public void setAttribute(String name, Object value)


 public object getAttribute (String name)
 public void removeAttribute (String name)
 public Enumeration getAttributeNames ( )

SESSION SCOPE IN JSP WITH EXAMPLE


SESSION SCOPE IN JSP
Session Scope
1. In Servlets this scope is maintained by HttpSession object, but in in Jsp
maintained by session implicit object.
2. Session scope will be started at the time of session object creation and ends
at the time of session object destroy.
3. The information is stored in session scope is by default available to all
servlets and jsps available in that web application.
4. HttpSession interface defines the following methods to perform attribute
management in session scope.

Methods:

 public void setAttribute (String name, Object value)


 public Object getAttribute (String name)
 public void removeAttribute (String name)
 public Enumeration getAttributeNames ( )

Application scope in jsp with example


APPLICATION SCOPE IN JSP
Application Scope

1. We can maintain this scope in servlet by using ServletContext object. But in


jsp’s by using application implicit object.
2. The information stored in application scope is by default available for all
web applications in the tomcat .
3. application scope will be started at the time of context object creation and
ends at the time of context object destroy .
4. ServletContext interface defines the following methods to perform attribute
management in application scope.
Methods:

 public void setAttribute (String name, Object value)


 public Object getAttribute (String name)
 public void removeAttribute (String name)
 public Enumeration getAttributeNames ( )

Jsp Directives Introduction


Jsp Directives

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:

<%@ directive_name attribute_name = attribute_value %>

There are three types of directive tag.

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:

1. Without import attribute


<h1>The Server time is: <%= new java.util.Date( )%></h1>

2. With import attributes

<%@ page import = "java.util.*" %>


<h1>The Server time is: <%= new Date( )%></h1>

Output:

Case 2 :

To import multiple packages the following are various possibilities.


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

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.

1. <%@ page session="true" session = 'true' %>


// one attribute with same value

2: <%@ page session="true" session = 'false' %>


// same attribute with different 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.

<%@ page isError Page =”true” %>

2. Session
Syntax:
<%@ page session = “true” %>

Note: The default value of the session attribute is 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

<%@ page session = “hftech” %>

Translation time error : Invalid value for session attribute.

3. Content Type

Definition : We can use this attribute to specify content type and character set
of the response

Syntax : <%@ page contentType="text/html; charset=ISO-8859-1" %>

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 :

1. In jsp 1.2 version expression languages has introduced.The main objective of


Expression Language is to eliminate java, Code from the Jsp.
2. The isELIgnored attribute takes boolean value of true or false as input.
3. If isELIgnored is true, then any Expression Language in JSP is ignored.
4. The default value of isELIgnored is false.

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"%>

According to jsp 1.2 version :

Case 1: isELIgnored = “true”


Expression language is disabled in the Jsp and any Expression Language Syntax
treated as Template text .

test.jsp

<%@page isELIgnored="false"%>
Additon : ${2+3}

Output:

Case 2 : isELIgnored = “false”

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"%>

Case 1 : 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.

Case 2: isThreadSafe = “false”

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.

Syntax: <%@ page isErrorPage="false" %>

Case 1: isErrorPage = “false”

1. The exception implicit object is not available to a JSP page


2. The default value of isErrorPage is false.

Case 2: isErrorPage = “true”

1. The exception implicit object is available to a JSP page,


2. And this page act as a error page .

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 :

<@ page errorPage = "relativeURL" %>

Example:

<%@ page errorPage = "/myjavahub/error.jsp" %>

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:

<%@ page extends="class name" %>

Example:

For example, the following page directive indicate the JSP translator to
generate the servlet with extendshftech/test

<%@ page extends="hftech/test" %>

Note: extends attribute usage is very rare.

jsp page directive with buffer,autoFlush,info,pageEncoding


Attributes
10. Buffer
Introduction :

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

Syntax: <%@ page buffer= "integer/none” %>

Case 1 :setting buffer size


The buffer attribute of page directive may also be used to change the buffer
size. The example below sets the buffer size to 4 KBytes.

Ex: <%@ page buffer="4kb" %>

In this case all the servlet output write into the buffer before writing to the
response object.

Case 2: disable buffer future

You may code a buffer value of "none" to specify no buffering so that all
servlet output is immediately write into the response object .

<%@ page buffer="none" %>

11. autoFlush

Introduction:

1. The autoflush attribute of page directive is used to indicate JSP containers


behavior when the buffer gets full.
2. autoflush attribute takes boolean values true or false as input. The default
value for autoflush is true.

Syntax: <%@ page autoFlush="true/false" %>

Case 1 : autoFlush = “false”

If autoflush is set to false, if the buffer gets full, JSP container will raise an
exception.

<%@ page autoFlush="/false" %>

Case 2: autoFlush = “true”

1. the default value of the jsp page autoFlush attribute is “true” .


2. If autoflush is set to true, if the buffer gets full, JSP container will flush the
data into response object.

12. info
Introduction:

1. this attribute provide the information regarding current jsp page.


2. The JSP container ignores the info attribute.
3. The info attribute is meant for JSP programmers to help them understand
about the functionality of the page.

Syntax: <%@page info="content"%>

Example:

<%@page info="this document is provided by hftech team" %>

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.

Example :<%@ page pageEncoding="GBK" %>

jsp Include Directive


Include Directive
Introduction :

1. <%@ include file=”filename” %> is the JSP include directive.


2. At JSP page translation time, the content of the file given in the include
directive is ‘pasted’ as it is, in the place where the JSP include directive is
used.
3. Then the source JSP page is converted into a java servlet class. The included
file can be a static resource or a JSP page.
4. If several Jsp’s requires some common code it is recommended to separate
that common code in a separate file where ever it is required we have to place
one include call.

Syntax: <%@ include file=”filename” %>

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:

<h2>This is First JSP</h2>


<%@ include file="/second.jsp" %>

second.jsp

<h2> This is second JSP </h2>

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

<%@ taglib uri="uri" prefix="prefixOfTag" >

Attributes:

Taglib directive contains two attributes

1.prefix : prefix attribute informs a container what bits of markup are custom
actions.

2.uri : uri represents the location of tag libraries.

Example:

<%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %>


<html>
<body>
<mytag:hello/>
</body>
</html>
JSP Standard Actions Intraduction
STANDARD ACTIONS
Introduction:

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.

Action Element Description


<jsp:useBean> Enables JavaBeans components in that page
Get a property value from JavaBeans
<jsp:getProperty>
component and adds to the response
<jsp:setProperty> Sets the JavaBeans property value
Includes the response from the jsp page while
<jsp:include>
processing.
Forwards the processing of a request to ajsp
<jsp:forward>
page
Adds a parameter value to a request handed
<jsp:param>
off using the <jsp:include or <jsp:forward>
Generates a HTML elements appropriate to a
<jsp:plugin> browser to execute an applet using Java
Plugin.
Sets the value of the action element based on
<jsp:attribute>
the body of this element.
Sets action element body based on the body
<jsp:body>
of this element.
<jsp:element> Dynamically generates XML element.
Encapsulates template text, needed in JSP
<jsp:text>
pages written in XML.
JSP STANDARD ACTION
STANDARD ACTIONS
Introduction:

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:

 It should have a no-arg constructor.


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

Why use Java Bean?


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

Simple example of java bean class

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. }

How to access the java bean class?

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:

1. If we are using scriptlet and expression there is no clear separation of


presentation and business logic.
2. The person who is writing Jsp should have compulsory the knowledge of
both Java and html which may not possible always.
3. It reduces the readability and maintainability.
4. It reduces reusability of the code also.
We can recover these problems by encapsulating business logic inside a Java
Bean class.
Syntax:

<jsp:useBean id="objectName" class="package.class" />


Example:

SimpleBean.java

package com.hftech;

public class SimpleBean


{
private String uname ;
private String password ;
private String mail ;
private String mobileno;

public String getUname() {


return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getMobileno() {
return mobileno;
}
public void setMobileno(String mobileno) {
this.mobileno = mobileno;
}
}

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:

The main Advantages of this approach are

 Separation of presentation & business logic


Business logic is available in Bean Class and presentation logic available in
Jsp. It improves readability and maintainability of the code.

 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.

 It promotes reusability of the code.


Where ever square It functionality is required we can use the same Bean
without rewiring.
We can purchase a bean for file uploading and we can start uploading of files
within a few minutes.

<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

<jsp:useBean id="b" class="com. hftech.SimpleBean">


</jsp:useBean>

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.

What is the java bean ?

A Java Bean is a simple java class.


 The bean class should compulsory contain public no argument constructor
otherwise
<jsp: useBean> tag won’t work .
 For every property public getter and setter methods are required otherwise
<jsp: getProperty> and jsp: setProperty> won’t work properly.

Attributes of <jsp: useBean>:

<jsp:useBean> tag can contain the following five attributes.

 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

It specifies fully qualified Name of the Bean class.


For this class only Jsp engine performs instantiation and class should be
concrete class, Abstract classes and interfaces are not allowed for class
attribute.
Class attribute is optional but we have to specify either class attribute or type
attribute is mandatory

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

Note: scope attribute is optional and default scope is page.

<% @ page session = “false”%>


<jsp: UseBean id= “c” class= “pack1.calculatorBean” scope= “session”/>
Error:-Illegal for Use Bean to use session scope when Jsp page declares (via
page directive) that is does not participate in sessions.

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.

EX : <jsp: useBean id= “c” type= “java.lang.Runnable” scope= “session”/>

Jsp engine searches for Runnable type object with “c” name in session
scope. If it is not available then it raises runtime exception.

JSP STANDARD ACTION jsp:getProperty


<jsp:getProperty>
Introduction :

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:

You can use <jsp:getProperty> with JavaBeans components, but not


with enterprise beans. As alternatives, you can write a JSP page that
retrieves values from a Bean that in turn retrieves values from an
enterprise bean, or you can write a custom tag that retrieves values
from an enterprise bean directly.
Example:

getProperty Getter methods


<%
<jsp: useBean id= “s” class= “Student”/> Student s=new Student( );
<jsp: getProperty name= “s” property= out. printIn (s.getAge( ));
“age”/> %>

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.

2. Property : property name of the bean class to retrieve .

Test.jsp

<%@ page import = “pack1.*”>


<jsp:useBean id= “s” calss= “pack1.Student”/>
Student Name: <jsp: getProperty name= “s” property= “name”/>
Student Mail : <jsp: getProperty name= “s” property= “mail”/>

Student.java

package pack1;
Public class StudentBean
{
private String name= “hftech”
private String mail=” hftech2014@gmail.com”;
public String getName ( )
{
return name;
}
public String getMail ( )
{
return mail;
}
}

Output:

Student Name: hftech


Student Mail : hftech2014@gmail.com

JSP STANDARD ACTION jsp:setProperty


<jsp: setProperty>
Introduction:

1. The <jsp:setProperty> element sets the value of one or more properties in a


Bean, using the Bean's setter methods.
2. You must declare the Bean with <jsp:useBean> before you set a property
value with <jsp:setProperty>. Because <jsp:useBean> and <jsp:setProperty>
work together,
3. the Bean instance names they use must match (that is, the value of name in
<jsp:setProperty> and the value of id in <jsp:useBean> must be the same).

Syntax:

<jsp:setProperty name = “bean instance name” property = “name” value = “vlaue”>

Description:

We can use this standard action in the following combinations.

1. <jsp:setProperty property="uname" name="b" value=" hftech0001"/>

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" />

4. <jsp:setProperty property="*" name="b"/>


‘*’ specifies all properties of the bean

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

<jsp:useBean id="b" class="com. hftech.SimpleBean"></jsp:useBean>


<jsp:setProperty property="mail" name="b" value="ank001@gmail.com"/>
<jsp:setProperty property="*" name="b"/>
<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>Age</h2></td><td><h2><%= b.getAge()%></h2></td></tr>
<tr><td><h2>Mail Id</h2></td><td><h2><%= b.getMail()%></h2></td></tr>
</table>

SimpleBean.java

package com.hftech;

public class SimpleBean


{
private String uname ;
private int age;
private String mail ;

public int getAge() {


return age;
}
public void setAge(int age) {
this.age = age;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
}

Note: All the required type conversions will take care by automatically by
the <jsp:setProperty> :(string to int).

Note: It is always a good programming practice to maintain form parameter


name are exactly same as bean property names.

JSP STANDARD ACTION jsp:include


<jsp:include>
Introduction:

1. The <jsp:include> element allows you to include either a static or dynamic


file in a JSP file.
2. If the file is static, its content is included in the calling JSP file. If the file is
dynamic, it acts on a request and sends back a result that is included in the
JSP page.
3. When the include action is finished, the JSP container continues processing
the remainder of the JSP file.
4. If the included file is dynamic, you can use a <jsp:param> clause to pass the
name and value of a parameter to the dynamic file

Syntax:

<jsp:include page= “header.jsp” flush= “true” />

The Response of header.jsp will be placed in the current response at request


processing time (Run time). Hence it is dynamic include.
<jsp: include> is a tag representation of pageContext.include (“header.jsp”);
This standard action contains the following 2 attributes.
 page : It represents the name of the included page. It is a mandatory attribute.

 flush : It specifies whether the response will be flushed before inclusion (or)
not. it is optional attribute. The default value is false.

< jsp:include page= “header.jsp” flush= “true” />


<%
pageContext. include (“header.jsp”);
%>

Example: first.jsp

<h2>This is First JSP</h2>


<jsp:include page = "/second.jsp" %>

second.jsp

<h2> This is second JSP </h2>

Output:

Note : In total the following are 4 possible ways to perform inclusion.


 Include Directive

<%@ include file= “header.jsp” %>

 Include Action
<jsp:include page= “header.jsp” %>

 By using pageContext implicit object:-


<%
pageContext.include(“header.jsp”);
%>

 By using RequestDispatcher
<%
RequestDispatcher rd= request.getRequestDispatcher (“header.jsp”);
rd.include(request, response);
%>

JSP STANDARD ACTION jsp:forward


<jsp:forward>
Introduction:
1. The <jsp:forward> element forwards the request object from one JSP file to
another file.
2. The target file can be an HTML file, another JSP file, or a servlet, forwarded
files must me with in same web application.
3. As long as it is in the same application context as the forwarding JSP file.
The lines in the source JSP file after the <jsp:forward> element are not
processed.
<jsp: forward page= “/second.jsp” />

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

<h2>This is First JSP</h2>


<jsp:forward page="/second.jsp"></jsp:forward>

second.jsp

<h2> This is second JSP </h2>

Output: http://localhost:8080/Scwcd_jsp/first.jsp
1. Forward Standard Action
<jsp: forward page= “/second.jsp>

2. By Using Page Context Implicit Object


<%
pageContext.forward (“second.jsp”);
%>

3. By Using RequestDispatcher
<%
RequestDispatcher rd=request.getRequestDispatcher (“second.jsp”);
rd.forward (req., resp);
%>

JSP STANDARD ACTION jsp:param


<jsp:param>
Introduction:

1. While performing forward or include we can send parameters to target


page for this we have to use<jsp:param>
2. We can pass the parameter names and values to the forwarded file by using a
<jsp: param> tag. We can use multiple <jsp: param> tag inside the <jsp:
forward> tag if we have to pass more than one parameter to the target file.

Syntax:

<jsp:param name= “course1” value= “jsp1”/>

Attributes:

This standard action defines the following 2 mandatory attributes:


 name :The name of the parameter.
 value : Value of the parameter.
Example:

first.jsp

<h2>This is First JSP</h2>


<jsp:include page="/second.jsp">
<jsp:param value="scjp" name="course1"/>
<jsp:param value="scwcd" name="course2"/>
</jsp:include>

second.jsp

<%@ page isELIgnored="false" %>


<h2> This is second JSP </h2>
<h3>course 1: ${param.course1}</h3>
<h3>course 2: ${param.course2}</h3>

Output: http://localhost:8080/Scwcd_jsp/first.jsp

Standard Action jsp:plugin


Jsp:plugin
Syntax

<jsp:plugin
type="bean|applet"
code="classFileName"
codebase="classFileDirectoryName"
</jsp:plugin>

Description

1. The <jsp:plugin> tag is replaced by either an <object> or <embed> tag,


whichever is most appropriate for the client Web browser (the <object> tag is
for browsers that use HTML 4.0).
2. The <jsp:params> element sends parameter names and values to an applet or
Bean at startup.
3. The <jsp:fallback> element provides a message for the user if the plugin does
not start. If the plugin starts but the applet or Bean does not, the plugin
usually displays a popup window explaining the error to the user.

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:

JSP STANDARD ACTION final conclusion


Conclusion
Case1:

1. <jsp:forward page= http://localhost :8080/jspl/second.jsp />


2. <jsp:include page= http://localhost : 8080/jspl/second.jsp />
3. <%@ include file= http://localhost : 8080/jspl/second.jsp />

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:

1. <jsp:forward page= “/test”/>


2. <jsp:include page= “/test”/>
3. <%@ include file= “/test”/>

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:

1. <jsp:forward page= “second.jsp?c1=scjp”/>


2. <jsp: include page= “second.jsp?c1=scjp”/>
3. <%@ include file= “second.jsp?c1=scjp”/>

First and second are valid third is invalid.


In the case of forward and include action we are allow to pass query string
but in the case of include directive we can’t pass query string.
Scripting element Expression
Expression
Definition:

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 :

<%= java expression %>


Example:

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

<%@ page import="java.util.*"%>


<h2><%= new Date();%></h2>

Output:
Ex2 : test.jsp

<%@ page import="java.util.*"%>


<h2><%= new Date()%></h2>

Output:

Case 2:

Within the expression we can take method calls also but void return type
method calls are not allowed.

Ex:

<%@ page import="java.util.*"%>


<%= Math.random() %>
<%= new java.util.ArrayList().clear() %>

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:

<%@ page import="java.util.*"%>


<% = new Date() %>

<% = 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 :

<% java code %>

Description:

1. JSP Scriptlets begins with <% and ends %>


2. JSP Engine places these code in the _jspService() method
3. A scriptlet doesn't contribute any HTML.
4. Every statement inside scriptlet should ends with semicolon.
5. By itself a scriptlet does not generate HTML. If a scriptlet wants to
generate HTML, it can use a variable called "out".here “out “ is a
implicit object we will discuss later.
Ex: out.println(“<table><tr><td>”);
Out.println(“hftech</td></tr></table>”);

Scriptlet hit count example :

Write a jsp to display hit count of the jsp ?

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

Scripting element Declaration


Declaration
Definition:

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:

<%! Java code …. %>

Description:

1. These declarations will be placed directly in the generated servlet, but


outside of _jspService( ) method.
2. Every java statement inside declaration tag will should ends with semi colon.
3. A declaration doesn't contribute any HTML.

Example:test.jsp

<%@ page import="java.util.*" %>


<HTML>
<BODY>

<%!
Date d = new Date();
public Date getDate()
{
System.out.println( "In getDate() method" );
return d;
}
%>

<h2>Hello! The time is now : : <%= getDate() %></h2>


</BODY>
</HTML>

Output: http://localhost:8080/Scwcd_jsp/test.jsp

Note : All Jsp implicit object are local variables of _jspService ( ) so we


can’t use jsp implicit objects directly in declaration tag.
jsp comments ,java comment, Html comment
Comments
Inside jsp we can use three types of comments.
1. Jsp comments
2. Html/xml comments
3. Java comments

1. Jsp Comments:

Syntax :

<%-- comment --%>

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 :

<%@ page import="java.util.*" %>


<%
String s = "hftech";
out.println("<h2>"+s);
%>
<%-- This JSP comment part will not be included in the response object --
%>
: : : <%= new Date()%>
2. HTML/XML Comment:

Syntax:

< ! - - XML/HTML Comment - - >

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:

1. // single line comment


2. /* multi line crmment */

Description:

1. These are also known as scripting comments.


2. These are visible in the generated servlet source code. And not visible in the
remaining phases.

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:

1. It has introduced in Jsp 2.0 version.


2. The main objective of ExpressionLanguage is to eliminate java code from
the Jsp.
3. In General we can use ExpressionLanguagge with JSTL and custom tags for
complete elimination of java code
.
Syntax: ${expr}

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.

Ex: To print the value of request parameter username.

ExpressionLanguage Jsp expression


${param.uname} <% = request. getparameter (“uname”) %>

Ex: To print the value of scoped attribute “x” .


ExpressionLanguage Jsp Expression
${x} <% = pageContext. findAttribute (“x”) %>

Note:

To use any variable x in ExpressionLanguage directly compulsory it should


an attribute in some scope.

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.

Implicit object Description


1. pageScope Scoped variables from page scope
2. requestScope Scoped variables from request scope
3. sessionScope Scoped variables from session scope

4. applicationScope Scoped variables from application scope


5. param Request parameters as strings
6. paramValues Request parameters as collections of strings
7. header HTTP request headers as strings
8. headerValues HTTP request headers as collections of strings
9. initParam Context-initialization parameters
10. cookie Cookie values
11. pageContext The JSP PageContext object for the current page

1.The Scope Objects:


The pageScope, requestScope, sessionScope, and applicationScope implicit
objects are used to retrieve data from request, session,page,application
scopes.
Ex:1 To access the value of session scoped attribute ‘x’ ${sessionScope.x}
It prints the value of request scoped attribute ‘x’
If there is no such type of attribute we will get blank
space ${requestScope.x}

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

<%@ page isELIgnored="false" %>

<%

pageContext.setAttribute ("x", 100);

pageContext.setAttribute ("y", 1000);

pageContext.setAttribute ("X", 10);

%>

<h2> Attribute "x" value in scope : ${x}</h2> <br>

<h2>Attribute "x" in request scope : ${requestScope.x} </h2><br>

<h2>Attribute "y" in session scope : ${sessionScope.y}</h2> <br>

<h2>Attribute 'y' value : ${y}</h2>


OutPut:

EL Implicit Object param & paramValues


param & paramValues
1. We can use these implicit objects to retrieve request parameter values.
These implicit objects works just like getParameter() and
getParameterNames() in servlet.

Expression Language code Jsp code


param request. getParameter (String name );
paramValues request. getParameterValues ( );

Ex: 1 ${param.x}

It prints the value associates with request parameter x .


If the parameter is associated with multiple values, then it prints the
first value.
If the specified parameter is not available then we will get blank space.

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

<%@ page isELIgnored="false" %>


<table border = 2>
<tr><td>param.name :</td><td>${param.name}</td></tr>
<tr><td>param.age:</td><td>${param.age}</td></tr>
<tr><td>param.food:</td><td>${param.food}</td></tr>
<tr><td>paramVales.name[0]:</td><td>${paramVales.name[0]}</td></tr>
<tr><td>paramValues.food[0]:</td><td>${paramValues.food[0]}</td></tr>
<tr><td>paramValues.food[100]:</td><td>${paramValues.food[100]}</td></tr>
<tr><td>paramValues.food[1]:</td><td>${paramValues.food[1]}</td></tr>
</table>

Case 1: http://localhost:8080/Scwcd_jsp/login.jsp

Case 2: Enter name, mail id,food1 and food2 and click on submit
Note:

Expression Language handles NullPointerException and


ArrayIndexOutOfBoundsException very nicely it just suppresses them and
prints blank space.

EL Implicit Object header & headerValues


header& headerValues
The header and headerValues objects are used to retrieve the header
values normally available through the request.getHeader and
request.getHeaders methods.
Ex: To access a header named user-agent, use the
expression ${header.user-agent} or${header["user-agent"]}.

${header.accept}
${headerValues.accept[0]}

test.jsp

<%@ page isELIgnored="false" %>


<table border = 2>
<tr><td>header.cookie :</td><td>${header.cookie}</td></tr>
<tr><td>header.connection</td><td>${header.connection}</td></tr>
<tr><td>headerValues.host[0]</td><td>${headerValues.host[0]}</td></tr>
<tr><td>headerValues.accept[0]</td><td>${headerValues.accept[0]}</td></tr>
<tr><td>header.user-agent</td><td>${header.user-agent}</td></tr>
</table>
Output: http://localhost:8080/Scwcd_jsp/test.jsp

EL Implicit Object cookie


Cookie
We can use this implicit object to retrieve cookies associated with the
request.

Example :${cookie.JSESSIONID}
${cookie.JSESSIONID.name}
${cooke.JSESSIONID.value}

test.jsp

<%@ page isELIgnored="false" %>


<%
Cookie cookie = new Cookie ("username","chamu");
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);
%>
<table border= 2>
<tr><td><h2>${cookie.username.name}</h2></td> <td><h2>${cookie.username.value}</h2><
/td></tr>
<tr><td><h2>${cookie.JSESSIONID.name}</h2></td> <td><h2>${cookie.JSESSIONID.value
}</h2></td></tr>
</table>
First Request:

SecondRequest:

EL Implicit Object initParam


initParam
By using this implicit object we can access context initialization parameters.

ExpressionLanguage Jsp code


initParam.user application.getInitParameter ( “user”)

Ex: ${initParam.user} Output : scott


${initParam.pwd} Output:Blank space.

Add this piece of code in web.xml

<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

<%@ page isELIgnored="false" %>


<%
Cookie cookie = new Cookie ("username","chamu");
cookie.setMaxAge(60 * 60);
response.addCookie(cookie);
%>
<table border= 2>
<tr><td><h2>initParam.user</h2></td> <td><h2>${initParam.user}</h2></td></tr>
<tr><td><h2>initParam.password</h2></td> <td><h2>${initParam.password}</h2></td></tr>
</table>

Output: http://localhost:8080/Scwcd_jsp/test.jsp

EL Implicit Object pageContext


pageContext
Introduction:

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

request ServletRequest The current request

response ServletResponse The current response

servletConfig ServletConfig The servlet configuration

servletContext ServletContext The servlet context

session HttpSession The current session

Ex: 1.${pageContext.request.method}
2.${pageContext.session.id}

EL operators Property Access Operator,Collection Access Operator


EL Operators
Introduction:

Expression Language (EL) contains its own set of operators the following is
the list of all available operators in Expression Language (EL) .

1. Property access operator: (.)


2. Collection access operator : ([])
3. Arithmetic Operators
4. Relational Operators
5. Logical Operators.
1. Property Access Operator: (.)

Syntax:

Ex- ${param.uname}
Map key

Ex: ${initParam.password}
Map key

Ex: ${customer.age}
Bean property

1. Collection Access Operator : []

Syntax: ${LeftVariable [RightVariable]}

LeftVariable : Map , Bean ,Array, List


RightVariable : Key,Property,index

Example for map:

 $ {initParam[“mail”]}

Example for Bean:

 $ {customer [“name”]}

Example for Arrays:

<%@ page isELIgnored="false" %>


<%@ page import="java.util.*" %>
<%
String[ ] s = {"hftech", "java2s", "javaken", "java2share" };
pageContext.setAttribute ("s", s);
%>
${s[0]}<br>
${s[1]}<br>
${s[2]}<br>
${s[3]}<br>
${s[100]}

Example for List:

<%@ page isELIgnored="false" %>


<%@ page import="java.util.*" %>
<%
List<String> l = new ArrayList<String>();
l.add("myjavahub");
l.add("java2s");
l.add("javaken");
l.add("java2share");
pageContext.setAttribute ("List",l);
%>
${List["0"]}<br>
${List["1"]}<br>
${List["2"]}<br>
${List["3"]}<br>

Note:

Where ever property access operator is available we can replace with


collection access, but wherever collections access operator is available we
may not replace with property access operator.
El Arithmetic Operators
Arithmetic Operators
Introcution:
The EL supports the following arithmetic operators.
1. Addition +
2. Subtraction –
3. Multiplication *
4. Division / and div
5. Modulo division % and mod

Addition + : ExpressionLanguage doesn’t support operator overloading


hence “+” operator always meant for arithmetic addition operator.

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 - :

All rules are exactly same as ‘+’ operator.

Ex:
1. ${10-3} Output : 7
2. ${“abc”-3} Output : NumberFormatException.
3. ${abc-3} Output 3

Multiplication * :

All rules are exactly similar to “+” operator.

Ex:
1. $ {10*3} Output: 30
2. ${“abc”*3} Output: NumberFormatException.

Division / and div :

All the rules are exactly same as ‘+’ operator.

Syntax: ${a/b} (or) ${a div b}

Ex:

1. ${10/2} Output : 5.0


2. ${10/0} Output : Infinity

Note : Division operator always follows floating point arithmetic but not
integral arithmetic.

System.out.println (10/0) Output: ArithmeticException / Zero


System.out.println (1.0/0) Output : Infinity
System.out.println (0/0) Output :ArithmeticException
System.out.println (0/0.0) Output :NaN

Modulo division % and mod :

All the rules are exactly same as ‘+’ operator.


And this operator can provide can support for both integral and floating point
arithmetic.

Ex:

1. $ {10%3} Output : 1
2. $ {10%0} Output : ArithmeticException
3. $ {10.0%0} Output : NaN

Note: /  Floating point Arithmetic.


%  Integral & Floating point arithmetic.
El Relational,Logical,conditional operators
Relational Operators
Introduction:

Equality or relational operator in JSP Expression Language is used to check


the values returned by two expressions or operands. Comparisons can also be
done with other values like boolean, string, integer, or floating point literals.

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:

S.No Logic Expression Symbol


Result
1 Equal ${10.0==10} or ${10.0 true == or
eq 10} eq
2 Not Equal ${10.0 != 10} or true != or
${10.0 ne 10} ne
3 Less than ${2<3} or ${4 lt true < or lt
6}
4 Less than or equal ${2 <= 4} or ${2 true >= or
le 4} le
5 Greater ${3.2 > 2} or ${3.2 true > or gt
than gt 2}
6 Greater than or ${3.2 > -2} or ${3.2 true >= or
equal ge 2} ge
Logical Operators

S.No Logic Symbol Expression Result


1 And and or && ${true and false}or ${true flase
&& false}
2 Or or or || ${true or false} or $ {true || True
false}
3 Not not or ! ${not false} or ${! True
false}

Conditional Operator

Ex:

1. ${ (3<4) ? “yes” : “no” } Output: yes


2. ${ (true = = false) ? “Right” : “wrong”} Output: wrong

empty Operator :

$ {empty object}

 if object does not exists


 object is an empty array
 object is an empty string
 object is an empty collection.

In all other cases it returns false

$ {empty abcd} true


$ {empty “abcd”} false
$ {empty null} true

EL Operator Precedence

1. Unary Operator:- !, empty


2. Arithmetic Operators:-
*, /, %, +, -.
3. Relational Operators
4. Logical Operators
5. Conditional Operators

EL Reserved Words

tue, false, null, empty, instanceOf, it, lt, ge, le, ne, eq,and,or,not,mod,div.

EL Vs Number

EL behaves very nicely with null.


 In arithmetic operators it is treated as zero.
 In string evaluation it is treated as empty string.
 In Boolean operators it is treated as false.

Expression Language Functions with examples


EL Functions
Introduction:

1. The main objective of Expression Language (EL) is to separate java code


from the Jsp.
2. If we have any business functionality we can separate it into a java class and
we can invoke that functionality through Expression Language (EL) syntax.
3. The page designer has to know only function name and tld file uri to get its
functionality. Hence EL is almost treated as alternative to custom tags.

Designing Expression Language (EL) function application contains the


following steps.

1. Writing a java classes with required functionality.


2. Writing tld file to map java class to the Jsp.
3. Write a taglib directive to make business functionality available to Jsp.
4. Write Expression Language (EL) function call.

1. Writing a Java Class:

Any java class can simply acts as a repository for EL functions.


The only requirements of a method that acts as EL function it should be
declared as public & static.
Method can take parameters also.
No restrictions on return type void return types also allow.

2.Writing tld file: (tag library descriptor)

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>

3.Writing tagLib Directive:

This is to make EL functionality available to the Jsp.


<%@ taglib prefix="myString" uri="StringOperations" %>

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.*;

public class TestELServlet extends HttpServlet {


public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {

RequestDispatcher view = request.getRequestDispatcher("result.jsp");


view.forward(request,response);
}
}

result.jsp

<%@ taglib prefix="myString" uri="StringOperations" %>


<html>
<body>
<h1 align="CENTER">Result</h1>
${myString:upper(param.name)}
</body></html>

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

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

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

my method java file is:

public class StrMethods {


public static String upper(String s) {
return s.toUpperCase();
}
}
Jsp Standard Tag Library -JSTL-INTRODUCTION
JSTL-INTRODUCTION
Introduction :
1. Sun people encapsulated the core functionality which is common to many
web applications in the form of JSTL.
2. Programmer can views this predefined Library without writing on his own.
3. The main objective of ExpressionLanguage is removing java code from the
Jsp. But it fails to replace java code which processes some functionality like
setting attribute in a particular scope.
4. We can fill this gap by using JSTL. Hence the main object of JSTL is also
removing the java code from the Jsp.
Vendors develop this implementation. It is api specification.
Entire JSTL Library divided in to 5 sub parts.
1. Core Library
2. Xml Library
3. Formatting tags
4. Sql Library
5. JSTL Functions
JSTL Description:
Core Library:
The core group of tags is the most frequently used JSTL tags. Following is
the syntax to include JSTL Core library in your JSP:
Syntax:

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

It defines server standard actions to perform programming general stuff like


implementing loop and conditional statements. It can also perform Jsp
fundamental task like setting attributes, writing output, redirecting the request
to other pages etc.

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:

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

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:

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

JSTL Functions:

It defines several standard actions which can be used for manipulating


collections & string objects.
Syntax:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/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:

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

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:

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

1. General purpose tags


1. <c:out>
2. <c:set>
3. <c:remove>
4. <c:catch>
2. Conditional tags
1. <c:if>
2. <c:choose>
3. <c:when>
4. <c:otherwise>
3. Iteration Tags
1. <c: forEach>
2. <c: forTokens>
4. URL Related Tags
1. <c:import>
2. <c:uri>
3. <c: redirect>
4. <c:param>

jstl General Purpose Tags: c:out


General Purpose Tags:

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:

1. <c:out value = “hftech”/>


It prints MYJAVAHUB in to the Jsp.

2. <c: out value = “${param.uname}”/>


It prints the value of request parameter uname of the Jsp.

Form2:

3. <c:out value = “${param.uname}” default = “Java Jobs”/>


If the main value is not available or it evaluates to null then default value will
be considered.

Attributes:

<c: out> defines the following 3 attributes.


1. value: It is the mandatory attribute and it is for providing the value.It should
be either literal (or) runtime expression.
2. default: It is optional attribute and it is to provide default value.
Jsp engine considered its value if and only if the value attributes evaluates to
null.
3. Escape xml:
True if the tag should escape special XML characters

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

jstl General Purpose Tags: c:set


<c: set>
2. <c: set>
The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is
helpful because it evaluates an expression and uses the results to set a value
of a JavaBeans or a java.util.Map object.

Attributes :

The attributes of <c: set> are

1. Value : Information to save


2. Target : Name of the variable whose property should be modified
3. Property : Property to modify
4. var : Name of the variable to store information.
5. scope : Scope of variable to store information
Form1: To set an attribute in any scope.

Syntax:

<c:set var = “name of attribute” value = “value of attribute” scope =


“session”/>

Note : var and value attributes are mandatory but scope attribute is optional.
default scope is page.

test.jsp

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="x" value="10" scope="session"></c:set>
<c:set var="y" value="20" scope="session"></c:set>
<c:set var='z' value="50" scope="session"></c:set>
<h3>Addition :<c:out value="${x+y+z}"></c:out></h3>
<h3>subtraction :<c:out value="${z-y-x}"></c:out></h3>
<h3>multiplication :<c:out value="${x*y*z}"></c:out></h3>

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:

<c:set target = “customer” property = “name” value = “pavan”/>

jstl General Purpose Tags: c:remove


<c: remove>
<c: remove>

This tag can be used to remove attributes in the specified scope.


This tag contains the following 2 attributes.

1. var : Name of the attribute.


2. scope: The scope in which attribute present.

Ex: <c:remove var = “x” scope = “session”/>

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:

<%@ page isELIgnored="false" %>


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

<c:set var="x" value="10" scope="session"></c:set>


<c:set var="y" value="20" scope="session"></c:set>
<h3>Product :<c:out value="${x*y}"></c:out></h3>
<c:remove var="x"/>
<<c:remove var="y"/>
<h3>Product :<c:out value="${x*y}" </c:out></h3>

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

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h3>UserName :${param.uname}</h3>
<c:catch var="e">
<% System.out.println(10/Integer.parseInt(request.getParameter("age")));
out.println("Age :"+request.getParameter("age")); %>
</c:catch>
<h3>Exception:<c:out value="${e}"></c:out></h3>

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

jstl Conditional Tags c:if


<c: if>
<c: if>

This tag can be used to implement core java if statement.


There are two forms of <c: if>

Form1: without body

Syntax:

<c:if test= “test-condition” var = “x” scope = “request” />

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.

Form2: With Body

<c:if test = “test-condition” var = “x” scope= “request”>


----- Body
</c: if>

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:

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="age" value="20"></c:set>
<c:if test="${age ge 18}">
<h3><c:out value="WELCOME to MYJAVAHUB"></c:out></h3>
</c:if>

Case 1: http://localhost:8080/Scwcd_jsp/test.jsp
jstl Conditional Tags c:choose,c:when,c:otherwise

<c: choose>, <c: when>, <c: otherwise>


<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:when test= “test-condition”>


Action 1
</c: when>

<c: otherwise>
Action 2
</c: otherwise>

</c: choose>

If test-condition is true action 1 will be executed otherwise Action 2 will be


executed.
Example:

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


<html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:set var="salary" scope="session" value="${param.sal}"/>
<p>Your salary is : <c:out value="${salary}"/></p>
<c:choose>
<c:when test="${salary > 1000}">
Salary is very good.
</c:when>
<c:otherwise>
No comment sir...
</c:otherwise>
</c:choose>
</body>
</html>

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:

1. <c:choose> should compulsory contain at least one <c: when >where as


<c:otherwise> is optional.
2. We have to take <c:otherwise> compulsory as the last case only.
3. Every <c:when> tag implicit contain break statement . Hence there is no
chance of fall throw inside a switch.
4. <c:choose> and <c:otherwise> won’t take any attributes, but <c:when>
contains one mandatory attribute. “test”.

Syntax:

<c: choose>

<c: when test= “test-condition1”>


Action 1
</c: when>

<c: when test =“test-condtion2”>


Action 2
</c: when>

<c: when test= “test-condition3”>


Action 3
</c: when>
<c: otherwise>
Default Action
</c: otherwise>

</c: choose>

Example:

Switch.jsp

<%@ page isELIgnored="false" %>


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

<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

jstl - Iteration Tags c:forEach


JSTL- <c:forEach>
<c:forEach>

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:

<c:forEatch begin = “value” end = “vlaue” step = “value”>


// body
</c:forEatch>
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

To implement general for loop

1.<c:forEach>

JSTL For loop Java For loop


<c:forEach begin="1" end="10" step="4"> for (int i = 0;i>=4 ; i++)
This is JSTL forEach loop<br> {
</c:forEach> out.println("this is java
for loop");
}

Examples:

test.jsp:

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach begin="1" end="10" step="4">
This is JSTL forEach loop<br>
</c:forEach>

Output: http://localhost:8080/Scwcd_jsp/test.jsp

Form 2: <c:forEach> with var attribute

<c:forEach> internally maintains a counter variable which can be accessed by


using var attribute. This variable is a Local variable from outside of loop we
can’t access.

Ex: write a Jsp to print the set of even numbers up to 20 by using


<c:forEach>

<%@ page isELIgnored="false" %>


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

<c:forEach begin="1" end="10" step="4" var="x">


Begin Index value :${x}<br>
</c:forEach>

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

<c:forEach> for integrating through Arrays and collections.

Example 1: test.jsp

<%@ page isELIgnored="false" %>


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

<c:forEach items="chamu,mohan,nisheedha,malli" var="x">


Begin Index value : : : ${x}<br>
</c:forEach>

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

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String[ ] s= {"chamu", "malli", "chari", "ramu"};
String[ ] S= {"chamu", "malli", "chari", "ramu"};
pageContext.setAttribute("S",s);
%>
<c:forEach items="${S}" var="x">
Begin Index value : : : ${x}<br>
</c:forEach>

Output: http://localhost:8080/Scwcd_jsp/jstl_exp1.jsp

Example 3: test.jsp

Write a program to display all request Headers by using <c:forEach>

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table>
<c:forEach items="${header}" var="head">
<tr><td>${head.key}</td><td> ------ </td><td>${head.value}</td>
</c:forEach>
</table>

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:

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<table border= 2><tr><td>count</td><td>isFirst</td><td>isLast</td><td>c
urrent key</td><td>current value</td></tr>
<c:forEach items="${header}" varStatus="status" >
<tr><td>${status.count}</td><td>${status.first}</td><td>${status.last}</td
><td>${status.current.key}</td>
<td>${status.current.value}</td></tr>
</c:forEach>
</table>

Output: http://localhost:8080/Scwcd_jsp/test.jsp

jstl Iteration Tags c:forTokens


<c:forTokens>
<c:forTokens>

The <c:forTokens> tag has similar attributes as <c:forEach> except one


additional attribute delims which specifies characters to use as delimiters.
It behaves exactly same as StringTokennizer class.

Note: The StringTokennizer class is use to split a String object into different
tokens by certain delimiter. (space is the default delimiter)

Syntax:

<c:forTokens items=" List of string objects " delims=" separator "


var="name">
// body
</c:forTokens>

Example: http://localhost:8080/Scwcd_jsp/test.jsp

test.jsp

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forTokens items="chamu,mohan,ramu" delims="," var="name">
<c:out value="${name}"/><p>
</c:forTokens>

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.

NOTE: In the case of <c:forEach> items attribute can be a map (or)


collection (or) Array or list of String objects with’ ,’ separator.
But in the case of <c:forTokens> items attribute should be list of string
objects with some separator.

jstl URL Related Tags : c:import


<c:import>
<c:import>

This is used for importing the response of other pages into current page at
request processing time (dynamic include).
Form 1:

<c:import url= ”second.jsp” />

Example:

first.jsp

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h3>This is first JSP</h3>
<c:import url="/second.jsp"></c:import>

second .jsp:

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1> WELCOME TO HFTECH </h1>
Form 2 :

We can import the resources from outside of current application also i.e
(cross context communication is also possible).

Syntax:

<c:import url="/second.jsp" context="/webapp2" />

NOTE: By default cross context communication is not allowed in most of


web servers to meet security constrains. To enable cross context
communication, server level configuration changes are required.

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:

<c:import url = 'second.jsp' var = 'second' scope =


'request'></c:import>

Example:

first.jsp

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h3>This is first JSP</h3>
<c:import url = '/second.jsp' var = 'second' scope = 'request'></c:import>
<h2>1.${second}</h2>
<h2>2.${second}</h2>
<h2>3.${second}</h2>

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

<%@ page isELIgnored="false" %>


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

<h2>This is First JSP</h2>


<c:import url="/second.jsp">
<c:param name='c1' value="jsp"/>
<c:param name='c2' value="servlet" />
</c:import>

second.jsp

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h1> WELCOME TO HFTECH </h1>
<h2>First Parameter : : :${param.c1}</h2>
<h2>Second Parameter : : :${param.c2}</h2>
jstl URL Related Tags : c:redirect
2. <c:redirect>
<c:redirect>

This action can be used to redirect the request to another page.


The <c:redirect> tag redirects the browser to an alternate URL by providing
automatically URL rewriting, it supports context-relative URLs, and it
supports the <c:param> tag.
This is exactly similar to sendRedirect() of ServletResponse.

FORM1:
<c:redirect url= ”second.jsp” />

FORM2: We can redirect the request to some other web application resource
also.

Syntax :

<c:redirect url=”/second.jsp” context=”/webapp2” />

FORM3:While performing redirection we can pass parameters also to the


target resource.

first.jsp

<%@ page isELIgnored="false" %>


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

<h2>This is First JSP</h2>


<c:redirect url="/second.jsp">
<c:param name='c1' value="jsp"/>
<c:param name='c2' value="servlet" />
</c:redirect>

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

<h2> This is second JSP </h2>

<h2>First Parameter : : :${param.c1}</h2>


<h2>Second Parameter : : :${param.c2}</h2>

Output:

jstl URL Related Tags : c:url


3.<c:url>
<c:url>

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:

<c:url value=”second.jsp” var=”x” scope=”session” />

Example:

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/second.jsp" var="x" />
<h1>the modified url : ${x},</h1><br>
<a href="${x}">click Here </a>

FORM 2 :

Corss context communication.

Syntax:

<c:url value=”second.jsp” context= ”/webpage2” var=”x”


scope=”request”/>

FORM 3:

While formatting the URL we can pass parameters also to the target
resource.

Syntax:

<c:url value="/second.jsp" var="x" >


<c:param name="d1" value="SCJP"/>
<c:param name ="d2" value="SCWCD"/>
</c:url>
Example:

first.jsp

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/second.jsp" var="x" >
<c:param name="d1" value="SCJP"/>
<c:param name ="d2" value="SCWCD"/>
</c:url>
<h1>the modified url : ${x},</h1><br>
<a href="${x}">click Here </a>

second.jsp

<%@ page isELIgnored="false" %>


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<h2> This is second JSP </h2>
<h2>First Parameter : : :${param.d1}</h2>
<h2>Second Parameter : : :${param.d2}</h2>

Output:

Click on “click here” hiperlink .


Custom Tags:
Custom tags are user-defined tags. They eliminates the possibility of
scriptlet tag and separates the business logic from the JSP page.
The same business logic can be used many times by the use of costom
tag.

Advantages of Custom Tags

The key advantages of Custom tags are as follows:


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

Syntax to use custom tag


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

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


<prefix:tagname attr1=value1....attrn=valuen >
body code
</prefix:tagname>
JSP Custom Tag API
The javax.servlet.jsp.tagext package contains classes and interfaces for
JSP custom tag API. The JspTag is the root interface in the Custom
Tag hierarchy.

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.

Example of JSP Custom Tag


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

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

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

1) Create the Tag handler class

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

The PageContext class provides getOut() method that returns the


instance of JspWriter class. TagSupport class provides instance of
pageContext bydefault.
File: MyTagHandler.java

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

2) Create the TLD file

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

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


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

3) Create the JSP file

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

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

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

Attributes in JSP Custom Tag

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

 Define the property in the TagHandler class with the attribute


name and define the setter method
 define the attribute element inside the tag element in the TLD
file

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

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

Here m is the prefix, cube is the tag name and number is the attribute.
Simple example of attribute in JSP Custom Tag

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

 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

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


2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>http://tomcat.apache.org/example-taglib</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>cube</name>
15. <tag-class>com.javatpoint.taghandler.CubeNumber</tag-class>
16. <attribute>
17. <name>number</name>
18. <required>true</required>
19. </attribute>
20. </tag>
21. </taglib>

Output
1. Cube of 4 is: 64

JSP Custom Tag attribute example with database

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

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

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

m.tld

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


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

index.jsp

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


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

Iteration using JSP Custom Tag

We can iterate the body content of any tag using


thedoAfterBody() 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_AGAINconstant in the doAfterBody() method.

Example of Iteration using JSP Custom Tag

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

 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

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


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

Looping using Iteration Tag (creating tag for loop)

Let's create a loop tag that iterates the body content of this tag.
File: index.jsp

1. <!DOCTYPE html PUBLIC "-


//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"
>
2. <html>
3. <head>
4. <title>Insert title here</title>
5. </head>
6. <body>
7.
8. <%@taglib prefix="m" uri="sssuri" %>
9. <m:loop end="5" start="1">
10. <p>My Name is khan</p>
11. </m:loop>
12.
13. </body>
14. </html>

File: mytags.tld

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


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

1. package com.javatpoint.customtag;
2. import javax.servlet.jsp.JspException;
3. import javax.servlet.jsp.tagext.TagSupport;
4.
5. public class Loop extends TagSupport{
6. private int start=0;
7. private int end=0;
8.
9. public void setStart(int start) {
10. this.start = start;
11. }
12. public void setEnd(int end) {
13. this.end = end;
14. }
15.
16. @Override
17. public int doStartTag() throws JspException {
18. return EVAL_BODY_INCLUDE;
19. }
20.
21. @Override
22. public int doAfterBody() throws JspException {
23. if(start<end){
24. start++;
25. return EVAL_BODY_AGAIN;
26. }else{
27. return SKIP_BODY;
28. }
29.
30. }
31.
32.
33. }

File: web.xml

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


2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.co
m/xml/ns/javaee/web-
app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.su
n.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

Custom URI in JSP Custom Tag

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

Example to use custom URI in JSP Custom Tag

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

 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

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


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

mytags.tld

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


2. <!DOCTYPE taglib
3. PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
4. "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
5.
6. <taglib>
7. <tlib-version>1.0</tlib-version>
8. <jsp-version>1.2</jsp-version>
9. <short-name>simple</short-name>
10. <uri>mytags</uri>
11. <description>A simple tab library for the examples</description>
12.
13. <tag>
14. <name>today</name>
15. <tag-class>com.javatpoint.taghandler.PrintDate</tag-class>
16. </tag>
17. </taglib>
PrintDate.java

1. package com.javatpoint.taghandler;
2.
3. import javax.servlet.jsp.JspException;
4. import javax.servlet.jsp.JspWriter;
5. import javax.servlet.jsp.tagext.TagSupport;
6.
7. public class PrintDate extends TagSupport{
8.
9. public int doStartTag() throws JspException {
10. JspWriter out=pageContext.getOut();
11. try{
12. out.print(java.util.Calendar.getInstance().getTime());
13. }catch(Exception e){e.printStackTrace();}
14.
15. return SKIP_BODY;
16. }
17.
18. }

MVC in JSP
Model 1 and Model 2 (MVC) Architecture

Before developing the web applications, we need to have idea about


design models. There are two types of programming models (design
models)

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.

Problem in Servlet technology Servlet needs to recompile if any


designing code is modified. It doesn't provide separation of concern.
Presentation and Business logic are mixed up.

JSP overcomes almost all the problems of Servlet. It provides better


separation of concern, now presentation and business logic can be
easily separated. You don't need to redeploy the application if JSP
page is modified. JSP provides support to develop web application
using JavaBean, custom tags and JSTL so that we can put the business
logic separate from our JSP that will be easier to test and debug.

As you can see in the above figure, there is picture which show the flow
of the model1 architecture.

1. Browser sends request for the JSP page


2. JSP accesses Java Bean and invokes business logic
3. Java Bean connects to the database and get/save data
4. Response is sent to the browser which is generated by JSP

Advantage of Model 1 Architecture

 Easy and Quick to develop web application


Disadvantage of Model 1 Architecture

 Navigation control is decentralized since every page


contains the logic to determine the next page. If JSP page name
is changed that is referred by other pages, we need to change it in
all the pages that leads to the maintenance problem.
 Time consuming You need to spend more time to develop
custom tags in JSP. So that we don't need to use scriptlet tag.
 Hard to extend It is better for small applications but not for
large applications.

Model 2(MVC) Architecture

MVC stands for Model View and Controller. It is adesign


pattern that separates the business logic, presentation logic and data.

Controller acts as an interface between View and Model. Controller


intercepts all the incoming requests.

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

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

Advantage of MVC (Model 2) Architecture


1. Navigation Control is centralized
2. Easy to maintain the large application
Advantage of Model 2 (MVC) Architecture

 Navigation control is centralized Now only controller


contains the logic to determine the next page.
 Easy to maintain
 Easy to extend
 Easy to test
 Better separation of concerns

Disadvantage of Model 2 (MVC) Architecture

 We need to write the controller code self. If we change the


controller code, we need to recompile the class and redeploy the
application.

Example of following MVC in JSP

In this example, we are using servlet as a controller, jsp as a view


component, Java Bean class as a model.

In this example, we have created 5 pages:

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


 ControllerServlet.java a servlet that acts as a controller.
 login-success.jsp and login-error.jsp files acts as view
components.
 web.xml file for mapping the servlet.
File: index.jsp
1. <form action="ControllerServlet" method="post">
2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
5. </form>

File: ControllerServlet

1. package com.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>

You might also like