Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 4

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

Servlets

 Java Servlets are programs that run on a Web or Application server and act as a middle
layer between a requests coming from a Web browser or other HTTP client and databases
or applications on the HTTP server.
 Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
 Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary to create
a separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.

Servlets Architecture

 The following diagram shows the position of Servlets in a Web Application.


Servlets Tasks

 Servlets perform the following major tasks −


 Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
Types of Servlets
 There is a possibility of developing ‘n’ types of servlets, like httpservlet, ftpservlet,
smtpservlet etc. for all these protocol specific servlet classes GenericServlet is the common
super class containing common properties and logics. So, GenericServlet is not a separate
type of servlet.
 As of now Servlet API is giving only one subclass to GenericServlet i.e HttpServlet class
because all web servers are designed based on the protocol http.
 Generic servlets extend javax.servlet.GenericServlet – It is protocol independent servlet.
Generic Servlet is a base class servlet from which all other Servlets are derived. Generic
Servlet supports for HTTP, FTP and SMTP protocols. It implements the Servlet and
ServletConfig interface. It has only init() and destroy() method of ServletConfig interface in
its life cycle. It also implements the log method of ServletContext interface.
 HTTP servlets extend javax.servlet.HttpServlet – HTTPServlet is HTTP dependent
servlet. The HTTP protocol is a set of rules that allows Web browsers and servers to
communicate. When Web browsers and servers support the HTTP protocol, Java-based web
applications are dependent on HTTP Servlets.HttpServlet is Extended by Generic Servlet. It
provides an abstract class for the developers for extend to create their own HTTP specific
servlets.
Servlets - Life Cycle
 A servlet life cycle can be defined as the entire process from its creation till the
destruction.
 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.
 Finally, servlet is garbage collected by the garbage collector of the JVM.

The init() Method:

• The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as
with the init method of applets.
• The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first started.
• When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.
• The init method definition looks like this −

public void init() throws ServletException {

// Initialization code... }
The service() Method

• The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from the
client( browsers) and to write the formatted response back to the client.
• Each time the server receives a request for a servlet, the server spawns a new thread and
calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
• Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

• The service () method is called by the container and service method invokes doGet,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type of
request you receive from the client.
• The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.

The doGet() Method

• A GET request results from a normal request for a URL or from an HTML form that has
no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code }

The doPost() Method

• A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Servlet code

The destroy() Method

• The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
• After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this −

public void destroy() {

// Finalization code...

Architecture Diagram
• The following figure depicts a typical servlet life-cycle scenario.
 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.
Advantages of Servlets
 A servlet can be imagined to be as an applet running on the server side. Some of the other
server side technologies available are Common Gateway Interface (CGI), server side
JavaScript and Active Server Pages (ASP). Advantages of servlets over these server side
technologies are as follows:
 Persistent: Servlets remain in memory until explicitly destroyed. This helps in serving
several incoming requests. Servlets establishes connection only once with the database
and can handle several requests on the same database. This reduces the time and
resources required to establish connection again and again with the same database.
Whereas, CGI programs are removed from the memory once the request is processed and
each time a new process is initiated whenever new request arrives.
 Portable: Since servlets are written in Java, they are portable. That is, servlets are
compatible with almost all operating systems. The programs written on one operating
system can be executed on other operating system.
 Server-independent: Servlets are compatible with any web server available today. Most
of the software vendors today support servlets within their web server products. On the
other hand, some of the server side technologies like server side JavaSricpt and ASP can
run on only selected web servers. The CGI is compatible with the web server that has
features to supports it.
 Protocol-independent: Servlets can be created to support any of the protocols like FTP
commands, Telnet sessions, NNTP newsgroups, etc. It also provides extended support for
the functionality of HTTP protocol.
 Extensible: Servlets being written in Java, can be extended and polymorphed into the
objects that suits the user requirement.
 Secure: Since servlets are server side programs and can be invoked by web server only,
they inherit all the security measures taken by the web server. They are also safe from
the problems related to memory management as Java does not support the concept of
pointers and perform garbage collection automatically.
 Fast: Since servlets are compiled into bytecodes, they can execute more quickly as
compared to other scripting languages. The bytecode compilation feature helps servlets
to give much better performance. In addition, it also provides advantage of strong error
and type checking.
Cookies

 A cookie is a small piece of information that is persisted between the multiple client
requests.
 A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

How Cookie works:

 By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.

Types of Cookie:

 There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

 It is valid for single session only. It is removed each time when user closes the
browser.

Persistent cookie

 It is valid for multiple session. It is not removed each time when user closes the
browser. It is removed only if user logout or sign-out.
Advantage of Cookies:

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies:

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.

Cookie class:

 javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of


useful methods for cookies.

Constructor of Cookie class

Constructor Description
Cookie() Constructs a cookie.
Cookie(String name, String Constructs a cookie with a specified name and
value) value.

Useful Methods of Cookie class:

 There are given some commonly used methods of the Cookie class.

Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be changed
after creation.
public String getValue() Returns the value of the cookie.
public void setName(String Changes the name of the cookie.
name)
public void setValue(String Changes the value of the cookie.
value)
Other methods required for using Cookies:

 For adding cookie or getting the value from the cookie, we need some methods provided by
other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used
to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to
return all the cookies from the browser.

Create Cookie:

 Let's see the simple code to create cookie.

Cookie ck=new Cookie ("user","sonoo jaiswal");//creating cookie object

response.addCookie(ck);//adding cookie in the response

Delete Cookie:

 Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie

ck.setMaxAge(0);//changing the maximum age to 0 seconds

response.addCookie(ck);//adding cookie in the response

Get Cookies:

 Let's see the simple code to get all the cookies.

Cookie ck[]=request.getCookies();

for(int i=0;i<ck.length;i++)

out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());

}
Example of Servlet Cookies:

 In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.

index.html

<form action="servlet1" method="post">

Name:<input type="text" name="userName"/><br/>

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

</form>

FirstServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object

response.addCookie(ck);//adding cookie in the response

//creating submit button

out.print("<form action='servlet2'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}

SecondServlet.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){

try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();

out.print("Hello "+ck[0].getValue());

out.close();
}catch(Exception e){System.out.println(e);}

web.xml

<web-app>

<servlet>

<servlet-name>s1</servlet-name>

<servlet-class>FirstServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s1</servlet-name>

<url-pattern>/servlet1</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>s2</servlet-name>

<servlet-class>SecondServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>s2</servlet-name>

<url-pattern>/servlet2</url-pattern>

</servlet-mapping>

</web-app>
Output
Session

 HttpSession Interface provides a way to identify a user across more than one page request
or visit to a Web site and to store information about that user.
 Web container creates a session id for each user. The container uses this id to identify the
particular user.
 The servlet container uses this interface to create a session between an HTTP client and an
HTTP server.
 The session persists for a specified time period, across more than one connection or page
request from the user.

Get the HttpSession object

 The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. publicHttpSessiongetSession():Returns the current session associated with this request,
or if the request does not have a session, creates one.
2. publicHttpSessiongetSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns
a new session.
Destroy Session
session.invalidate();

Set/Get data in session


session.setAttribute(name,value);
session.getAttribute(name);

Methods
 public String getId():Returns a string containing the unique identifier value.
 public long getCreationTime():Returns the time when this session was created, measured
in milliseconds since midnight January 1, 1970 GMT.
 public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1, 1970
GMT.
 public void invalidate():Invalidates this session then unbinds any objects bound to it.
Steps

 On client's first request, the Web Container generates a unique session ID and gives it back
to the client with response. This is a temporary session created by web container.
 The client sends back the session ID with each request. Making it easier for the web container
to identify where the request is coming from.
 The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.

Ex: SessionTrack.java

import java.io.*; importjavax.servlet.*; importjavax.servlet.http.*;


public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest
request,
HttpServletResponse response) throws ServletException, IOException {
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
String title = "Welcome to my website"; String userID = "";
Integer visitCount = new Integer(0);
if (session.isNew())
{
userID = "Kalpana"; session.setAttribute("UserId", "Kalpana");
}
else {
visitCount = (Integer)session.getAttribute("visitCount"); visitCount = visitCount + 1;
userID = (String)session.getAttribute("UserId");
}
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html"); PrintWriter out = response.getWriter();
out.println("<html>" +
"<body>" +
"<h1>Session Infomation</h1>" + "<table border='1'>" +
"<tr><th>Session info</th><th>value</th></tr>" + "<tr><td>id</td><td>" +
session.getId() + "</td></tr>" + "<tr><td>User ID</td<td>" + userID + ―</td></tr>" +
"<tr><td>Number of visits</td><td>" + visitCount + "</td></tr>" +
"</table></body></html>");
}
}
web.xml

<web-app>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<url-pattern>/SessionTrack</url-pattern>
</servlet- mapping>
</web-app

Output
JSP (Java Server Pages)

 JSP Stands for "Java Server Pages". Using "JSP" we can use both, static HTML with
dynamically-generated HTML. Web pages created using CGI programs are mostly static,
dynamic part is limited to a few small locations. But using CGI and servlet, you can generate
entire page through one program. Using JSP, you can built two parts separately.
 JSP is the product of Sun Microsystems Inc. JSP has more advance features than Servlet. JSP
separates the presentation logic from the business logic, provide facility to developers to
work separately without any trouble. JSP have the properties of Cold fusion and ASP and
hence provide the flexibility to embed the business logic efficiently within the HTML content
(presentation logic).
Advantages of JSP:-
 JSP is useful for server side programming
 JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.
 JSP uses simplified scripting language based syntax for embedding HTML into JSP.
 JSP containers provide easy way for accessing standard objects and actions.
 JSP reaps all the benefits provided by JAVA servlets and web container environment, but
they have an added advantage of being simpler and more natural program for web
enabling enterprise developer
 JSP use HTTP as default request /response communication paradigm and thus make JSP
ideal as Web Enabling Technology

JSP and Servlets

 JSP documents are not executed directly


 When a JSP document is first visited,
 First the server translates the JSP document to a servlet
 Compiles the servlet
 Then the servlet is executed
 If any error occurs while executing, the exception will occur which gives the information
for the servlet not for the JSP
 A JSP-generated servlet has a _jspService() method rather than doGet() or doPost()
 This method begins to access the java code by creating a number of implicit objects.
Implicit Objects in JSP

 JSP Implicit Objects are:


 Pre-defined variables that can be included in JSP expressions and scriptlets.
 Implemented from servlet classes and interfaces.
 The followings are the implicit objects supported by jsp.

OBJECT CLASS
Out JSP writer

Request HttpServletRequest

Response HttpServletRespose

Session HttpSession

Application ServletContext

Config Sevlet Config

Difference between servlet and JSP

 In servlets both the presentation and business logic are place it together where as in jsp both
are separated by defining by java beans.
 Servlet is a java code where HTML code can be embedded whereas in jsp, it is a kind of HTML
where java code can be embedded by using special tags.
 JSP allows creating and using custom tag libraries.

For example

<%@page language=”java” content Type="text/html" %>


<html><body>

<% out.println(“JSP = HTML+JAVA”) %> Today


date is:

</body> </html>

 In this code, jsp elements that use java code are merged with HTML code.
Scoped Variables

 Four different types of variable scopes within the JSP page can be used:
 Page Scope: Objects stored in page scope can only be retrieved during the processing of
that page for a specific request.
 Request Scope: Objects stored in request scope can be retrieved during the processing
of all pages taking part in the processing of a request
 Session Scope: Object stored in session scope can be retrieved by any pages accessed by
a user during a single interactive session with the Web application
 Application Scope: Object stored in application scope is accessible from all pages and
for all users, until the Web application itself is unloaded
Applications

 A web application is a collection of resources that are used together to implement some web-
based functionality
 To develop a web applications the following resources are needed:
 Server side Programming
 Servlets /JSP,
 Client side programming: HTML documents, style sheets, XML , images, non-servlet java
classes etc,
 Web form validation: JavaScript, non-servlet Java classes, etc.
 Other resources:
 Databases: MS-Access, MySQL/SQL
 Web server: Appache Tiomcat/ Java Web server/ Glass fish,
 Browser: IE/Netscape/Chrome/FireFox

Basic JSP

 JSP page has the following components(contents)


 Directives
 Declarations
 Expressions
 Standard Actions
 Scriplets
Directives

 The directives are used to specify the attributes of the JSP page. Also it can be used to import
java packages in to the jsp page.
 For example,

<%@ page language=”java” contentType=”text/html” %>

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

 Where language=”java” tells tha the page is contains java code, the code
contentType=”text/html” specifies the MIME type, the code import =”java.util.*” used to
import all the classes of java’s utility package into this page.

Declarations

 Provide a mechanism to define variables and methods. Declarative statements are placed
within <%! and %> symbols and always end with a semicolon.
 Syntax: <%! Declare all the variables here %> For example, <% int a, b %>

Scriplets:

 Consists of valid Java code snippets that are enclosed within <% and %> symbols. The syntax
to declare JSP scriptlets to include valid Java code is:

<% Java code %>

 Scriplets can't generate HTML itself. Using "out" variable, it can generate HTML. This variable
does not need to be declared. It is already predefined for Scriplets, along with some other
variables. The "out" variable is of type "javax.servlet.jsp.JspWriter".
 For example,

<HTML>
<BODY>
<%
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>

Output: Hello! The time is now 12/12/2010 12:10:02


Expression:

 Insert values directly into the output. The syntax to include a JSP expression in the JSP file is:

<%= expression %>.

 For example, <%= "Hello World!" %>

Actions:

 The elements which are used to access the java bean in a jsp page is called jsp action
elements.
 JSP defines the following action elements:
1. Standard action and Custom action
2. JSTL

Standard action tags

S.No. Syntax & Purpose


jsp:include
1
Includes a file at the time the page is requested.
jsp:useBean
2
Finds or instantiates a JavaBean.
jsp:setProperty
3
Sets the property of a JavaBean.
jsp:getProperty
4
Inserts the property of a JavaBean into the output.
jsp:forward
5
Forwards the requester to a new page.
jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the Java
plugin.
jsp:element
7
Defines XML elements dynamically.
jsp:attribute
8
Defines dynamically-defined XML element's attribute.
jsp:body
9
Defines dynamically-defined XML element's body.
jsp:text
10
Used to write template text in JSP pages and documents.
JSP - Standard Tag Library (JSTL):

 JSTL: JSP Standard Tag Libraries is a collection of JSP custom tags


 The goal of JSTL, is to help simplify Java Server Pages page authoring tasks. To achieve this
goal, JSTL has provided custom tags for many common JSP page authoring tasks that require
scripting statements to manipulate server side dynamic data.

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 −
 Core Tags
 Formatting tags
 SQL tags
 XML tags
 JSTL Functions

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 = "http://java.sun.com/jsp/jstl/core" %>

 Following table lists out the core JSTL Tags –


S.No. Tag & Description


<c:out>
1
Like <%= ... >, but for expressions.
<c:set >
2
Sets the result of an expression evaluation in a 'scope'
<c:remove >
3
Removes a scoped variable (from a particular scope, if specified).
<c:catch>
4
Catches any Throwable that occurs in its body and optionally exposes it.
<c:if>
5
Simple conditional tag which evalutes its body if the supplied condition is true.
6 <c:choose>
Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>.
<c:when>
7
Subtag of <choose> that includes its body if its condition evalutes to 'true'.
<c:otherwise >
8 Subtag of <choose> that follows the <when> tags and runs only if all of the prior
conditions evaluated to 'false'.
<c:import>
9 Retrieves an absolute or relative URL and exposes its contents to either the page, a
String in 'var', or a Reader in 'varReader'.
<c:forEach >
10 The basic iteration tag, accepting many different collection types and supporting
subsetting and other functionality .
<c:forTokens>
11
Iterates over tokens, separated by the supplied delimeters.
<c:param>
12
Adds a parameter to a containing 'import' tag's URL.
<c:redirect >
13
Redirects to a new URL.
<c:url>
14
Creates a URL with optional query parameters

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 = "http://java.sun.com/jsp/jstl/fmt" %>

 Following table lists out the Formatting JSTL Tags −


S.No. Tag & Description
<fmt:formatNumber>
1
To render numerical value with specific precision or format.
<fmt:parseNumber>
2
Parses the string representation of a number, currency, or percentage.
<fmt:formatDate>
3
Formats a date and/or time using the supplied styles and pattern.
<fmt:parseDate>
4
Parses the string representation of a date and/or time
<fmt:bundle>
5
Loads a resource bundle to be used by its tag body.
<fmt:setLocale>
6
Stores the given locale in the locale configuration variable.
<fmt:setBundle>
7 Loads a resource bundle and stores it in the named scoped variable or the bundle
configuration variable.
<fmt:timeZone>
8
Specifies the time zone for any time formatting or parsing actions nested in its body.
<fmt:setTimeZone>
9
Stores the given time zone in the time zone configuration variable
<fmt:message>
10
Displays an internationalized message.
<fmt:requestEncoding>
11
Sets the request character encoding

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 = "http://java.sun.com/jsp/jstl/sql" %>

 Following table lists out the SQL JSTL Tags


S.No. Tag & Description
<sql:setDataSource>
1
Creates a simple DataSource suitable only for prototyping
<sql:query>
2
Executes the SQL query defined in its body or through the sql attribute.
<sql:update>
3
Executes the SQL update defined in its body or through the sql attribute.
<sql:param>
4
Sets a parameter in an SQL statement to the specified value.
<sql:dateParam>
5
Sets a parameter in an SQL statement to the specified java.util.Date value.
<sql:transaction >
6 Provides nested database action elements with a shared Connection, set up to
execute all statements as one transaction.

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. This includes
parsing the XML, transforming the XML data, and the flow control based on the XPath
expressions.

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


 Following is the list of XML JSTL Tags −
S.No. Tag & Description
<x:out>
1
Like <%= ... >, but for XPath expressions.
<x:parse>
2
Used to parse the XML data specified either via an attribute or in the tag body.
<x:set >
3
Sets a variable to the value of an XPath expression.
<x:if >
4 Evaluates a test XPath expression and if it is true, it processes its body. If the test
condition is false, the body is ignored.
<x:forEach>
5
To loop over nodes in an XML document.
<x:choose>
6 Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise> tags.
<x:when >
7
Subtag of <choose> that includes its body if its expression evalutes to 'true'.
<x:otherwise >
8 Subtag of <choose> that follows the <when> tags and runs only if all of the prior
conditions evaluates to 'false'.
<x:transform >
9
Applies an XSL transformation on a XML document
<x:param >
10
Used along with the transform tag to set a parameter in the XSLT stylesheet

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 = "http://java.sun.com/jsp/jstl/functions" %>
 Following table lists out the various JSTL Functions –
S.No. Function & Description
fn:contains()
1
Tests if an input string contains the specified substring.
fn:containsIgnoreCase()
2
Tests if an input string contains the specified substring in a case insensitive way.
fn:endsWith()
3
Tests if an input string ends with the specified suffix.
fn:escapeXml()
4
Escapes characters that can be interpreted as XML markup.
fn:indexOf()
5
Returns the index withing a string of the first occurrence of a specified substring.
fn:join()
6
Joins all elements of an array into a string.
fn:length()
7
Returns the number of items in a collection, or the number of characters in a string.
fn:replace()
8 Returns a string resulting from replacing in an input string all occurrences with a
given string.
fn:split()
9
Splits a string into an array of substrings.

fn:startsWith()
10
Tests if an input string starts with the specified prefix.
fn:substring()
11
Returns a subset of a string.
fn:substringAfter()
12
Returns a subset of a string following a specific substring.
fn:substringBefore()
13
Returns a subset of a string before a specific substring.
fn:toLowerCase()
14
Converts all of the characters of a string to lower case.
fn:toUpperCase()
15
Converts all of the characters of a string to upper case.
fn:trim()
16
Removes white spaces from both ends of a string.

You might also like