0% found this document useful (0 votes)
3 views

Unit-11 Web Development Using JSP (E-next.in)

Java Server Pages (JSP) is a technology for creating dynamic web pages using HTML and Java code. The JSP life cycle includes phases such as translation, compilation, loading, instantiation, initialization, request processing, and destruction. JSP offers advantages like ease of use and integration with Java, but also has disadvantages such as difficulty in error tracing and increased disk space requirements.

Uploaded by

kcsfbca2022to25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-11 Web Development Using JSP (E-next.in)

Java Server Pages (JSP) is a technology for creating dynamic web pages using HTML and Java code. The JSP life cycle includes phases such as translation, compilation, loading, instantiation, initialization, request processing, and destruction. JSP offers advantages like ease of use and integration with Java, but also has disadvantages such as difficulty in error tracing and increased disk space requirements.

Uploaded by

kcsfbca2022to25
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Unit-11 Web development using JSP

Q.1 What is JSP? Explain JSP Life Cycle with suitable example.
Java Server Pages (JSP):
 Java Server Pages (JSP) is a technology that helps software developers create
dynamically generated web pages based on HTML, XML, or other document types.
 It is a technology which helps developers insert java code in HTML pages by making
use of special JSP tags, most of which start with.
 It can be thought of as an extension to servlet because it provides more functionality
than servlet such as expression language, jstl etc.
 A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain
than servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tag etc.
 JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages and sharing information between requests, pages etc.
 To deploy and run Java Server Pages, a compatible web server with a servlet
container, such as Apache Tomcat or Jetty, is required.

JSP Life cycle phases:


 A JSP life cycle is defined as the process from its creation till the destruction.
 This is similar to a servlet life cycle with an additional step which is required to
compile a JSP into servlet.

JSP Life cycle phases

 SP pages are saved with .jsp extension which lets the server know that this is a JSP
page and needs to go through JSP life cycle stages.
 When client makes a request to Server, it first goes to container. Then container
checks whether the servlet class is older than jsp page( To ensure that the JSP file got
modified).
 If this is the case then container does the translation again (converts JSP to Servlet)
otherwise it skips the translation phase (i.e. if JSP webpage is not modified then it
doesn’t do the translation to improve the performance as this phase takes time and
to repeat this step every time is not time feasible)

Khan S. Alam 1 https://E-next.in


Unit-11 Web development using JSP

The steps in the life cycle of jsp page are:


1) Translation:
 As stated above whenever container receives request from client, it does translation
only when servlet class is older than JSP page otherwsie it skips this phase (reason
explained above).

2) Compilation:
 Servlet page is compiled by the compiler and gets converted into the class file.

3) Loading:
 Loads the corresponding servlet class.

4) Instantiation:
 Instantiates the servlet class.

5) Initialization:
 When a container loads a JSP it invokes the jspInit() method before servicing any
requests.
 If you need to perform JSP-specific initialization, override the jspInit() Typically
initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.

6) RequestProcessing:
 This phase of the JSP life cycle represents all interactions with requests until the JSP
is destroyed.
 A new thread is then gets created, which invokes the_jspService() method.
 Whenever a browser requests a JSP and the page has been loaded and initialized,
the JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its


parameters as follows:
void _jspService(HttpServletRequest request, HttpServletResponse response)
{ // Service handling code... }

The _jspService() method of a JSP is invoked once per a request and is responsible for
generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.

7) Destruction:
 Invokes the jspDestroy() method to destroy the instance of the servlet class.

Khan S. Alam 2 https://E-next.in


Unit-11 Web development using JSP

Advantages of JSP:
1. HTML friendly simple and easy language and tags.
2. Supports Java Code.
3. Supports standard Web site development tools.
4. The JSP serves all facilities of Java i.e. write once run anywhere.
5. JSP is ideal for Web based Technology.
6. The JSP pages are translated and compiled into JAVA Servlet but are easier to
develop than JAVA Servlet.
7. JSP containers provide easy coding for accessing standard objects and actions.
8. JSP acquire all the benefits provided by JAVA Servlets and web container
environment.
9. The JSP use HTTP as default request /response communication model.

Disadvantages of JSP:
1. As JSP pages are translated to servlets and compiled, it is difficult to trace errors
occurred in JSP pages.
2. JSP pages require double the disk space to hold the JSP page.
3. JSP pages require more time when accessed for the first time as they are to be
compiled on the server.
4. Difficult looping in JSP.

HTML Code:
<form method=post action=”display.jsp”>
<pre>

Enter your Name: <input type=text name=t1>


Enter DOB: <input type=text name=t2>
Enter DOJ: <input type=text name=t3>
Select your Gender: <input type=radio name=r1 value=”Male”> Male
<input type=radio name=r1 value=”Female”> Female
<input type=submit value=”Click here”>

</pre>
</form>

JSP Code:
<%
String a,b,c,d;

A=request.getParameter(“t1”);
B= request.getParameter(“t2”);
C= request.getParameter(“t3”);
D= request.getParameter(“r1”);

Out.println(“Name is:”+a +” \n DOB is:”+ b+ “\n DOJ is:”+ c+”


\n Your Gender is:”+ d);
%>

Khan S. Alam 3 https://E-next.in


Unit-11 Web development using JSP

Q.2 Explain JSP Architecture with neat diagram.


JSP Architecture:
 The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages.
 A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that
are part of JSPs.
 Following diagram shows the position of JSP container and JSP files in a Web
application.

JSP Processing:
The following steps explain how the web server creates the Webpage using JSP:
1) As with a normal page, your browser sends an HTTP request to the web server.
2) The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
3) The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements
the corresponding dynamic behavior of the page.
4) The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
5) A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format. The
output is furthur passed on to the web server by the servlet engine inside an HTTP
response.
6) The web server forwards the HTTP response to your browser in terms of static HTML
content.
7) Finally, the web browser handles the dynamically-generated HTML page inside the
HTTP response exactly as if it were a static page.

Khan S. Alam 4 https://E-next.in


Unit-11 Web development using JSP

All the above mentioned steps can be seen in the following diagram:

 Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet.
 If the JSP is older than its generated servlet, the JSP container assumes that the JSP
hasn't changed and that the generated servlet still matches the JSP's contents.
 This makes the process more efficient than with the other scripting languages (such
as PHP) and therefore faster.
 So in a way, a JSP page is really just another way to write a servlet without having to
be a Java programming wiz.
 Except for the translation phase, a JSP page is handled exactly like a regular servlet.

Khan S. Alam 5 https://E-next.in


Unit-11 Web development using JSP

Q.3 Explain JSP Implicit objects.


JSP Implicit objects:
 JSP container makes available implicit objects to be used within scriptlets and
expressions, without the programmer first having to first create them.
 These objects act as wrappers around underlying java classes and interfaces defined
in servlet API.

A list of the 9 implicit objects is given below:


Object Type

Request HttpServletRequest
Response HttpServletResponse
Out JspWriter
Session HttpSession
application ServletContext
Config ServletConfig
pageContext PageContext
page Object
exception Throwable

Explanation of Implicit objects are given below:


1) request
 The request object provides access to all information associated with a request
including its source,the requested Url and any headers,cookies or parameters
associated with the request
 The request object has request scope.
 The request object is in scope unless the response to the client is complete.
 Instance of HttpServletRequest

2) response
 Setting headers, cookies for the client and sending response to the client.
 Response object has page scope.
 It encapsulates the response generated by JSP.
 Instance of HttpServletResponse

3) out
 This is the PrintWriter object used to send output to the client.
 The initial JspWriter object is instantiated differently depending on whether the page
is buffered or not.
 The JspWriter object contains most of the same methods as the java.io.PrintWriter
class
 Instance of a javax.servlet.jsp.JspWriter

Khan S. Alam 6 https://E-next.in


Unit-11 Web development using JSP

4) session
 HTTP is a stateless protocol
 In web applications, a client’s interaction with the application will span many
requests and responses.
 To join all of them into one conversation between client and server, sessions are
used.
 Sessions are used to maintain the state and user identity across multiple page
requests.
 The session object has session scope.
 Provides access to session data and information about the session.
 Instance of HTTP Session.

5) application
 Represents the application to which JSP belongs.
 The object holds references to other objects that more than one user may require
access to i.e database connection pool shared by all users.
 Application object has application scope.
 Instance of ServletContext.

6) config
 Contains initialisation parameters, defined in deployment descriptor and the
ServletContext object.
 The config object has page scope.
 Used to pass information to a servlet or JSP page during initialization.
 Instance of ServletConfig.

7) page context
 Implements methods for transferring control from the current page to another page
either temporarily or permanently.
 PageContext object has page scope.
 Provides methods for accessing all other objects and attributes for holding data that
is shared between multiple components in the same page. Rarely used
 Instance of javax.servlet.jsp.PageContext.

8) page
 Page object represents the JSP page itself.
 Synonym for this.
 Page object has page scope.
 Rarely used.
 Instance of java.lang.Object.

9) exception
 Refers to runtime Exception that results in an error page being invoked.
 The exception object is available only in an error page.
 Exception object has a page scope.
 Instance of java.lang.Throwable.

Khan S. Alam 7 https://E-next.in


Unit-11 Web development using JSP

Q.4 What are actions in JSP? Explain any four actions in JSP with a program.
Action elements:
 There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks.
 The action tags are used to control the flow between pages and to use Java Bean.

The Jsp action tags are given below:


JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include mostly.
can be used to print the message if plugin is working. It is used in
jsp:fallback
jsp:plugin.

The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development.
So we will see these tags in bean developement.

1) jsp:forward action tag:


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

Syntax of jsp:forward action tag without parameter:


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

Syntax of jsp:forward action tag with parameter:


<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:forward>

Example of jsp:forward action tag without parameter:


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

index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" />
</body>
</html>

Khan S. Alam 8 https://E-next.in


Unit-11 Web development using JSP

printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

Example of jsp:forward action tag with parameter:


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

index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value="ABC" />
</jsp:forward>
</body>
</html>

printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>

2) jsp:include action tag:


 The jsp:include action tag is used to include the content of another resource it may
be jsp, html or servlet.The jsp include action tag includes the resource at request
time so it is better for dynamic pages because there might be changes in future.
 The jsp:include tag can be used to include static as well as dynamic pages.

Advantage of jsp:include action tag:


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

Difference between jsp include directive and include action:


JSP include directive JSP include action
includes resource at translation time. includes resource at request time.
better for static pages. better for dynamic pages.
includes the original content in the generated servlet. calls the include method.

Khan S. Alam 9 https://E-next.in


Unit-11 Web development using JSP

Syntax of jsp:include action tag without parameter:


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

Syntax of jsp:include action tag with parameter:


<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>" />
</jsp:include>

Example of jsp:include action tag without parameter:


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

File: index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>

File: printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>

3) jsp:useBean action tag:


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

package mypack;
public class Employee implements java.io.Serializable
{
private int id;
private String name;
public Employee(){}

public void setId(int id)


{
this.id=id;
}

Khan S. Alam 10 https://E-next.in


Unit-11 Web development using JSP

public int getId()


{
return id;
}

public void setName(String name)


{
this.name=name;
}

public String getName()


{
return name;
}
}

How to access the java bean class?


To access the java bean class, we should use getter and setter methods.

package mypack;
public class Test
{
public static void main(String args[])
{
Employee e=new Employee(); //object is created
e.setName("Subodh"); //setting value to the object
System.out.println(e.getName());
}
}
Note: There are two ways to provide values to the object, one way is by constructor and
second is by setter method.

jsp:useBean action tag:


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

Syntax of jsp:useBean action tag:


<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>

Attributes and Usage of jsp:useBean action tag:


 id: is used to identify the bean in the specified scope.
 scope: represents the scope of the bean. It may be page, request, session or
application. The default scope is page.

Khan S. Alam 11 https://E-next.in


Unit-11 Web development using JSP

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

Simple example of jsp:useBean action tag:


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

Calculator.java (a simple Bean class)


public class Calculator
{
public int cube(int n)
{
return n*n*n;
}
}

index.jsp file
<jsp:useBean id="obj" class="ABC"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>

Output:

Khan S. Alam 12 https://E-next.in


Unit-11 Web development using JSP

4) jsp:setProperty and jsp:getProperty action tags:


 The setProperty and getProperty action tags are used for developing web application
with Java Bean. In web devlopment, bean class is mostly used because it is a
reusable software component that represents data.
 The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.

Syntax of jsp:setProperty action tag:


<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>

Example of jsp:setProperty action tag if you have to set all the values of incoming request
in the bean:
<jsp:setProperty name="bean" property="*" />

Example of jsp:setProperty action tag if you have to set value of the incoming specific
property:
<jsp:setProperty name="bean" property="username" />

Example of jsp:setProperty action tag if you have to set a specific value in the property:
<jsp:setProperty name="bean" property="username" value="ABC" />

5) jsp:getProperty action tag:


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

Syntax of jsp:getProperty action tag:


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

Simple example of jsp:getProperty action tag:


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

Displaying applet in JSP (jsp:plugin action tag):


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

Syntax of jsp:plugin action tag:


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

Khan S. Alam 13 https://E-next.in


Unit-11 Web development using JSP

Q.5 What is directives? Explain different types of directives in JSP?


JSP directive elements:
 The jsp directives are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
 It is a one of the kind of building block of JSP program which gives specific meaning
or instruction to the JSP engine during translation phase of JSP program into servlet
class.

There are three types of directives:


1) page directive
2) include directive
3) taglib directive

JSP page directive:


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

Syntax of JSP page directive:


<%@ page attribute="value" %>

Attributes of JSP page directive:


1) import
2) contentType
3) extends
4) info
5) buffer
6) language
7) isELIgnored
8) isThreadSafe
9) autoFlush
10) session
11) pageEncoding
12) errorPage
13) isErrorPage

1) import:
 The import attribute is used to import class,interface or all the members of a
package.
 It is similar to import keyword in java class or interface.

Example of import attribute:


<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>

Khan S. Alam 14 https://E-next.in


Unit-11 Web development using JSP

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

Example of contentType attribute:


<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>

3) extends:
 The extends attribute defines the parent class that will be inherited by the generated
servlet. It is rarely used.

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

Example of info attribute:


<html>
<body>
<%@ page info="composed by ABC" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

The web container will create a method getServletInfo() in the resulting servlet.
For example:
public String getServletInfo()
{
return "composed by ABC";
}

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

Example of buffer attribute:


<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>

Khan S. Alam 15 https://E-next.in


Unit-11 Web development using JSP

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

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

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

If you make the value of isThreadSafe attribute like:


<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:
public class SimplePage_jsp extends HttpJspBase
implements SingleThreadModel
{
.......
}

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

Example of errorPage attribute:


//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>

10) isErrorPage:
 The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.

Khan S. Alam 16 https://E-next.in


Unit-11 Web development using JSP

Example of isErrorPage attribute:


//myerrorpage.jsp
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!
<br/>
The exception is: <%= exception %>
</body>
</html>

JSP Include directive:


 The include directive is used to include the contents of any resource it may be jsp
file, html file or text file.
 The include directive includes the original content of the included resource at page
translation time (the jsp page is translated only once so it will be better to include
static resource).
 Include directives are used for include the external file into the jsp file statically.
 Include directives are executed at the time of translation phase only, hence its
included file output show only static content. We cannot modify external file content
at runtime.

Advantage of Include directive:


 Code Reusability

Syntax of include directive:


<%@ include file="resourceName" %>

Example of include directive:


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

<html> <body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body> </html>
Note: The include directive includes the original content, so the actual page size grows at
runtime.

JSP Taglib directive:


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

Syntax JSP Taglib directive:


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

Khan S. Alam 17 https://E-next.in


Unit-11 Web development using JSP

Example of JSP Taglib directive:


In this example, we are using our tag named currentDate. To use this tag we must specify
the taglib directive so the container may get information about the tag.

<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>

Khan S. Alam 18 https://E-next.in


Unit-11 Web development using JSP

Q.6 Explain Custom tags in JSP.


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

Advantages of Custom Tags:


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

Syntax to use custom tag:


There are two ways to use the custom tag. They are given below:
<prefix:tagname attr1=value1....attrn=valuen />
or
<prefix:tagname attr1=value1....attrn=valuen >
body code
</prefix:tagname>

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:
1) Define the property in the TagHandler class with the attribute name and define the
setter method.
2) define the attribute element inside the tag element in the TLD file.

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


<m:cube number="4"></m:cube>
Here m is the prefix, cube is the tag name and number is the attribute.

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

Khan S. Alam 19 https://E-next.in


Unit-11 Web development using JSP

Understanding flow of custom tag in jsp

1) Create the Tag handler class:


 To create the Tag Handler, we are inheriting the TagSupport class and overriding its
method doStartTag().
 To write data for the jsp, we need to use the JspWriter class.
 The PageContext class provides getOut() method that returns the instance of
JspWriter class.
 TagSupport class provides instance of pageContext bydefault.

File: MyTagHandler.java
package com.javatpoint.sonoo;

import java.util.Calendar;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class MyTagHandler extends TagSupport


{
public int doStartTag() throws JspException
{
JspWriter out=pageContext.getOut();
try
{
out.print(Calendar.getInstance().getTime());
}
catch(Exception e){System.out.println(e);}
return SKIP_BODY;
}
}

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.

Khan S. Alam 20 https://E-next.in


Unit-11 Web development using JSP

File: mytags.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">

<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>simple</short-name>
<uri>http://tomcat.apache.org/example-taglib</uri>
<tag>
<name>today</name>
<tag-class>com.javatpoint.sonoo.MyTagHandler</tag-class>
</tag>
</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.
 It uses taglib directive to use the tags defined in the tld file.

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

Output:

Khan S. Alam 21 https://E-next.in


Unit-11 Web development using JSP

Q.7 Write a short note on JSP scripting language.


JSP elements:
 If you want to put any java code in that file then you can put it by the use of jsp tags
(elements).

There are mainly three groups of jsp tags(elements) available in java server page:
1. JSP scripting elements:
a) JSP scriptlet tag
b) JSP expression tag
c) JSP declaration tag
d) Comment tag
2. JSP directive elements:
a) page directive
b) include directive
c) taglib directive
3. JSP standard action elements:

JSP scripting elements:


 The scripting elements provides the ability to insert java code inside the jsp.
 JSP Scripting element are written inside <% %> tags. These code inside <% %> tags
are processed by the JSP engine during translation of the JSP page.
 Any other text in the JSP page is considered as HTML code or plain text.

There are four types of scripting elements:


1) scriptlet tag
2) expression tag
3) declaration tag
4) Comment tag

1) scriptlet tag:
 A scriptlet is a valid code in java and is placed in the jspService() method of the JSP
engine at the time of running.

The scriplet syntax is:


<% java code %>

There are variables available exclusively for the scriplets. They are request, response,
out,session and pageContext, application, config and exception.

Simple Example of JSP scriptlet tag:


In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

Khan S. Alam 22 https://E-next.in


Unit-11 Web development using JSP

Example of JSP scriptlet tag that prints the user name:


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

index.html:
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

welcome.jsp:
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>

2) JSP expression tag:


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

Syntax of JSP expression tag:


<%= statement %>

Example of JSP expression tag:


In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

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

Khan S. Alam 23 https://E-next.in


Unit-11 Web development using JSP

Example of JSP expression tag that prints current time:


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

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

Example of JSP expression tag that prints the user name


 In this example, we are printing the username using the expression tag.
 The index.html file gets the username and sends the request to the welcome.jsp file,
which displays the username.

index.html:
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>

welcome.jsp:
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</form>
</body>
</html>

JSP Declaration Tag:


 The JSP declaration tag is used to declare fields and methods.
 The code written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet. So it doesn't get memory at each request.

Syntax of JSP declaration tag:


The syntax of the declaration tag is as follows:
<%! field or method declaration %>

Khan S. Alam 24 https://E-next.in


Unit-11 Web development using JSP

Difference between the jsp scriptlet tag and jsp declaration tag ?
Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare The jsp declaration tag can declare variables
variables not methods. as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.

Example of JSP declaration tag that declares field:


 In this example of JSP declaration tag, we are declaring the field and printing the
value of the declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

Example of JSP declaration tag that declares method:


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

index.jsp
<html>
<body>
<%!
int cube(int n)
{
return n*n*n*;
}
%>

<%= "Cube of 3 is:"+cube(3) %>


</body>
</html>

4) JSP Comment:
 There is only one type of JSP comment available by JSP specification.

JSP Comment Syntax:


<%-- comment --%>

Khan S. Alam 25 https://E-next.in


Unit-11 Web development using JSP

 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’.
 Example:
<%-- This JSP comment part will not be included in the response object --%>

There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially.
Here's a summary:

Syntax Purpose
<%-- comment --%> A JSP comment. Ignored by the JSP engine.
<!-- comment --> An HTML comment. Ignored by the browser.
<\% Represents static <% literal.
%\> Represents static %> literal.
\' A single quote in an attribute that uses single quotes.
\" A double quote in an attribute that uses double quotes.

Khan S. Alam 26 https://E-next.in


Unit-11 Web development using JSP

Q. 8 Write a short note on Error handling in JSP.


Exception Handling in JSP:
 Exception Handling is a process of handling exceptional condition that might occur in
your application.
 Exception Handling in JSP is much easier than Java Technology exception handling.
Although JSP Technology also uses the same exception class objects.
 The exception is normally an object that is thrown at runtime.
 Exception Handling is the process to handle the runtime errors. There may occur
exception any time in your web application. So handling exceptions is a safer side for
the web developer.

Ways to perform Exception Handling in JSP:


JSP provide 3 different ways to perform exception handling:
1) Using isErrorPage and errorPage attribute of page directive.
2) Using <error-page> tag in Deployment Descriptor.
3) Using simple try...catch block.

Example of isErrorPage and errorPage attribute:


 isErrorPage attribute in page directive officially appoints a JSP page as an error page.
error.jsp

errorPage attribute in a page directive informs the Web Container that if an exception
occurs in the current page, forward the request to the specified error page.

Khan S. Alam 27 https://E-next.in


Unit-11 Web development using JSP

sum.jsp

Whenever an exception occurs in sum.jsp page the user is redirected to the error.jsp page,
where either you can display a nice message, or you can also print the exception trace into a
file/database in the background, to check later what caused the error.

Using the try...catch block:


Using try...catch block is just like how it is used in Core Java.
<html>
<head>
<title>Try...Catch Example</title>
</head>
<body>
<%
try{
int i = 100;
i = i / 0;
out.println("The answer is " + i);
}
catch (Exception e){
out.println("An exception occurred: " + e.getMessage());
}
%>
</body>
</html>

Example of exception handling in jsp by the elements of page directive:


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

Khan S. Alam 28 https://E-next.in


Unit-11 Web development using JSP

There are 3 files:


1) index.jsp for input values
2) process.jsp for dividing the two numbers and displaying the result
3) error.jsp for handling the exception

index.jsp:
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/>
</form>

process.jsp:
<%@ page errorPage="error.jsp" %>
<%

String num1=request.getParameter("n1");
String num2=request.getParameter("n2");

int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);

%>

error.jsp:
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>

Output of this example:

Khan S. Alam 29 https://E-next.in


Unit-11 Web development using JSP

Khan S. Alam 30 https://E-next.in


Unit-11 Web development using JSP

Q.9 Explain JSTL tags in details.


JSTL:
 JSP Standard Tag Library(JSTL) is a standard library of readymade tags.
 The JSTL contains several tags that can remove scriplet code from a JSP page by
providing some ready to use, already implemented common functionalities.

Classification of The JSTL Tags:


The JSTL tags can be classified, according to their functions, into the following JSTL tag
library groups that can be used when creating a JSP page:
1) Core Tags
2) Formatting tags
3) SQL tags
4) XML tags
5) JSTL Functions

JSTL is divided into 5 groups:


1. JSTL Core: JSTL Core provides several core tags such as if, forEach, import, out etc to
support some basic scripting task. Url to include JSTL Core Tag inside JSP page is →
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

2. JSTL Formatting: JSTL Formatting library provides tags to format text, date, number for
Internationalised web sites. Url to include JSTL Formatting Tags inside JSP page is →
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

3. JSTL sql: JSTL SQL library provides support for Relational Database Connection and tags
to perform operations like insert, delete, update, select etc on SQL databases. Url to
include JSTL SQL Tag inside JSP page is →
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

4. JSTL XML: JSTL XML library provides support for XML processing. It provides flow
control, transformation features etc. Url to include JSTL XML Tag inside JSP page is →
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

5. JSTL functions: JSTL functions library provides support for string manipulation. Url to
include JSTL Function Tag inside JSP page is →
<%@ taglib prefix="fn" uri= "http://java.sun.com/jsp/jstl/functions" %>

Khan S. Alam 31 https://E-next.in

You might also like