0% found this document useful (0 votes)
2 views23 pages

Module 4 (Chapter 1)

This document provides an introduction to Servlets and JSP, explaining their functionalities, advantages, and lifecycle. It details the steps to create a Servlet, the Servlet API, and the differences between Servlets and JSP, highlighting how JSP simplifies web application development. Additionally, it covers the processing of HTTP requests and responses, along with the structure and processing of JSP pages.

Uploaded by

cmuthukr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views23 pages

Module 4 (Chapter 1)

This document provides an introduction to Servlets and JSP, explaining their functionalities, advantages, and lifecycle. It details the steps to create a Servlet, the Servlet API, and the differences between Servlets and JSP, highlighting how JSP simplifies web application development. Additionally, it covers the processing of HTTP requests and responses, along with the structure and processing of JSP pages.

Uploaded by

cmuthukr
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-4: "Introduction to Servlet & JSP"

Module-4
Chapter 1
Introduction to Servlets
✓ A Java servlet is a Java Program which is executed on server system, When requested
by the html document being displayed by the browser.
✓ Servlet request and response should be done with HTTP Protocols

✓ Applets extend the functionality of a web browser


✓ Servlets extend the functionality of a web server
✓ In earlierdays,web server could dynamically construct a web page by creating a
separate process to handle each request
✓ Web server was communicating using common gateway interface

Disadvantage of Common Gate Way Interface


➢ Processor and memory resources was very expensive
➢ Cgi programs was not platform independent
➢ Open and closing database connections was very expensive

Advantages of Servlets
✓ Performance is better
✓ Servlets execute with an address space inside a server so no necessary of creating
process
✓ Servlets are platform independent
✓ Java security manager enforces a set of restrictions to protect resources
✓ It can communicate with applets, databases and other software's via the socket ,RMI
mechanisms

4.1 Life Cycle of Servlets


The following are the paths followed by a servlet.
✓ The servlet is initialized by calling the init() method.
✓ The servlet calls service () method to process a client's request.
✓ The servlet is terminated by calling the destroy() method.

Dept of CSE,GST,Bengaluru Page 1


Unit-4: "Introduction to Servlet & JSP"

➢ Let us consider a typical scenario to understand when these methods are called
➢ First, assume that a user enter a URL to web browser
➢ The browser then generates an http request to this URL
➢ This request is then sent to the appropriate server
➢ Second, the http request is received by the web server.
➢ The server maps this request to a particular servlet
➢ The servlet is dynamically retrieved and loaded into the address space of the server.
➢ The server invokes the init method() of the servlet
➢ This method is invoked only once when the servlet is first loaded into memory
➢ The server invokes the service() method of the servlet
➢ This method is called to process the http request and also formulate an http response
for the client
➢ The servlet remains in the address space & available to process any other http requests
➢ The service method() is called for each http request
➢ Finally the server may decide to unload the servlet from the memory.
➢ The algorithms are specific to each server
➢ The server calls the destroy method() to release any file resources that are allocated
to the servlet

Steps to Create a Servlet


1) Create and compile the servlet source code
2) Copy the servlets class file to the proper directory and add the servlets name and
mapping to the proper [Link] file
3) Start tomcat
4) Start a browser and request the servlet

A sample Servlet program([Link])


import [Link].*;
import [Link].*;
import [Link].*;
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Strinng message =“hello world”;
[Link]("text/html");

Dept of CSE,GST,Bengaluru Page 2


Unit-4: "Introduction to Servlet & JSP"

PrintWriter out = [Link]();


[Link]("<h1>" + message + "</h1>");
}
}

4.2 The Servlet API


➢ Two packages contain the classes and interfaces that are required to build the servlets
➢ They are
i)[Link]
ii)[Link]
➢ They constitutes the core of the servlet api
➢ These packages are not part of java core packages
➢ They are provided by Tomcat and java ee

4.3 The [Link] Package


➢ The [Link] package contains many interfaces and classes that are used by the
servlet or web container.
➢ These are not specific to any protocol.
➢ There are many interfaces in [Link]

➢ There are many classes in [Link] package. They are as follows:

Dept of CSE,GST,Bengaluru Page 3


Unit-4: "Introduction to Servlet & JSP"

Servlet Interface
➢ All servlet must implement the servlet interfaces
➢ It declares the init(),service() and destroy() methods that are called by the server
during the life cycle
➢ A method is also provided that allows a server to obtain any initialization parameters
Method Description
a)void init(ServletConfig Sc) –called when the servlet is intialized
b)void service(ServletRequest req,ServletResponse res) –called to process request
from client
c)void destroy()- called when the servlets unloaded
d)ServletConfig getServletConfig()-returns a ServletConfig object that contains any
initialization parameters

The Servlet Config Interface


➢ It allows a servlet to obtain configuration data when it is loaded
Methods
➢ ServletContext getServletContext()-returns the context for this servlet
➢ Servlet getInitParameter(String param)-returns the value of intialization
parameters
➢ String getServletName()- returns the name of the invoking servlet

The Generic Servlet Class


➢ The generic servlet class provides the implementation of the basic life cyle
➢ It implements the servlet and servletConfig interfaces
➢ In addition, a method to append a string to the server log is available
void log(string s)
void log(string s,Throwable s)

4.4 The [Link] Package


➢ Whenever working with http, it has also defined interfaces and classes
➢ The interfaces defines in [Link] are

➢ The classes defined in [Link] are

Dept of CSE,GST,Bengaluru Page 4


Unit-4: "Introduction to Servlet & JSP"

Cookie Class
➢ A cookie is stored on a client and contains state information
➢ Cookies are valuable for tracking user activities
➢ A servlet can write a cookies to a user machine via the addcookie() method
➢ Some Methods defined in cookie
String getName() –returns the name
String getValue() –returns the value

Http Servlet Class


✓ The httpServlet class extends the generic servlet.
✓ It is commonly used when developing servlet that receive and process http requests
✓ The methods defined in HttpServlet Class are
a)void doDelete - Handles an http delete request
b)void doGet() - Handles an http get request
c)void doPost() - Handles an http post request
d)void doPut() -Handles an http put request
e)Void doHead() -Handles an http head request

4.5 Handling Http Request and Responses


❖ The HttpServlet Class provides specialized methods that handles various types of http
requests.
❖ A servlet developer usually deploy one of these methods.
❖ These methods are doDelete(),doGet(),doPut(),doPost(),doTrace(),doHead().
❖ The commonly used methods are doGet() and doPost().

a)Handling HTTP GET Requests


A servlet is developed that handles the http get requests
The servlet is invoked when the page is submitted
One Example is demonstrated that handles the HTTP GET Request.
The Example contain two files
A)[Link]
B)[Link]
The html page contains the select element and a submit button & action parameter
contains the url
The java servlet program contains the doGet() method and it uses getParameter() to
obtain the selection from the user
[Link]
<html>
<body>
<center>
<form action = "[Link]
<B> color :</B>
<select name = "color" size="1" >
<option value = "red"> red </option>
<option value = "green"> green </option>
<option value = "blue"> blue </option>
</select>

Dept of CSE,GST,Bengaluru Page 5


Unit-4: "Introduction to Servlet & JSP"

<input type ="submit" value="submit">


</form>
<br> <br>
</body>
</html>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException
{
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B> the selected color is ");
[Link](color);
[Link]();
}
}

b) Handling the HTTP POST Requests


✓ A servlet is developed that handles the http post requests
✓ The servlet is invoked when the page is submitted
✓ The Example contain two files
✓ [Link]
✓ [Link]
✓ The html file contains the select and submit buttton and it has url and post method in
form tag.
✓ The java program uses the getPost() method and it uses getParameters() to obtain
information from the user
[Link]
<html >
<body>
<center>
<form name ="form1" method="post"
action ="[Link]
<B> color :</B>
<select name = "color" size="1" >
<option value = "red"> red </option>
<option value = "green"> green </option>
<option value = "blue"> blue </option>
</select>
<input type ="submit" value="submit" >
</form>

Dept of CSE,GST,Bengaluru Page 6


Unit-4: "Introduction to Servlet & JSP"

<br> <br>
</body>
</html>

[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class ColorGetServlet1 extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException
{
String color = [Link]("color");
[Link]("text/html");
PrintWriter pw = [Link]();
[Link]("<B> the selected color is ");
[Link](color);
[Link]();
}
}

Introduction to JSP
✓ JSP is a server side technology that does all the processing at server.
✓ It is used for creating dynamic web applications, using java as programming
language.
✓ JSP pages are easier to maintain than a Servlet.
✓ JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code,
While JSP adds Java code inside HTML using JSP tags.
✓ Everything a Servlet can do, a JSP page can also do it.
✓ JSP have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases
✓ It is an advanced version of Servlet Technology.
✓ JSP is first converted into servlet by JSP container before processing the client’s
request.
✓ In the end a JSP becomes a [Link] pages are converted into Servlet by the Web
Container.
✓ The Container translates a JSP page into servlet class source(.java) file and then
compiles into a Java Servlet class

Dept of CSE,GST,Bengaluru Page 7


Unit-4: "Introduction to Servlet & JSP"

4.6 Problem with Servlets


1. [Link] are difficult to code which are overcome in JSP. JSP is almost
a replacement of Servlets . (coding decreases more than half)
2. In Servlets, both static code and dynamic code are put together. In JSP, they are
separated. For example, In Servlets:
[Link](“Hello Mr.” + str + ” you are great man”);
In Servlets, in println(),put both static and dynamic content together.
In JSP:
HelloMr./static content as HTML code
<%= str %> // dynamic content as JSP code
you are great man // static content as HTML code
* In JSP, the static content and dynamic content is separated.
* Static content is written in HTML and dynamic content in JSP.
* Static content involves displaying company logo, company building, company
literature like company present and back history etc. which will never change.
* The dynamic content changes every day and every minute like displaying running
share prices, clearing client doubts.
The objects of PrintWriter,HttpSesssion,RequestDispatcher,ServletContext,ServrletConfig etc.
are created by the Programmer in Servlets and used.
* But in JSP, they are built-in and are known as implicit objects.
* In JSP, Programmer never creates these objects and straightaway use them as they are
implicitly created and given by JSP container. This decreases lot of coding.
4. A Servlet is a Java class. It is written like a normal Java. JSP is comes with some
elements that are easy to write.
5. JSP needs no compilation by the Programmer. Programmer deploys directly a JSP
source code file in server
where as in case of Servlets, the Programmer compiles manually a Servlet file and
deploys a .class file in server.
6. Writing alias name in <url-pattern> tag of [Link] is optional in JSP but mandatory in
Servlets
7. Thorough Java programming knowledge is needed to develop and maintain all aspects
of the application,
*since the processing code and the HTML elements are lumped together.
[Link] the look and feel of the application, or adding support for a new type of client
(such as a WML client), requires the servlet code to be updated and recompiled.

Dept of CSE,GST,Bengaluru Page 8


Unit-4: "Introduction to Servlet & JSP"

4.7 The anatomy of a JSP page

Structure of JSP program

• Everything in page that is not jsp element is called as template text


• The tagged elements are called as JSP elements
• Template text can be any text: HTML, WML, XML, or even plain text.
• Template text is always passed straight through to the browser.
• When a JSP page request is processed, the template text and dynamic content
generated by the JSP elements are merged.
• The result is sent as the response to the browser

4.8 JSP Processing


➢ Just as a web server needs a servlet container to provide an interface to servlets
➢ The server needs a JSP container to process JSP pages.
➢ The JSP container is responsible for converting requests for JSP pages.
➢ To process all JSP elements in the page, the container first turns the JSP page into a
servlet (known as the JSP page implementation class).
➢ The conversion is pretty straightforward
➢ All template text is converted to println( ) statements.
➢ All JSP elements are converted to Java code that implements the corresponding
dynamic behavior.
➢ The container then compiles the servlet class.
➢ The block diagram of JSP Processing is as shown below

Dept of CSE,GST,Bengaluru Page 9


Unit-4: "Introduction to Servlet & JSP"

✓ Converting the JSP page to a servlet and compiling the servlet form the translation
phase.
✓ The JSP container initiates the translation phase for a page automatically when it
receives the first request for the page.
✓ Since the translation phase takes a bit of time, the first user to request a JSP page
notices a slight delay.
✓ The translation phase can also be initiated explicitly; this is referred to as
precompilation of a JSP page
✓ The JSP container is also responsible for invoking the JSP page implementation class
(the generated servlet) to process each request and generate the response. This is
called the request processing phase.
✓ When the JSP page is modified, it goes through the translation phase again before
entering the request processing phase.
✓ The JSP container is often implemented as a servlet configured to handle all requests
for JSP pages.
✓ In fact, these two containers—a servlet container and a JSP container—are often
combined in one package under the name web container.
✓ A JSP page inherits all the advantages of a servlet.
✓ So in a way, a JSP page is really just another way to write a servlet without having
✓ to be a Java programming( Except for the translation phase, a JSP page is
✓ handled exactly like a regular servlet);
✓ it's loaded once and called repeatedly, until the server is shut down.

4.9 JSP APPLICATIONS


✓ The simplest web application, such as an online phone list or an employee vacation
planner.
✓ Enterprise applications, such as a human resource application or a sophisticated online
shopping site can be developed by using JSP.
✓ A design model suitable for both simple and complex applications called Model-
View-Controller (MVC).
✓ In a server application, classify the parts of the application as: business logic,
presentation, and request processing.

Dept of CSE,GST,Bengaluru Page 10


Unit-4: "Introduction to Servlet & JSP"

✓ Business logic is the term used for the manipulation of an application’s data, i.e.,
customer, product, and order information.
✓ Presentation refers to how the application is displayed to the user, i.e., the position,
font, and size.
✓ And finally, request processing is what ties the business logic and presentation parts
together.
✓ In MVC terms, the Model corresponds to business logic and data, the View to the
presentation logic, and the Controller to the request processing.

4.10 JSP Components


JSP categorized into 4 types
* Directives
* Standard Action elements
* Scriptlet Eléments
* Comments

a)Directives
➢ A directives tag always appears at the top of your JSP file.
➢ It is global definition sent to the JSP engine.
➢ Directives contain special processing instructions for the web container.
➢ You can import packages, define error handling pages or the session information of
the JSP page.
➢ Directives are defined by using <%@ and %> tags.
➢ Syntax -
<%@ directive attribute="value" %>

Directive elements
a)<%@ page ...%> Defines page-dependent attributes, such as session tracking, error page,
and buffering requirements

Dept of CSE,GST,Bengaluru Page 11


Unit-4: "Introduction to Servlet & JSP"

Example
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%int a=60,b=30,c=a/b;
[Link](a/b);
%>
</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h1> Error in page</h1>
</body>
</html>

b) <%@ include ... %>- Includes a file during the translation phase

Example
[Link]
<head>
<%@include file="[Link]" %>
<title>Insert title here</title>
</head>
<body>
<h2> This is the main page</h2>
</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>

Dept of CSE,GST,Bengaluru Page 12


Unit-4: "Introduction to Servlet & JSP"

<h1 style="font-family:impact;color:green;font-size:35px"> Gitam College </h1>


</body>
</html>

c)<%@ tag lib ... %>Declares a tag library, containing custom actions, that is used in

Example
[Link]
<!DOCTYPE html>
<%@ taglib prefix="c" uri="[Link] %>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<c:forEach var = "i" begin = "1" end = "5">
Item <c:out value = "${i}"/><p>
</c:forEach>
</body>
</html>

b) Standard Action Elements


➢ Action elements typically perform some action based on information that is required
at the exact time the JSP page is requested by a browser.
➢ An action can, for instance, access parameters sent with the request to do a database
lookup.
➢ It can also dynamically generate HTML, such as a table filled with information
retrieved from an external system.

i)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
<jsp:forward page="relativeURL | <%= expression %>" />

It includes resource at translation time.

Dept of CSE,GST,Bengaluru Page 13


Unit-4: "Introduction to Servlet & JSP"

• It is better for static pages.

Example
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h2> This is index page </h2>
<jsp:forward page="[Link]" />
</body>
</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%[Link]("Today is:"+[Link]().getTime()); %>
</body>
</body>
</html>

ii) 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.
Syntax of jsp:include action tag
<jsp:include page="relativeURL | <%= expression %>" />

Example
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>

Dept of CSE,GST,Bengaluru Page 14


Unit-4: "Introduction to Servlet & JSP"

<h2>this is index page</h2>


<jsp:include page="[Link]" />
<h2>end section of index page</h2>
</body>
</html>

[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<% [Link]("Today is:"+[Link]().getTime()); %>
</body>
</html>

iii)Java Beans

A JavaBean is a Java class that should follow the 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

[Link]
package mypack;
public class Employee implements [Link]{
private int id;
private String name;
public Employee(){}
public void setId(int id){[Link]=id;}
public int getId(){return id;}
public void setName(String name){[Link]=name;}
public String getName(){return name;}
}

[Link]
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
[Link]("Arjun");//setting value to the object
[Link]([Link]());
}}

Dept of CSE,GST,Bengaluru Page 15


Unit-4: "Introduction to Servlet & JSP"

iv) Jsp:Use Bean

• The jsp:useBean action tag is used to locate or instantiate a bean class.


Syntax
<jsp:useBean id = "beanName" class = "className"
scope = "page | request | session | application">

v)jsp:getProperty Tag & jsp:setProperty Tag

• The getProperty tag is used to retrieve a property from a JavaBeans instance.


The syntax of the getProperty tag is as follows:
<jsp:getProperty name="beanName" property="propertyName" />
• The setProperty tag is used to store data in JavaBeans instances.
The syntax of setProperty tag is:
<jsp:setProperty name="beanName" property="propertyName">

Example
[Link]
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="[Link]" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>
</body>
</html>

[Link]
package [Link];

public class User {


private String name;
private String password;
private String email;

// Setter methods
public void setName(String name) {
[Link] = name;
}

Dept of CSE,GST,Bengaluru Page 16


Unit-4: "Introduction to Servlet & JSP"

public void setPassword(String password) {


[Link] = password;
}

public void setEmail(String email) {


[Link] = email;
}

// Getter methods
public String getName() {
return name;
}

public String getPassword() {


return password;
}

public String getEmail() {


return email;
}
}

[Link]
<jsp:useBean id="u" class="[Link]"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
</body>
</html>

c)scripting Elements
Scripting elements, allow you to add small pieces of code (typically Java code) in a JSP page
Like actions, they are also executed when the page is requested.

Dept of CSE,GST,Bengaluru Page 17


Unit-4: "Introduction to Servlet & JSP"

i)Scriplets
❖ In this tag we can insert any amount of valid java code.
❖ These codes are placed in _jspService method by the JSP engine.
❖ Scriptlets can be used anywhere in the page.
❖ Scriptlets are defined by using <% and %> tags.
❖ Syntax - <% Scriptlets%>

Examples:
[Link]
<html>
<body>
<form action="[Link]">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
[Link]
<html>
<body>
<% String name=[Link]("uname");
[Link]("welcome "+name); %>
</body>
</html>

ii)Expressions:
❖ Expressions in JSPs is used to output any data on the generated page.
❖ These data are automatically converted to string and printed on the output stream.
❖ It is an instruction to the web container for executing the code with in the expression
and replace it with the resultant output content.
❖ For writing expression in JSP use <%= and %> tags.
❖ Syntax - <%= expression %>

Examples:
[Link]
<html>
<body>

Dept of CSE,GST,Bengaluru Page 18


Unit-4: "Introduction to Servlet & JSP"

<form action="[Link]">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
[Link]
<html>
<body>
<%= "Welcome "+[Link]("uname") %>
</body>
</html>

iii)Declarations
This tag is used for defining the functions and variables to be used in the JSP.
This element of JSPs contains the java variables and methods which you can call in
expression block of JSP page.
Declarations are defined by using <%! and %> tags.
Whatever you declare within these tags will be visible to the rest of the page.
Syntax - <%! declaration(s) %>
Example1:
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example2:
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

d)Comments
• Comments help in understanding what is actually code doing.
• JSPs provides two types of comments for putting comment in your page.
• First type of comment is for output comment which is appeared in the output stream
on the browser.

Dept of CSE,GST,Bengaluru Page 19


Unit-4: "Introduction to Servlet & JSP"

• It is written by using the <!-- and --> tags.


Syntax - <!-- comment text -->
• Second type of comment is not delivered to the browser.
• It is written by using the <%-- and --%> tags.
Syntax - <%-- comment text --%>

4.11 JSP - Standard Tag Library (JSTL)


✓ The Java Server Pages Standard Tag Library (JSTL) is a collection of useful JSP tags
which encapsulates the core functionality common to many JSP applications.
✓ Classification of The JSTL Tags
According to their functions, The JSTL tags can be classified, into the following JSTL tag
library groups that can be used when creating a JSP page −
❖ Core Tags
❖ Formatting tags
❖ SQL tags
❖ XML tags
❖ JSTL Functions

a)Core Tags
❖ The core group of tags are the most commonly used JSTL tags.
❖ Following is the syntax to include the JSTL Core library in your JSP
<%@ taglib prefix = "c" uri = "[Link] %>
List of CoreTags
1.<c:out>:Like <%= ... >, but for expressions.
2.<c:set >:Sets the result of an expression evaluation in a 'scope'
3.<c:remove >:Removes a scoped variable (from a particular scope, if specified).
4.<c:catch>:Catches any Throwable that occurs in its body and optionally exposes it.
5.<c:if>:Simple conditional tag which evalutes its body if the supplied condition is
true.
Example
[Link]
<%@ taglib uri="[Link] prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="income" scope="session" value="${4000*4}"/>
<c:if test="${income > 8000}">
<p>My income is: <c:out value="${income}"/><p>
</c:if>
</body>
</html>
</body>
</html>

Dept of CSE,GST,Bengaluru Page 20


Unit-4: "Introduction to Servlet & JSP"

b)Formatting Tags
❖ The JSTL formatting tags are used to format and display text, the date, the time, and
numbers for internationalized Websites.
❖ Following is the syntax to include Formatting library in your JSP −
<%@ taglib prefix = "fmt" uri = "[Link] %>

List of Formatting Tags


1.<fmt:formatNumber>:To render numerical value with specific precision or format.
2.<fmt:parseNumber>:Parses the string representation of a number, currency, or percentage.
3.<fmt:formatDate>:Formats a date and/or time using the supplied styles and pattern.
4.<fmt:parseDate>:Parses the string representation of a date and/or time
5.<fmt:bundle>:Loads a resource bundle to be used by its tag body.
6.<fmt:timeZone>:Specifies the time zone for any time formatting or parsing actions nested
in its body

Example:
[Link]
<%@ taglib prefix="c" uri="[Link] %>
<%@ taglib prefix="fmt" uri="[Link] %>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<h3>The fmt:parseNumber tag Example is:</h3>
<c:set var="Amount" value="786.970" />

<fmt:parseNumber var="j" type="number" value="${Amount}" />


<p><i>Amount is:</i> <c:out value="${j}" /></p>

<fmt:parseNumber var="j" integerOnly="true" type="number" value="${Amount}" />


<p><i>Amount is:</i> <c:out value="${j}" /></p>
</body>
</html>

c)SQL Tags
❖ The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
❖ Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "[Link] %>
List of Sql Tags
1.<sql:setDataSource>:Creates a simple DataSource suitable only for prototyping
2.<sql:query>:Executes the SQL query defined in its body or through the sql attribute.
3.<sql:update>:Executes the SQL update defined in its body or through the sql attribute.

Dept of CSE,GST,Bengaluru Page 21


Unit-4: "Introduction to Servlet & JSP"

4.<sql:transaction >:Provides nested database action elements with a shared Connection, set
up to execute all statements as one transaction.

d)JSTL Functions
❖ JSTL includes a number of standard functions, most of which are common string
manipulation functions.
❖ Following is the syntax to include JSTL Functions library in your JSP −
<%@ taglib prefix = "fn" uri = "[Link] %>

List of Jstl Functions


[Link]:contains() It is used to test if an input string containing the specified substring in a
program.
[Link]:containsIgnoreCase() It is used to test if an input string contains the specified
substring as a case insensitive way.
[Link]:endsWith() It is used to test if an input string ends with the specified suffix.
[Link]:startsWith() It is used for checking whether the given string is started with a
particular string value.
[Link]:toLowerCase() It converts all the characters of a string to lower case.
[Link]:toUpperCase() It converts all the characters of a string to upper case.

Example:
[Link]
<%@ taglib uri="[Link] prefix="c" %>
<%@ taglib uri="[Link] prefix="fn" %>
<html>
<head>
<title>Using JSTL Functions</title>
</head>
<body>
<c:set var="String" value="Welcome to functions"/>
<c:if test="${fn:contains(String, 'functions')}">
<p>Found functions string<p>
</c:if>
</body>
</html>

e) XML tags
❖ The JSTL XML tags provide a JSP-centric way of creating and manipulating the
XML documents.
❖ Following is the syntax to include the JSTL XML library in your JSP.
❖ The JSTL XML tag library has custom tags for interacting with the XML data.
<%@ taglib prefix = "x" uri = "[Link] %>

Jstl Xml Tags


x:out-Similar to <%= ... > tag, but for XPath expressions.
x:parse-It is used for parse the XML data specified either in the tag body or an attribute.
x:set-It is used to sets a variable to the value of an XPath expression.

Dept of CSE,GST,Bengaluru Page 22


Unit-4: "Introduction to Servlet & JSP"

x:if-It is used for evaluating the test XPath expression and if it is true, it will processes its
body content
x:when-It is a subtag of that will include its body if the condition evaluated be 'true'.

Example:
[Link]
<%@ taglib prefix="c" uri="[Link] %>
<%@ taglib prefix="x" uri="[Link] %>

<html>
<head>
<title>XML Tags</title>
</head>
<body>
<h2>Vegetable Information:</h2>
<c:set var="vegetable">
<vegetables>
<vegetable>
<name>onion</name>
<price>40/kg</price>
</vegetable>
<vegetable>
<name>Potato</name>
<price>30/kg</price>
</vegetable>
<vegetable>
<name>Tomato</name>
<price>90/kg</price>
</vegetable>
</vegetables>
</c:set>
<x:parse xml="${vegetable}" var="output"/>
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[1]/name" /><br>
<b>Price of the Potato is</b>:
<x:out select="$output/vegetables/vegetable[2]/price" />
</body>
</html>

Dept of CSE,GST,Bengaluru Page 23

You might also like