moinrazakhan.files.wordpress.com€¦  · web viewjsp introduction: java server pages or jsp for...

62
JSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time. In today's environment most web sites servers dynamic pages based on user request. Database is very convenient way to store the data of users and other things. JDBC provide excellent database connectivity in heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web application. Java is known for its characteristic of "write once, run anywhere." JSP pages are platform independent. Your port your .jsp pages to any platform. Other Servers that support JSP Apache Tomcat. Tomcat is the official reference implementation of the servlet 2.2 and JSP 1.1 specifications. It can be used as a small stand-alone server for testing servlets and JSP pages, or can be integrated into the Apache Web server. Allaire JRun. JRun is a servlet and JSP engine that can be plugged into Netscape Enterprise or FastTrack servers, IIS, Microsoft Personal Web Server, older versions of Apache, O?Reilly?s WebSite, or StarNine WebSTAR.

Upload: others

Post on 28-Feb-2021

5 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

JSP introduction:

Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy.  JSP pages are efficient, it loads into the web servers memory  on receiving the request very first time and the subsequent calls are served within a very short period of time. 

  In today's environment most web sites servers dynamic pages based on user request. Database is very convenient way to store the data of users and other things. JDBC provide excellent database connectivity in heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web application. 

   Java is known for its characteristic of "write once, run anywhere." JSP pages are platform independent. Your port your .jsp pages to any platform.   

Other Servers that support JSP

Apache Tomcat. Tomcat is the official reference implementation of the servlet 2.2 and JSP 1.1 specifications. It can be used as a small stand-alone server for testing servlets and JSP pages, or can be integrated into the Apache Web server. 

Allaire JRun. JRun is a servlet and JSP engine that can be plugged into Netscape Enterprise or FastTrack servers, IIS, Microsoft Personal Web Server, older versions of Apache, O?Reilly?s WebSite, or StarNine WebSTAR.

New Atlanta?s ServletExec. ServletExec is a fast servlet and JSP engine that can be plugged into most popular Web servers for Solaris, Windows, MacOS, HP-UX and Linux. You can download and use it for free, but many of the advanced features and administration utilities are disabled until you purchase a license.

Gefion's LiteWebServer (LWS).  LWS is a small free Web server that supports servlets version2.2 and JSP 1.1.

GNU JSP . free, open source engine that can be installed on apache web server.

Page 2: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

PolyJSP . PolyJsp is based on XML/XSL and has been designed to be extensible. Now supportsWebL  

JRUN . Available for IIS server. WebSphere . IBM's WebSphere very large application server now implements JSP.

 

JSP ARCHITECTURE:

JSP Architecture

The web server needs a JSP engine ie. container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to support JSP pages development.

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 web page using JSP:

As with a normal page, your browser sends an HTTP request to the web server. 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. 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 that implements the corresponding dynamic behavior of the page.

Page 3: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.

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, which the servlet engine passes to the web server inside an HTTP response.

The web server forwards the HTTP response to your browser in terms of static HTML content. Finally web browser handles the dynamically generated HTML page inside the HTTP response

exactly as if it were a static page.

All the above mentioned steps can be shown below 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 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

JSP - Life Cycle

he key to understanding the low-level functionality of JSP is to understand the simple life cycle they follow.

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

The following are the paths followed by a JSP

Compilation Initialization

Page 4: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

Execution Cleanup

The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:

JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps:

Parsing the JSP. Turning the JSP into a servlet. Compiling the servlet.

JSP 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() method:

public void jspInit(){ // Initialization code...}

Page 5: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

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.

JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.

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.

JSP Cleanup:

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to perform any cleanup, such as releasing database connections or closing open files.

The jspDestroy() method has the following form:

public void jspDestroy(){ // Your cleanup code goes here.}

JSP Expressions:A JSP expression is used to insert values directly into the output. It has the followingform:<%= Java Expression %>The expression is evaluated, converted to a string, and inserted in the page. Thisevaluation is performed at runtime (when the page is requested) and thus has full

Page 6: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

access to information about the request. For example, the following shows thedate/time that the page was requested.Current time: <%= new java.util.Date() %>Predefined VariablesTo simplify these expressions, you can use a number of predefined variables (or“implicit objects”). There is nothing magic about these variables; the system simplytells you what names it will use for the local variables in _jspService (the methodthat replaces doGet in servlets that result from JSP pages). These implicit objectsare discussed in more detail in Section 11.12, but for the purpose of expressions, themost important ones are these:• request, the HttpServletRequest.• response, the HttpServletResponse.• session, the HttpSession associated with the request (unlessdisabled with the session attribute of the page directive—seeSection 12.4).• out, the Writer (a buffered version of type JspWriter) used tosend output to the client.• application, the ServletContext. This is a data structureshared by all servlets and JSP pages in the Web application and is goodfor storing shared data.XML Syntax for ExpressionsXML authors can use the following alternative syntax for JSP expressions:<jsp:expression>Java Expression</jsp:expression>In JSP 1.2 and later, servers are required to support this syntax as long as authorsdon’t mix the XML version and the standard JSP version (<%= ... %>) in the samepage. This means that, to use the XML version, you must use XML syntax in the entirepage. In JSP 1.2 (but not 2.0), this requirement means that you have to enclose theentire page in a jsp:root element. As a result, most developers stick with the classicsyntax except when they are either generating XML documents (e.g., xhtml or SOAP)or when the JSP page is itself the output of some XML process (e.g., XSLT).Note that XML elements, unlike HTML ones, are case sensitive. So, be sure touse jsp:expression in lower case.

Example: JSP Expressions

Expressions.jsp

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE>JSP Expressions</TITLE><META NAME="keywords"CONTENT="JSP,expressions,JavaServer Pages,servlets"><META NAME="description"CONTENT="A quick example of JSP expressions.">

<LINK REL=STYLESHEET

Page 7: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

HREF="JSP-Styles.css"TYPE="text/css"></HEAD><BODY><H2>JSP Expressions</H2><UL><LI>Current time: <%= new java.util.Date() %><LI>Server: <%= application.getServerInfo() %><LI>Session ID: <%= session.getId() %><LI>The <CODE>testParam</CODE> form parameter:<%= request.getParameter("testParam") %></UL></BODY></HTML>

Tag Extensions:

INTRODUCTION TO JSP TAGS

In this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags can be devided into 4 different types. These are:  

1. DirectivesIn the directives we can import packages, define error handling pages or the session information of the JSP page.  

Page 8: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

2. DeclarationsThis tag is used for defining the functions and variables to be used in the JSP. 

3. ScripletsIn this tag we can insert any amount of valid java code and these codes are placed in _jspServicemethod by the JSP engine. 

4. ExpressionsWe can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream. 

Now we will examine each tags in details with examples. DIRECTIVES

Syntax of JSP directives is:

<%@directive attribute="value" %>

Where directive may be:

1. page: page is used to provide the information about it.Example: <%@page language="java" %>  

2. include: include is used to include a file in the JSP page.Example: <%@ include file="/header.jsp" %>   

3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags).Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>  

and attribute may be:

1. language="java"This tells the server that the page is using the java language. Current JSP specification supports only java language.

Page 9: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

Example: <%@page language="java" %>  

2. extends="mypackage.myclass"This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages.Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %>  

3. session="true"When this value is true session data is available to the JSP page otherwise not. By default this value is true.Example: <%@page language="java" session="true" %>   

4. errorPage="error.jsp"errorPage is used to handle the un-handled exceptions in the page.Example: <%@page language="java" session="true" errorPage="error.jsp"  %>  

5. contentType="text/html;charset=ISO-8859-1"Use this attribute to set the mime type and character set of the JSP.Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1"  %>   

JSP - Standard Tag Library (JSTL)

The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications.

JSTL has support for common, structural tasks such as iteration and conditionals, tags for manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework for integrating existing custom tags with JSTL tags.

The JSTL tags can be classified, according to their functions, into following JSTL tag library groups that can be used when creating a JSP page:

Core Tags Formatting tags SQL tags

Page 10: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

XML tags JSTL Functions

Install JSTL Library:

If you are using Apache Tomcat container then follow the following two simple steps:

Download the binary distribution from Apache Standard Taglib and unpack the compressed file. To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR files in the

distribution's 'lib' directory to your application's webapps\ROOT\WEB-INF\lib directory.

To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses the library.

Core Tags:

The core group of tags are the most frequently used JSTL tags. Following is the syntax to include JSTL Core library in your JSP:

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

There are following Core JSTL Tags:

Tag Description

<c:out > Like <%= ... >, but for expressions.

<c:set > Sets the result of an expression evaluation in a 'scope'

<c:remove >Removes a scoped variable (from a particular scope, if specified).

<c:catch>Catches any Throwable that occurs in its body and optionally exposes it.

<c:if>Simple conditional tag which evalutes its body if the supplied condition is true.

<c:choose>Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>

Page 11: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<c:when>Subtag of <choose> that includes its body if its condition evalutes to 'true'.

<c:otherwise >Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'.

<c:import>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 >The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality .

<c:forTokens> Iterates over tokens, separated by the supplied delimeters.

<c:param> Adds a parameter to a containing 'import' tag's URL.

<c:redirect > Redirects to a new URL.

<c:url> 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 Web sites. Following is the syntax to include Formatting library in your JSP:

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

Following is the list of Formatting JSTL Tags:

Tag Description

<fmt:formatNumber> To render numerical value with specific precision or format.

<fmt:parseNumber>Parses the string representation of a number, currency, or percentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles and

Page 12: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

pattern

<fmt:parseDate> Parses the string representation of a date and/or time

<fmt:bundle> Loads a resource bundle to be used by its tag body.

<fmt:setLocale> Stores the given locale in the locale configuration variable.

<fmt:setBundle>Loads a resource bundle and stores it in the named scoped variable or the bundle configuration variable.

<fmt:timeZone>Specifies the time zone for any time formatting or parsing actions nested in its body.

<fmt:setTimeZone>Stores the given time zone in the time zone configuration variable

<fmt:message> To display an internationalized message.

<fmt:requestEncoding> 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 is the list of SQL JSTL Tags:

Tag Description

<sql:setDataSource> Creates a simple DataSource suitable only for prototyping

<sql:query>Executes the SQL query defined in its body or through the sql attribute.

Page 13: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<sql:update>Executes the SQL update defined in its body or through the sql attribute.

<sql:param> Sets a parameter in an SQL statement to the specified value.

<sql:dateParam>Sets a parameter in an SQL statement to the specified java.util.Date value.

<sql:transaction >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 XML documents. Following is the syntax to include JSTL XML library in your JSP.

The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing XML, transforming XML data, and flow control based on XPath expressions.

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

Before you proceed with the examples, you would need to copy following two XML and XPath related libraries into your <Tomcat Installation Directory>\lib:

XercesImpl.jar: Download it from http://www.apache.org/dist/xerces/j/ xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html

Following is the list of XML JSTL Tags:

Tag Description

<x:out> Like <%= ... >, but for XPath expressions.

<x:parse>Use to parse XML data specified either via an attribute or in the tag body.

<x:set > Sets a variable to the value of an XPath expression.

<x:if > Evaluates a test XPath expression and if it is true, it

Page 14: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

processes its body. If the test condition is false, the body is ignored.

<x:forEach> To loop over nodes in an XML document.

<x:choose>Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise>

<x:when >Subtag of <choose> that includes its body if its expression evalutes to 'true'

<x:otherwise >Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'

<x:transform > Applies an XSL transformation on a XML document

<x:param >Use 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 is the list of JSTL Functions:

Function Description

fn:contains() Tests if an input string contains the specified substring.

fn:containsIgnoreCase()Tests if an input string contains the specified substring in a case insensitive way.

fn:endsWith() Tests if an input string ends with the specified suffix.

Page 15: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

fn:escapeXml()Escapes characters that could be interpreted as XML markup.

fn:indexOf()Returns the index withing a string of the first occurrence of a specified substring.

fn:join() Joins all elements of an array into a string.

fn:length()Returns the number of items in a collection, or the number of characters in a string.

fn:replace()Returns a string resulting from replacing in an input string all occurrences with a given string.

fn:split() Splits a string into an array of substrings.

fn:startsWith() Tests if an input string starts with the specified prefix.

fn:substring() Returns a subset of a string.

fn:substringAfter() Returns a subset of a string following a specific substring.

fn:substringBefore() Returns a subset of a string before a specific substring.

fn:toLowerCase() Converts all of the characters of a string to lower case.

fn:toUpperCase() Converts all of the characters of a string to upper case.

fn:trim() Removes white spaces from both ends of a string.

A MORE DETAILED AND EXAMPLE IN JSTL:

As J2EE programmers, we are familiar with Servlets , JSP   and JavaBeans.  Any JSP page should encapsulate the business logic in a bean and invoke it by using<jsp:useBean>  tag.  Till recently, a combination of Servlets, JSP and beans was the standard practice. But, the JCP

Page 16: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

released an API for enabling programmers to create custom tags and use them in their JSP pages. The difference between javabean and java custom tags was that, though both made use of java classes,  tags can be used by non-programmers also without  knowledge of Java programming, just as they would use html tags.( From a programmer's perspective,however, a much more important distinction is that tags are specific to the page in which they are created while javabeans are general. )

{{{  Back in  1998, a Web-Server Technology , known as ColdFusion , created by Allaire of Allaire Corporation, was very much in demand!. It was a purely tag-basedlanguage, using which page-authors can turn into programmers overnight. The tags were so powerful and simple to use! There is a separate lesson on using ColdFusion for typical web-based database operations, elsewhere in this edition, just to indicate the source of inspiration of the tag library idea, of the JSTL. To this day, ColdFusion is unbeatable, in its power,speed, ease of use and productivity. However, among the various web-server technologies ( namely

ASP, Servlets, JSP,Perl,PHP , ColdFusion &

ASP.net), CF is the only technology that is not free!And perhaps for this reason, it is no longer popular in Indian environment, though it is said to be very much in vogue still, in US!

MacroMedia of 'Flash fame' purchased ColdFusion .There was even a tutorial on MacroMedia ColdFusion Exprsess in DeveloperIQ., a few months back.It is interesting to make a comparison of the CF tags approach and the JSTL approach., especially , in DataBase operations.Readers are requested to read the lesson on ColdFusion,in this edition, after covering sql tags in JSTL , in the fourth part of this tutorial..}}}

   To resume,the release of the TagLibrary API, triggered   a lot of   activity and hundreds of tags were introduced by the java community, some of them 'open' and a few 'proprietary'.  This led to a lot of confusion in code maintenance, because knowledge of Java was no longer sufficient to understand and interpret a given jsp page using non-standard tags .The JCP had unwittingly   introduced elements of confusion by the JSP-Custom-Tag specification.

   To correct this problem, Sun and JCP, initiated   the JSP-Standard Tag Library(JSTL) project.  Though there are a number of popular and powerful tag-libraries, it is always better for j2ee coders to  adopt the JCP standard because, it is likely to be merged into the core specification of Java langauage itself , in future. (That yardstick may be valid for all creations, in Java world. Splintering of the Java platform due to' hyper-active creativity'  without the

Page 17: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

corresponding discipline to get it through a standards body ,is the greatest threat, looming large in the Java-horizon.

Too frequent revisions and additions, that too without caring for backward compatibility,are not conducive to programmer productivity  and the net result is that programmers spend ,in learning new twists in grammar,  their  precious time  which should have been spent more usefully in applying that grammar in solving business-logic problems and acquiring proficiency in the chosen application-domain. While, tag library is sometimes very elegant and simple to use, it defeats the very purpose if the tags  are not standard tags and if there is proliferation of non-standard tags.It is for this reason that JSTL merits our serious study and adoption.

JSTL is a quite recent  development. It was only in 2003, that the official version 1.1 was released and now incorporated into  JSP-2.

   According to the latest position, the JCP is suggesting that a JSP page should be completely free from any trace of Java code!  So, programmers who were writing their JSP using Javabeans and scriptlets , may not be able to carry on in their old style as, to prevent programmers from introducing scripting sections in their pages, there is a provision  for turning off scriptlets altogether from a jsp page. If that happens ,all our knowledge of Java coding will be of little use in creating a jsp page, though such knowledge may be useful in creating beans and other types of java programs.

  It is thus very important for  J2EE students, to understand the trend and get to know the techniques, advantages and limitations of  tag libraries...In a way, a study of JSTL is almost synonymous  with a study of the latest version of JSP (ie) JSP2.0 .

---------------------------------------

  Without an introductory demo for each of these types, it may be difficult to appreciate the significance of the above lines. So we will now give simplest illustration.

==============================================

[It is presumed that readers are conversant with basic Servlets & JSP techniques and executing them in Tomcat environment. In case of any difficulty, they can refer to back issues of this magazine ( from Oct-2003  onwards) and gain access to a number of lessons for illustrations.]

Page 18: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

Servlets are full-fledged java-classes and so are very powerful. But, when we want to create a dynamicalay-generated web-page using servlets, it becomes difficult and clumsy.Let us consider a very simple example.

The user fills up text in html form with his name and submits the form,to the servlet. The servlet reads the data , appends a greeting and sends it back to the user.

   How exactly we should proceed to  instal   JSTL, we will take up shortly. For the moment, we are just getting familiar with the required syntax.   We begin with taglibdirective.

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

The directive says that we are using 'core' tags and the prefix will be 'c'.  If we want to assign the value 'sam' to a variable 'a' and then print it, the JSTL code will be

 <c:set  var="a"   value="sam" />

 <c:out   value="${a}"   />

-----------------------------------

The Dollar sign  & brace will be familiar ground for Perl programmers.   In JSTL & JSP-2, it is  known as EL ( Expression Language).

==============================================

To consider another example,  In servlet & jsp, we write:

 String s = request.getParameter("text1");

to collect the input from the user.

The same job is done in  JSTL   by: <c:set  var="s" value="${param.text1}" >

==================================

 With these brief hints, it should not be difficult to understand the

Page 19: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

following   JSP  page written  by   using JSTL core-tags.

-----------------------------------------------

//   greeting4.jsp   (  uses  JSTL)

===========

<%@  taglib   prefix="c" uri="http://java.sun.com/jstl/core"  %> <html>  <body>  <c:set var=s  value="${param.text1}" />  We welcome<br>  <c:out  value="${s}" />  </body>  </html>

-----------------------------------------------

In the previous  examples, there was java code in a few lines atleast. But, in the  JSTL example, we find that there are only tags and no java  scriptlets. This is the avowed objective of the JSTL  initiative,

under the auspices of Java Community Project! Why?   This enables , clean separation of  Page author's role and Logic programmers' role. Thus maintenance becomes easy.

===============================================

  There are five groups under which the JSTL tags have been organized.

   They are as follows:

  1)   core

  2)   xml

  3)   sql

  4)   formatting

Page 20: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

  5)   functions.

-----------------------------------------------   The most difficult part is  to set up Tomcat  so that it executes JSTL.   There are some basic requirements, before we can experiment and study the use of JSTL.All that we have studied in using Tomcat for servlets and JSP may not be sufficient to learn JSTL, because, jstl library is not built into Tomcat5  even, as yet.

  Without hands-on experimention, JSTL could be confusing and strange,because of the   fact that it is very  recent  . But in coming months, support will be built into Tomcat and we won't have to worry about installing the JSTL  libraries inside Tomcat. But, as it is, we have to learn how to set up the necessary development environment..

   So , how do we go about , placing the JSTL libraries in tomcat?

------------------------------------------------   The best solution is to get JWSDP1.3.

   This is Java Web Service Development' Pack.

( Carefully note the version , however!).

   It is good to start with this because, it contains a lot of valuable software , including the latest and greatest from  JCP, (ie) JSF

(Java Server Faces).... which may soon replace Struts. We unzip   the jwsdp1.3  and install   it in C: drive. There   are  a number of folders like JAXP, JAXR, JAXB,JAX-RPC, JSF, JSTL etc. in the JWSDP pack.

 For the present, we are interested in JSTL folder only. If we expand the JSTL folder, we find  four   sub folders :

   a)  docs

   b)  lib

   c)  samples

   d)  tld  (  tag library descriptors)

   When we look into the 'lib' folder, we find  two jar files:

Page 21: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

  a)  standard.jar

  b)   jstl.jar

We should copy  these two jar files into  :

 'e:\tomcat5\webapps\root\WEB-INF\lib'

-----------------------------------------------

( Remember to restart the Tomcat server). That is all that is required to use   JSTL. !  

The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These files are already  included in the /META-INF folder of the jstl.jar and so will be automatically loaded by Tomcat, when it is restarted.

***********************************************

 ( we are using tomcat5 & jdk1.4.2)

 ( the results are not  ensured   for other environments.).( however, we adopted the same method in Tomcat4.1 with jdk1.41 and got correct functioning.)

===============================================

  The JSTL  folder contains a sub-folder named 'tld'.  There will be a number of tld files there such as

c.tld,  ( core)

x.tld,  (xml)

fmt.tld,  (format)

sql.tld &  (sql)

fn.tld.  (functions)

------------------------------

Page 22: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

Some authors say that we should copy these tld files  to ..

..:\tomcat5\webapps\root\WEB-INF   folder.

 A few others , say that there is automatic detection and so it is  not necessary. We chose not to copy the tld files into

e:\tomcat5\webapps\root\WEB-INF   folder !

We found that the programs works well. No problem!  

When we study the web.xml file in e:\tomcat\webapps\root\WEB-INF   folder, we find that it follows  DTD and not Schema.

( DTD  stands for Document -Type- Definition).

( Schema  serves the same purpose but is in XML format and is more powerful). ( The default is DTD ).

   This point is very important. The default allows us to use EL,(Expression Language) but by using <c:out   value="${s}" syntax.

If we modify the DTD into the prescribed J2EE schema , we can directly print as   ${s}.This requires very careful handling and we take it up later.

   For the present , let us not tamper with the DTD. or the web.xml file.

In the next part of this tutorial, we study the tags available in the JSTL-core library.

JSTL Core Tags

The JSTL encapsulates the core functionality which is common to many web applications. The JSTL provides a single set of tags instead of mixing many set of tags. The JSTL have tags for loop statement, If Else statement etc. It removes the burden of writing long java codes. Please go through the tutorial of JSTL given below.

In the second part of this tutorial on JSTL, the author explains how the tags in the core-group can be used in JSP pages, with a number of simple examples.

Page 23: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

We are now ready to experiment with all the tags in the 'core' library. The core tags have the following uniform 'uri'.

'http://java.sun.com/jstl/core'.)

The prefix is  ?c:? 

The following tags are available in the ?core? library.

( Remember them as a dozen!).

   <c:set   <c:out   <c:if  test= ?     <c:choose  ,   <c:when ,  <c:otherwise   <c:forEach   <c:forTokens   <c:import   <c:url   <c:redirect   <c:param

-----------------------------------------------

We will now see simplest illustrations for the above tags.There are a dozen demos, to bring out the features of each of these tags.

---------------------------------------  

demo1.jsp  uses   <c:set &  <c:out  tags.

:We create demo1.jsp  as:

e:\tomcat5\webapps\root\demo1.jsp

-----------------------------------------

//   demo1.jsp

Page 24: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<%@ page contentType="text/html" %><%@ taglib  prefix="c"  uri="http://java.sun.com/jstl/core"  %><html><body   bgcolor=lightblue> <form   method=post  action="demo1.jsp"> NAME <input  type=text  name="text1"><br> PLACE<input  type=text  name="text2"><br>     <input type=submit> </form>

 NAME:<c:out  value="${param.text1}"  /><br> PLACE:<c:out   value="${param.text2}"  /></body></html>----------------------------------------------

In all the previous examples, we invoked the JSP file through a html  file. But, in demo1.jsp, we are  posting the page to itself.( in asp.net style!).( but there is no 'retention of data' , unlike asp.net).

We start Tomcat5, and type the url as :

 ?http://localhost:8080/demo1.jsp?.  in the browser.We get a form with two text boxes and a submit button. We fill up the textboxes with ?name? and ?place? and submit.

The demo1.jsp executes and displays the  values entered by the user.due to the JSTL tags

<c:out   value=?${param.text1}   />  etc.

That is about our first and introductory example.

----------- ---

   The second example is very important. When the user enters data in a number of fields, it is tedious to collect the data and transfer it to jsp page for processing. In our example, we are collecting data about a player,  such as his name, place and game. We can have much more but we are restricting for space considerations. JSP has an action tag , known as 'jsp:setProperty'.

Page 25: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

Using this along with a standard javabean, we can extract data and transfer it to our program in a single step.

The syntax is

<jsp:useBean   id="bean1"  class="ourbeans.player"  > <jsp:setProperty    name="bean1"   property="*"   /></jsp:useBean>

:( the * sign denotes 'all').

-----

   But, we should first create the 'player ' bean with all the attributes and getter & setter methods, as shown.

---------------------------------------------

//  player.javapackage ourbeans;public class player{ String   name; String   place; String   game; public player(){  name="  ";  place=" ";  game=" ";   }//---------------------------

 public void setName(String a){   name=a; }

Page 26: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

 public void setPlace(String b){   place=b; }

 public void setGame(String c){  game=c;  }//------------------------------

 public String   getName(){   return  name; }

 public String  getPlace(){   return  place; }

 public String  getGame(){   return  game; }

}

---------------------------------

   In demo2.jsp, we collect the data and then display  the data entered by the user.

Note that instead of {param.text1}, we are using {bean1.name}. We should carefully name the html form controls with the corresponding attribute names given in the bean. We cannot name the controls as 'text1' etc, now!

<c:out   value="${bean1.name}"   /><c:out   value="${bean1.place}"  /><c:out   value="${bean1.game}"   />

---

 We get correct result.

Page 27: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

=============================================

//   demo2.jsp

<%@ page contentType="text/html" %><%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"  %>

<html><body><form method=post action="demo2.jsp"><jsp:useBean id="bean1" class="ourbeans.player"><jsp:setProperty name="bean1" property="*"   /></jsp:useBean>Name <input   type=text   name="name"><br> Place<input  type=text  name="place"><br> Game<input   type=text   name="game"><br> <input type=submit> </form>

Name: <c:out value="${bean1.name}"  /><br> Place: <c:out value="${bean1.place}"  /><br> Game: <c:out value="${bean1.game}"  /> </body>  </html>

=============================================

Once again, it will be noticed that there is no java code in this example, as everything is being done by tags, only..

***********************************************

We are now ready to take up examples for 'condition'  tags.

  There are two types of 'condition tags'.

namely, <c:if>   &  <c:choose>.

Page 28: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

In the third demo, we learn how to use the <c:if  tag.

----------------------------------------------

//demo3.jsp <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <html>  <body  bgcolor=lightblue>  <form   method=post   action=demo3.jsp>    <select  name="combo1">   <option   value="sam">sam   <option  value="tom">tom    </select> <input   type=submit> </form> <c:set   var="s"   value="${param.combo1}"  /> <c:out value="${s}"  /> <br> 

<c:if  test="${s  eq   'sam'  }"   >    <c:out   value="Good Morning...SAM!"  /> </c:if>

<c:if   test="${s   = =   'tom'}"  >    <c:out  value=" How Are You?....TOM!"  />  </c:if> </body>  </html>  

-----------------------------------------

There is a combo with two options, namely

'sam' and 'tom'. If the user selects 'sam' and submits the form, he gets 'GoodMorning ...SAM!". If he selects 'tom' instead, he gets

Page 29: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

'How are you..TOM?'.  

  The above code is no ?Rocket-Science? as American  authors say!But , if we are careless  in typing the names ?sam? or ?tom? in the test condition, we could spend hours together , trying to coax this code into functioning! We should not leave space after the single quote  in the 'test expression'. Second point worth noting in the above example is that we can use either == ( double equal to) or eq  to test equality.

***********************************************

In the fourth example which follows, we take up <c:choose> tag.

The syntax is:

<c:choose >    <c:when   test="   "   >   <c:otherwise>  something  </c:otherwise> </c:choose>

The peculiarity to be noted here is that   unlike <c:if , where we had to explicitly  use <c:out for printing , no such <c:out has been used here., and yet the result is displayed,

because 'choose' includes 'displaying'..

When we choose '7', "select between 1 & 5 " will be displayed!

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

Example

<html> <body  bgcolor=lightblue>   <form   method=post  action="demo3.jsp">   <select name="combo1">    <option value="1">1   </option>    <option value="2">2   </option>    <option value="3">3   </option> 

Page 30: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<  option value="4">4  </option>

</option>    <option value="5">5   </option>    <option value="7">7   </option>   </select>

  <input  type=submit>   <c:set var="s"   value="${param.combo1}"  />   Today is    <br>

<font size=24 color=red>

<c:choose>   <c:when  test="${s==1}">Sunday   </c:when>   <c:when  test="${s==2}">Monday</c:when>   <c:when  test="${s==3}">Tuesday</c:when>   <c:when  test="${s==4}">Wednesday</c:when>   <c:when  test="${s==5}">Thursday</c:when>

 <c:otherwise>   select between 1 & 5      </c:otherwise> </c:choose>  </body>  </html>  

---------------------------------------------

Demo-5  deals with Iteration tag. We are familiar with the 'for-each' construct. JSTL's 'for-each'  also has the same functionality.   In the following example, we have a String array.  named as 'colors'.   By using the <c:forEach> tag, we iterate through the array and display the values.

------------------------------------

//demo5.jsp <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <% pageContext.setAttribute("colors",  new String[]  {"red","green","blue","orange","black"} );  %>

<table> <c:forEach  var="n"  items="${colors}" 

Page 31: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

   varStatus="a"> <tr> <td>   <c:out value="${a.index}"   /> </td> <td>   <c:out value="${a.count}"   /> </td> <td>  <c:out value="${a.first}"   /> </td> <td>  <c:out value="${a.last}"  /> </td> <td>   <c:out value="${a.current}" /> </td> <tr> </c:forEach> </table>

We get the following display, when we execute the program.  

0 1 true false red1 2 false false green2 3 false false blue3 4 false false purple4 5 false true black

===============================================

<c:forEach> action tag contain the following attribute list:

items  :  the collection of items like String[]

var    :  a symbolic name for the collection

begin  :  the starting index of iteration

end  :  the ending index of iteration

step   :  incremental step

varStatus: symbolic name for current status.

If we assign the symbolic name 'a' for the status, we are able to access its properties such as index, count, whether it is first item,

whether it is last item and the current value.

Demo6 also deals with iteration tag.In the following example, the iteration starts at value 3 and ends at value 8 .It displays the values of n in each iteration.Each iteration increments the value of n automatically by 1,if step   is  not specified.

-----------------------------------------------

demo6.jsp

Page 32: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:forEach  var="n"  begin="3"  end="8" >   <c:out  value="${n}"  />   <br>  </c:forEach>

3 4 5 6 7 8

===============================================

Demo7 deals with JSTL's 'forTokens' tag.<c:forTokens>, which iterates over a string of tokens separated by a set of delimiters like the stringTokenizer class in Java.

--------------------------------------------

demo7.jsp <%@ page contentType="text/html" %>  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>    <c:set var="s" value="SAM,DELHI,MCA,24,90"  /> <html> <body>    <table border="1">    <tr>    <th>Name</th>    <th>Place</th>    <th>Degree</th>    <th>Age</th>    <th>Mark</th>    </tr>    <tr> <c:forTokens   items="${s}"    delims=","   var="token"  >    <td><c:out value="${token}"  /></td> </c:forTokens>   </tr>   </table>   <br>   </font>   </body>   </html> ------------------------------------------

Name Place Degree Age Markkala Kkdi mca 23 87

Page 33: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

------------------------------------------

The essential attributes of 'forTokens' tag are:

Attribute  Description

items      The string to tokenize

delims     The delimiter characters         that separate the tokens of   the string.

===============================================

Demo8 deals with URL-Related actions.<c:import>action tag imports the conent of a URL-based resource and provides a simple way to access URL-based resources that can either be included or processed within the JSP..  In the following example,the import action tag imports the content of welcome.htm file here.So it displays the contents of demo8.jsp and welcome.htm.

--------------------------------------------

// welcome.htm <html> <body> WELCOME <br> </body> </html> ---------  

demo8.jsp <%@ taglib  prefix="c"  uri="http://java.sun.com/jstl/core" %> <c:import url="welcome.htm"/> <c:out   value="to our web-site!" /> ===============================================

In demo9 we discuss the <c:url> action tag.

<c:url> prints the value  of URL.It is easier to construct the hyperlinks.It is useful for session preservation (URL-Encoding).

In the following example,we use <c:url> to make a link to another html file. When we execute demo9, we get a link , with text 'send'.

When we click on the link, we are taken to welcome.htm.

Page 34: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

--------------------------------------

demo9.jsp

<%@ taglib  prefix="c" uri="http://java.sun.com/jstl/core" %>  <a   href="<c:url  value="http://localhost:8080/welcome.htm/>">  send  </a>

--------------------------------------

===============================================

demo10 deals with <c:redirect> action tag.

This tag forwards the browser to the specified URL .

demo10.jsp

<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:redirect url="http://localhost:8080/welcome.htm  />

===============================================

Finally, <c:param> tag is useful to send some parameter value to the page to which redirect occurs. In our example, the code redirects to sample.jsp, but it takes the param named 'a'

with value='SAM' , to the redirected page. And, the sample.jsp accepts this param and prints it. <c:out value="${param.name1}"/>

----------------------------------------------

demo11.jsp

<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:redirect  url="http://localhost:8080/jstldemos/   core/sample.jsp" > <c:param name="name1" value="SAM"/> </c:redirect> -------------------------------------------

( in a different file) sample.jsp 

Page 35: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %><c:out value="${param.name1}"/>

And to end our whirlwind tour of core-tags in JSTL, here is a demo which mixes EL of JSP-2(Expression Language of JSTL) with 'Expression' (also known as request-time Expression ) of JSP1.2.

 

demo12.jsp

<%@ page contentType="text/html" %>  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>  JSTL  welcomes <br>  <c:out   value="${param.text1}"   />  <br>  JSP Expression welcomes  <%=request.getParameter("text1") %>

JSTL XML Tags

No one can have any second opinion about the elegance of xml tags in JSTL.If the readers have been following the earlier instalments of this J2EE series of tutorials, they would have come across JAXP,DOM,SAX ,JDOM and such terms, and it may have been none too easy to learn. But the xml tags in JSTL , make XML processing and even Transformation , a cynch! And ,we now proceed to study them.

Making our study even easier, many of the xml tags in JSTL , are very much similar to the 'core' tags. For example, just like

<c:out>, we have <x:out>.

Similarly,

<x:forEach>, <x:if>,<x:when> etc.

No one can  have any second opinion about the elegance of xml tags in JSTL.If the readers have been following the earlier instalments of this J2EE series of tutorials, they would have come across JAXP,DOM,SAX ,JDOM and such terms, and it may  have been none too easy to learn. But the xml tags in JSTL , make XML processing and even Transformation , a cynch! And ,we now proceed to study them.

Page 36: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

Making our study  even easier, many of the xml tags in JSTL , are very much similar to the 'core' tags. For example, just like

<c:out>, we have <x:out>.

Similarly,

<x:forEach>, <x:if>,<x:when>  etc.

So, if we have understood the syntax of the 'core'; tags, it will not be difficult to use the 'xml' tags.

All the following  examples use the books.xml file.It contains 'elements' like 'title' and 'author'..

books.xml

<?xml version="1.0" ?><books>     <book>    <title>cobol</title>    <author>roy</author>   </book>   <book>    <title>java</title>    <author>herbert</author>   </book>   <book>    <title>c++</title>    <author>robert</author>   </book>   <book>    <title>coldfusion</title>    <author>allaire</author>   </book>   <book>    <title>xml unleashed</title>    <author>morrison</author> 

Page 37: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

  </book>   <book>    <title>jrun</title>    <author>allaire</author>   </book> </books> 

-----------------------------------------------  

demo1

The following program reads the xml file using 'forEach' tag and displays the title and author of   each book..

The syntax:

  <x:forEach   var="n" 

   select="$doc/books/book">

is used to select the elements from the xml file.

  <x:out   select="$n/title"  />

is used to print the elements of the xml file. We begin by  importing the reference to the XML file to be parsed.

<c:import   url="books.xml"  var="url" />

-----

 We have given a symbolic name for this file as 'url'.Next we ask  the program to parse this XML file.The resulting tree is given a symbolic name as 'doc'.

<x:parse   xml="${url}"   var="doc"   />

In the next step, we direct the program to select each title and each author in the XPATH expression $doc/books/book. If we refer to the xml file , we find that the root element of the

Page 38: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

document is 'books'. Inside this, we have 'book'.So, XPATH can be thought of as just a file hierarchy. Just like <c:out, we have <x:out!

demo1.jsp

<%@ page contentType="text/html" %>  <%@   taglib  prefix="c" uri="http://java.sun.com/jstl/core" %> <%@   taglib  prefix="c" >uri="http://java.sun.com/jstl/xml"   %>  

<html>  <body>   <c:import   url="books.xml"  var="url" />   <x:parse   xml="${url}"   var="doc"   />

 -----------------------------------------------<br>

 <x:forEach   var="n"    select="$doc/books/book">  <x:out   select="$n/title"  />  <br>   <x:out   select="$n/author"  />    <br>

 ========   <br>   </x:forEach> </body> </html>

  Magically, we have parsed a given XML document and extracted information, without any mention about DOM,SAX and such  words., atall!Wonderful!As a famous author would say, 'anything that makes my job easier, I like!'.

 When we execute  the 'program', we get the following result.

-------------------------------------------

(Result for executing demo1.jsp)

Page 39: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

==========================

cobolroy==========javaherbert==========c++robert==========coldfusionallaire==========xml unleashedmorrison==========jrunallaire==========

***********************************************

The following program (demo2)displays the books and authors of xml file  in table format.  

demo2.jsp

<%@ page contentType="text/html" %>  <%@   taglib   prefix="c" uri="http://java.sun.com/jstl/core" %> <%@   taglib  prefix="c" >uri="http://java.sun.com/jstl/xml"   %>  

<html>  <body>   <c:import   url="books.xml"  var="url" />   <x:parse   xml="${url}"   var="doc" />   <table  border=1>   <th> 

Page 40: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

  <tr>    <td>title</td>    <td>author</td>   </tr>    </th>

 <x:forEach   var="n"    select="$doc/books/book">    <td>   <tr> <x:out   select="$n/title"  /></tr>   <tr> <x:out   select="$n/author"  /></tr>   </td>  </x:forEach> </table>  </body>  </html>

title authorcobol royjava herbertc++ robertcoldfusion allairexml unleashed morrisonjrun allaire

------------------------------------------------

demo3 deals with the selection of particular book's author  from the xml file ,when we give the title, with the help of <x:if> action tag.The title is choosen from combo box indemo2.htm file and submitted.We get a display of the selected title and its author.

 Think of this as an sql query like

"select * from table1 where title='jrun'"

--------------------------------------------------

Page 41: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

demo3.htm

<html>  <body>    SELECT THE TITLE.<BR>   YOU WILL GET  TITLE & AUTHOR.  <form   method=post  action="demo3.jsp">  

<select name="combo1">   <option value="xml unleashed">xml   <option value="c++">c++     <option value="coldfusion">cold fusion   <option value="java">java   <option  value="cobol">cobol </select> <input type=submit> </form> </body> </html>

--------------------------

demo3.jsp  

<%@ page contentType="text/html" %>  <%@   taglib   prefix="c" uri="http://java.sun.com/jstl/core"  %>  <%@   taglib  prefix="c" uri="http://java.sun.com/jstl/xml" %>  

<html>  <body>   <c:import   url="books.xml"  var="url" />   <x:parse  xml="${url}"   var="doc"   />  <c:set  var="s" value="${param.combo1}"/>

------

Page 42: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<x:forEach  var="n" select="$doc/books/book" > <x:if  select="$n/title=$s" > <x:out   select="$n/title"  /> <br> <x:out   select="$n/author"  /> <br>  </x:if> </x:forEach> </body> </html>

demo4  is a simple variation on the same theme. In this case, the user selects the author name from the combo and any books by that author are displayed, due to the code.

 It will be noted that 'allaire' has two books to his credit and so if we choose 'allaire' in the combo,his two books are displayed.If 'haris' is chosen, we should display the message that it is yet to be published as there is no such entry in the xml file. But there is no 'if-else' construct and so we improvise.

We have created a variable 'a' and assigned the value 'ok' to it. If there is no author to match the user's selection, the conditional block is ignored and  'a' will not be 'ok'.

 w">From this, we conclude that 'the book is not ready'.

----------------------------------

demo4.htm

<html>  <body>  Select name of author & view his books<br>  <form method=post action="demo4.jsp">  <select name="combo1">   <option value="morrison">morrison   <option value="robert">robert   <option value="allaire">allaire   <option value="herbert">herbert   <option value="roy">roy   <option   value="haris">haris  </select>  <input type=submit>  </form>  

Page 43: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

</body>  </html>

==============

demo4.jsp

========

<%@ page contentType="text/html" %>  <%@   taglib   prefix="c" uri="http://java.sun.com/jstl/core"  %>  <%@   taglib  prefix="c" uri="http://java.sun.com/jstl/xml" %>  

<html>  <body>    <c:import  url="books.xml"  var="url" />  <x:parse   xml="${url}"     var="doc" />  <c:set   var="s"  value="${param.combo1}"/> <x:forEach  var="n" select="$doc/books/book" >

<x:if   select="$n/author=$s" > <c:set  var="a"   value="ok"  />  <x:out   select="$n/title"  />  <br>  <x:out   select="$n/author"  />  <br> </x:if> </x:forEach>

<c:if  test="${a!='ok'}"  />    <c:out   value="not yet ready!"  /> </c:if> </body>  </html>

===============================================

In demo5 also, we display the title & author for a   given title, but we now use <x:choose, <x:when logic. This is similar to <c:choose, <c:when & <c:otherwise logic in the core library.

----------------------------------------------

demo5.htm  <html>  <body> 

Page 44: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

   SELECT THE TITLE.<BR>   YOU WILL GET  TITLE & AUTHOR.  <form   method=post  action="demo5.jsp">

<select name="combo1">   <option value="xml unleashed">xml   <option value="c++">c++     <option value="coldfusion">cold fusion   <option value="java">java   <option  value="cobol">cobol </select> <input type=submit> </form> </body> </html>

-----------

demo5.jsp

<%@ page contentType="text/html" %> <%@   taglib   prefix="c" uri="http://java.sun.com/jstl/core"  %> <%@   taglib   prefix="c" uri="http://java.sun.com/jstl/xml"  %>

<html> <body>  <c:import   url="books.xml"  var="url" />  <c:set var="s" value="${param.combo1}" />  <x:parse   xml="${url}"   var="doc"  />  <x:forEach var="n" select="$doc/books/book">  <x:choose>  <x:when select="$n/title=$s"> <c:set var="m"  value="ok" />  <x:out select="$n/title" />  </x:when>  <x:otherwise> </x:otherwise> </x:choose></x:forEach> <c:if  test="${m!='ok'}">   <c:out  value="no such book"/>   </c:if>  </body> </html>

Page 45: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

Result --------------------title sent from user:c++--------------------c++robert

========================-title sent from user:VB--------------------no such records

***************************************

In demo6 , we see XSLtransform using JSTL. ( as promised in the earlier tutorial on XSLT in October issue).For the sake of continuity with the earlier tutorial,we revert back to students.xml and xsl1.xsl, as given in October issue. Just three lines and DONE!)

----------------------------------------------- <%@   taglib  prefix="c" uri="http://java.sun.com/jstl/core" %> <%@   taglib  prefix="x" uri="http://java.sun.com/jstl/xml" %>  <c:import   url="students.xml"  var="url" />  <c:import   url="xsl1.xsl"  var="xsl" />  <x:transform  xml="${url}" xslt="${xsl}"  />

-----------------------------------------------

// students.xml

<?xml version="1.0"?>

<students>   <student>    <name>Thomas</name>    <place>Delhi</place>    <number>1111</number>    <mark>78</mark>    </student>

  <student>    <name>David</name>    <place>Bombay</place>    <number>4444</number> 

Page 46: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

   <mark>90</mark>    </student>

  <student>    <name>Mathew</name>    <place>Bangalore</place>    <number>5555</number>    <mark>92</mark>    </student>

  <student>    <name>John</name>    <place>Hyderabad</place>    <number>6666</number>    <mark>72</mark>    </student>

</students>

-----------------------------------------------

xsl1.xsl

=======

<?xml version="1.0"?>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">  

<xsl:template match="/">   <html>   <body>   <table border="2" bgcolor="yellow">    <tr>   <th>Name</th>   <th>Place</th>   <th>Number</th>   <th>Mark</th>   </tr>  

Page 47: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<xsl:for-each  select="students/student">    <tr>    <td><xsl:value-of   select="name"/>  </td>   <td><xsl:value-of   select="place"/> </td>   <td><xsl:value-of   select="number"/> </td>    <td><xsl:value-of   select="mark"/>  </td>    </tr>   </xsl:for-each>

   </table>   </body>   </html> </xsl:template> </xsl:stylesheet>

---------------------------------------------

Name Place Number MarkThomas Delhi 1111 78David Bombay 4444 90Mathew Bangalore 5555 92John Hyderaba

d6666 72

===============================================

JSTL SQL Tags:

The Struts community has ordained that JSP should be  strictly a 'view-technology', in the Model-View-Controller Architecture. According to Struts philosophy, JSP should not deal with Data-Accesss and such data access  should be done by 'Model' components only.( read 'beans'). JSTL , however, provides for sql tags, inspired by ColdFusion! ( please see a very short tutorial on DB-Operations using ColdFusion' available in this issue as a separate lesson. and compare JSTL code and CF code!).And , a few months back, the editor of 'Java Lobby' magazine was all admiration for the absolutely nice features of these sql tags, whatever, 'struts' may say! Just as EJB may be 'overkill', except for really big Enterprise applications, Struts also may be  an unnecessary complication for small and medium level projects. In such cases, it is much more

Page 48: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

direct to provide for data access by the JSP itself, but using JSTL 'sql' tags.We take up these 'sql' tags in  this part of the tutorial.

Let us begin with 'sql.htm'. It just provides a simple form with just a textarea & submit button. Normally, queries by MIS department will be very complex and so we have provided a textarea for the 'select' query.After filling up the query, it is submitted and the corresponding query.jsp is invoked.

// query.htm

<html>  <body>  <form  method=post  action="query.jsp">  <textarea  name='area1'    rows=10  cols=30>  </textarea>  <input  type=submit>  </form>  </body>  </html>

------------------------------------ query.jsp is given below. In the standard jdbc code,we begin by asking for the availability of the driver."jdbc.odbc.JdbcOdbcDriver". And then, we specify the URL of the database as  'jdbc:odbc:telephone'.

Similarly, in JSTL also, we begin with

<sql:setDataSource tag.

  It has attributes for 'driver'   and 'url'. We will refer to the database as 'db'.   The next step is to collect the query typed in area1 by the user.

<c:set  var="s"  value="${param.area1}"  />

is used for this purpose.We also check up whether the query typed by the user has indeed been correctly received.

<c:out   value="${s}"  />

Page 49: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<br>

Next, the '<sql:query'  tag, takes  three attributes., such as, symbolic name:  var="query1" datasource="${db}  sql="${s}

The query result is then displayed in table form.It should be possible to follow the code now.In our example, we are having an Access db, with table1, having two fields, (name, place). registered with ODBC.

// query.jsp

============

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

<html>  <body>  

<sql:setDataSource   var="db"     driver="sun.jdbc.odbc.JdbcOdbcDriver"   url="jdbc:odbc:dbdemo"  />  <c:set   var='s'   value="${param.area1}"   />  <c:out   value="${s}"  />  <br>  <sql:query   var="query1"    dataSource="${db}"  sql="${s}"   /> </sql:query>  <table border="1">    <c:forEach   var="row"  items="${query1.rows}" >   <tr>   <td> <c:out value="${row.name}" /></td>   <td> <c:out value="${row.place}" /></td>   </tr>   </c:forEach>  </table>  </body>  </html>

Page 50: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

===============================================

In the second example,(dbeditor.htm & dbeditor.jsp) we provide a combo, with options such as: add, modify, remove and verify.

In JSTL , we have a separate sql tag known as '<sql:update'   for 'add', 'modify' and 'remove' operations.

When we want to verify, we must use' <sql:query'  tag, because, resultset will be returned.

------------------

dbeditor.htm

<html>  <body bgcolor=lightgreen>  <form method=post action="dbeditor.jsp">  <input type=text name='text1'>name<br>  <input type=text name='text2'>number<br>  <input type=text name='text3'> criterion<br>  <select name=combo1>    <option value="add">add    <option value="delete">delete    <option value="modify">modify    <option value="verify">find </select>  <br>  <input type=submit>  </body>  </html>  -------------------------------------------------

dbeditor.jsp

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

Page 51: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

<body>  <sql:setDataSource   var="db"   driver="sun.jdbc.odbc.JdbcOdbcDriver"   url="jdbc:odbc:dbdemo"  />

<c:set   var='a'   value='${param.text1}'  />  <c:set   var='b'  value='${param.text2}' />  <c:set   var='c'  value='${param.text3}' />  <c:set   var='d'   value='${param.combo1}' />  ----------------------------------------------

<c:if  test="${d == 'add'}" >

<sql:update var="query1"  dataSource="${db}"   sql="insert into table1 values${a}','${b}')" > </sql:update>  <c:out  value="record added"/>  </c:if>  ---------------------------------------------

<c:if   test="${d == 'delete'}" >   <sql:update  var="query1"  dataSource="${db}"   sql="delete from table1 where name='${a}'" >   </sql:update>   <c:out  value="record deleted"/>  </c:if> -------------------------------------------

<c:if  test="${d == 'modify'}" > <sql:update var="query1"  dataSource="${db}"     sql="update table1 set table1.name='${a}',    table1.place='${b}' where    table1.name='${c}'" > <--sql  should be typed in a single line  --></sql:update> <c:out value="record modified"/> </c:if> 

Page 52: moinrazakhan.files.wordpress.com€¦  · Web viewJSP introduction: Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server

------------------------------------------ <c:if  test="${d == 'verify'}" >   <sql:query   var="query1"  dataSource="${db}"   sql="select * from table1 where name='${a}'" >  </sql:query>  <table border="1">   <c:forEach   var="row" tems="${query1.rows}" >   <c:set   var="n" value="OK" />   <tr>   <td> <c:out value="${row.name}" /></td>   <td> <c:out value="${row.place}" /></td>   </tr>

 </c:forEach>   <c:if  test="${n != 'OK'}" >   <c:out value="No such Records" />   </c:if> </table> </c:if> </html> <body> ====================