AsJ2EE programmers, we are familiar with Servlets , JSPand 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 realeased 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 withoutknowledge 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. )
also read:
- Java EE Tutorials
- Java EE 7 Tutorials
- Java EE Interview Questions
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-based language, 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 opeartions, 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 MacroMediaColdFusionExprsess in DeveloperIQ., a few months back.It is interesting to make a comparison of the CF tags approach and the JSTL approach., especially , in DataBaseoperations.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, triggereda lot ofactivity 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 unwittinglyintroduced elements of confusion by the JSP-Custom-Tag specification. To correct this problem, Sun and JCP, initiatedthe JSP-Standard Tag Library (JSTL) project.Though there are a number of popular and powerful tag-libraries, it is always better for j2ee coders toadopt 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 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 recentdevelopment. It was only in 2003, that the official version 1.1 was released and now incorporated intoJSP-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 aprovisionfor 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 forJ2EE students, to understand the trend and get to know the techniques, advantages and limitations oftag libraries…In a way, a study of JSTL is almost synonymouswith 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-2003onwards) and gain access to a number of lessons for illustrations.] Servlets are full-fledged java-classes and so are very powerful. But, when we want to create a dynamically-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. We begin with a simple html form;
//greeting.htm
<html><body> <formmethod=post action='http://localhost:8080/servlet/greeting'> <inputtype=textname='text1'> <inputtype=submit> </form> </body> </html>
(relevant section of greeting.javaservlet)
//greeting.java( code-snippet only) public void doPost(HttpServletRequestreq, HttpServletResponseresp) throwsServletException,IOException { resp.setContentType("text/html"); PrintWriterout = resp.getWriter(); //------------------------------- Strings = req.getParameter("text1"); out.println("<html><bodybgcolor=yellow>"); out.println("wewelcome"+",<br>"); out.println (s); out.println("</body> </html>"); }
It will be noticed thatwe have to write so many ‘out.println’ statements. This makes the page unreadable.( If String-buffer is used , we can do it with just a single out.println , butforming the correct string may pose difficulties).
It is to solve this problemthat JSP was developed five years back(1999).While a servletinterposes HTMLin java code, JSP interposes java-code in HTML, as some authors correctly observe..( in this case, we have to modify the action field in html form, so that it refers to the following greeting1.jsp).
Student readers will know about ‘delimiters’( <%).in ASP. This is the same as inJSP. Only the syntax is slightly different.In JSP parlance, the code within delimiters is known as ‘scriptlet‘.( see greeting1.jsp)
———————————————–
//greeting1.jsp
<html> <bodybgcolor=yellow> <% Strings = request.getParameter("text1"); out.println("we welcome"+<br>); out.println(s); %> </body> </html>
Some coders prefer to use expressions. What is an ‘expression’? It is a method of sustituting request-time values in html page. ( see greeting2.jsp). Carefully note that there is no semi-colon after (“text1”).
// greeting2.jsp <html> <bodybgcolor=yellow> we welcome <br> <%=request.getParameter("text1")%> </body> </html>
The third variant is to use a javabean to encapsulate the business-logic. Wedevelop a jsp-bean as follows:
//greeter.java packageourbeans; public class greeter { public greeter(){} publicStringgreetme(Strings) { return"we welcome..."+s; } }
This source file is compiled and the class-file is copied to : ‘e:tomcat5webappsrootWEB-INFclassesourbeans’ (Carefully note that WEB-INF folder name should be in capital letters).
( Anytime, a new class is placed in Tomcat, we should remember to restart the server).
We can nowwrite our JSP code as follows:
greeting3.jsp
<html> <body> <jsp:useBeanid='bean1'class='ourbeans.greeter'> <% Strings = request.getParameter ("text1"); Stringr =bean1.greeteme(s); out.println(r); %> </body> </html>
<%@taglibprefix=”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 isknown as EL ( Expression Language).
To consider another example,Inservlet & jsp, we write:
String s = request.getParameter("text1");
to collect the input from the user. The same job is done inJSTLby:
<c:setvar="s" value="${param.text1}" >
With these brief hints, it should not be difficult to understand the followingJSPpage writtenbyusing JSTL core-tags.
//greeting4.jsp(usesJSTL)
<%@taglibprefix="c" uri="http://java.sun.com/jstl/core"%> <html> <body> <c:setvar=svalue="${param.text1}"/> We welcome<br> <c:outvalue="${s}" /> </body> </html>
In the previous examples, there was java code in a few lines atleast. But, in theJSTLexample, we find that there are only tags and no javascriptlets. This is the avowed objective of the JSTLinitiative, under the auspices of Java Community Project! Why?This enables, clean separation ofPage 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:
- core
- xml
- sql
- formatting
- functions.
The most difficult part isto set up Tomcatso 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 Tomcat5even, as yet. Without hands-on experimention, JSTL could be confusing and strange, because of thefact that it is veryrecent. But in coming months, support will be built into Tomcat and we won’t have to worry about installing the JSTLlibraries 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 fromJCP, (ie) JSF (Java Server Faces)…. which may soon replace Struts.
We unzipthe jwsdp1.3and installit 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 :
- docs
- lib
- samples
- tld(tag library descriptors)
When we look into the ‘lib’ folder, we findtwo jar files:
- standard.jar
- jstl.jar
We should copythese two jar files into:
'e:tomcat5webappsrootWEB-INFlib'
(Remember to restart the Tomcat server). That is all that is required to useJSTL. ! The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These files are alreadyincluded 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 notensuredfor other environments.).( however, we adopted the same method in Tomcat4.1 with jdk1.41 and got correct functioning.)
The JSTLfolder 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