You are on page 1of 61

Installing, Configuring, & Running Tomcat 6.

0 Servlet Container on
Microsoft Windows, and Developing & Running your first JSP Page
In this article I'll introduce what is JSP and why at all do we need to learn it.
Then I'll move on to describe the installation of open source Servlet
Container/JSP Engine, Tomcat. Once done, I'll explain the steps of running
your first JSP page. Note that I am not going to describe the structure of a
JSP page and what are the different features of JSP, I'll cover them in a
separate article.
What is JSP?
JSP stands for 'Java Server Pages'. These are pages which are used to serve
dynamic content to the user using logic and data (XML, Database etc) on the
server side. JSP is a part of J2SE (Java 2 Standard Edition) and along with
Java Servlets and Java Beans is used to develop efficient, scalable and
secure web applications in quick time.
Why bother with JSP when ASP is already here?
Nice question, first of all ASP is not the only solution out there which
supports rapid web application development, there are others like PHP, Perl,
ColdFusion etc. JSP is different from all of them because :
• JSP uses Java. Java is by far one of the most popular programming
languages on the web. Its simpler syntax and 'write once run
anywhere' capability makes it THE server side programming language
of choice. So JSP pages and Java applications that you create will run
on almost all major operating systems e.g. Windows , UNIX, Mac etc.
You don't need to create separate apps for separate platforms.
JSP is part of J2EE. J2EE (Java 2 Enterprise Edition) is one of the most
popular models used to develop Enterprise level applications. J2EE is
supported by software giants like Sun Microsystems, BEA, Oracle, IBM
etc. So once you learn to program JSP, you can extend your skills to
learn other Java technologies to become what is called, an Enterprise
Software Developer.
Networking is built into Java. Java's inherent support for networking
makes it an ideal langauge for the internet.
I can continue to write more and more reasons as to why to use Java (JSP)
but then it will make my article longer than I would like, so I suffice with the
above features. Once you'll learn Java (JSP), you'll come to know what I
mean when I say 'Java is the best language for the internet'.
Continue reading to see the basic steps required in the installation of Tomcat
6.0 Servlet Container / JSP Engine. I'll be using Tomcat in the later articles
and tutorials on 'Server Side Java' so you need to have it installed on your
system.
Following is a list of topics we'll cover in this article :
• Introduction to JSP ( this page )

• Installing Tomcat 6.0
• Your first JSP page
• Summary
You'll need to have JDK 1.6 (or simply 'JDK 6', as it is called on Sun's
download page) installed on your system in order for Tomcat 6.0 to work
properly. If you don't already have it, you can get it from java.sun.com.
Obtaining Tomcat 6.0
Tomcat 6.0 is an open source and free Servlet Container and JSP Engine. It
is developed by Apache Software Foundation and is available for download at
http://tomcat.apache.org, or more specifically at http://tomcat.apache.org/
download-60.cgi. Choose the latest Tomcat 6.0 version. Currently Tomcat
6.0.14 is the latest version. Once you have downloaded Tomcat 6.0, proceed
to the next step.
Installing Tomcat 6.0
Unzip the file to a suitable folder. In Windows, you can unzip it to C:\ which
will create a directory like C:\apache-tomcat-6.0.14 containing Tomcat files.
Now you'll have to create two environment variables, CATALINA_HOME and
JAVA_HOME. Most probably you'll have JAVA_HOME already created if you
have installed Java Development Kit on your system. If not then you should
create it. The values of these variables will be something like :
• CATALINA_HOME : C:\apache-tomcat-6.0.14
• JAVA_HOME : C:\Program Files\Java\jdk1.6.0_03
To create these environment variables in Windows 2000 or Windows XP , go
to Start -> Settings -> Control Panel -> System -> Advanced ->
Environment Variables -> System variables -> New. Enter the name and
value for CATALINA_HOME and also for JAVA_HOME if not already there.
Under Windows 95/98, you can set these variables by editing
C:\autoexec.bat file. Just add the following lines and reboot your system :
SET CATALINA_HOME=C:\apache-tomcat-6.0.14
SET JAVA_HOME=C:\Program Files\Java\jdk1.6.0_03

Running Tomcat 6.0
Ok now, lets start Tomcat by running the C:\apache-
tomcat-6.0.14\bin\startup.bat batch file. Tomcat server will start and print
some status messasge. Now point your browser to http://localhost:8080 and
you should see the default Tomcat home page. To shutdown the server run
C:\apache-tomcat-6.0.14\bin\shutdown.bat batch file.

0. }</style> </head> <body> <% String name = "Faisal Khan". %> .14\webapps\ folder and create a new directory with the name of "star".jsp' file and save it : <html> <head> <style>p { font-family:tahoma. Now create a new file and save it as 'index.Go to C:\apache-tomcat-6.jsp' in the "star" directory created above. You can give it any name you want but for this example we'll stick with "star". Copy the following text into 'index. font-size:14pt.

In this case we simply declared a variable 'name' of type String ( simple text ) and initialized it with a value of "Faisal Khan". %> Next we display the value of 'name' variable to the user. Each . Introducing JavaServer Pages Based on servlet technology. I then walked you through the steps of downloading and installing Tomcat 6. JavaServer Pages (JSP) is set to be one of the most important elements of Java server programming.jsp to see the JSP page running. So what are JavaServer Pages? Well.0. <p>Hello <%= name %>!</p> Start Tomcat server and point your browser to http://localhost:8080/star/ index. It's by no means complete yet. Tomcat is Java web container ( Servlet Container and JSP Engine ) available for free from Apache Software Foundation. <p>Hello <%= name %>!</p> </body> </html> Explanation Above page appears to be a simple HTML page except one line of Java code between the <% and %> tags. Summary In this article I introduced JSP as a new. efficient. but that will change as the Java 2 Enterprise Edition comes together.14. they combine markup (whether HTML or XML) with nuggets of Java code to produce a dynamic web page. In the end we built and tested a simple JSP page 'index. You can add server side Java code between these tags. you can substitute your own name if you want.jsp'. scalable and secure technology to develop web applications. These work the same way as <% %> tags in ASP. and currently shaping up at breakneck speed. <% String name = "Faisal Khan".

jsp package.page is automatically compiled to a servlet by the JSP engine.servlet. Finally. the page is first passed to a JSP engine which compiles the page to a servlet. With it. given the flexibility of the servlet model. If you take a look in the source files for the javax. you can split the functionality of your web applications into components with well-defined public interfaces glued together by a simple page. and then executed. runs it and returns the resulting content to the client. the web server's servlet engine will run the compiled page.esperanto. applets and the web server .org. with JRun. JSP provides a variety of ways to talk to Java classes. To give you an idea of the future. you'll find the following classes : • JSPPage • HttpJspPage . In this 'application assembly' model. This model allows tasks to be sub-divided . It is possible to view the finished servlet code that is generated by locating it within the directory structure of the servlet engine. it's nice and simple! In this chapter. the business logic is separated from the presentation of data.a developer builds custom components and the page designer assembles the application with a few judicious method calls.nz/jsp/jspfaq. making it more portable and the server market more competitive than its rivals. see the JSP FAQ at http://www. servlets.html). showing a typical web application architecture Architectural Overview A JavaServer Page is a simple text file consisting of HTML or XML content along with JSP elements (a sort of shorthand for Java code).1. we will : • Discuss the JavaServer Pages (JSP) architecture • Look at the elements of a JSP file. When a client requests a JSP page of the web server and it has not been run before. This is very helpful when trying to debug your JSP files. JavaServer Pages is a specification that is already implemented by several web servers (for more details. Thereafter. It should be no surprise. on which your code will run without change. and the tags used to represent them • Encapsulate logic in a JavaBean component and integrate it with JSP • Walk through a detailed example using JSP. For example. that the current reference implementation of the JSP engine is itself a servlet. this separation of logic and presentation may become yet more extreme with the use of custom tags slated for JSP 1. the first time it is requested. you can find the source code for your JSP files (in servlet form) in the jrun/ jsm-default/services/jse/servlets/jsp directory.

%> <!-. Not surprisingly they are : • jspInit() • jspDestroy() • _jspService(HttpServletRequest request.namely that it must have three methods.Scriptlet .Set global information for the page --> <%@ page language="java" %> <!-.Declare the character variable --> <%! char c = 0. and its creation is the responsibility of the JSP engine.They define the interface for the compiled JSP page . HttpServletResponse response) The first two methods can be defined by the JSP author (we'll see how in a moment). but the third is the compiled version of the JSP page.Java code --> . JSP Methods It's time we saw a JSP file : <html> <head> <title>Demo of a JSP page</title> </head> <body> <!-.

Elements of a JavaServer Page The Java code in the page includes : • Directives – these provide global information to the page. j++) { // Output capital letters of the alphabet. soon. We will meet the last JSP element type. The HTML is self-explanatory and written the way it should be. rather than cluttering up methods of a servlet. and change starting letter c = (char)(0x41 + (26 . import statements. for example. In the above example we set the script language to Java.these are for page-wide variable and method declarations.toString() to the HTML page --> <%= c %> <% } %> <br> <% } %> </body> </html> This page just outputs the alphabet 26 times and changes the starting letter.. • Expressions . the page for error handling or whether the page is part of a session. i < 26.the Java code embedded in the page.formats the expression as a string for inclusion in the output of the page.. j < 26. i++) { for (int j = 0.Output the value of c. They provide the means to totally separate presentation from logic.i + j)%26). A good example is <jsp:useBean . and perform a function behind the scenes. These elements follow an XML-like syntax. actions. • Declaratives . • Scriptlets . <% for (int i = 0./> which finds or creates an instance of a bean with the . %> <!-.

Now let's examine the basic elements of a JSP in a more complete fashion.given scope and name. With the tag extension mechanism to be introduced in JSP 1. the page directive has many possible attributes. where the directive may have a number of (optional) attributes. This has a concise summary of what we'll see here. before we code some more.sun. A JSP directive is a statement that gives the JSP engine information for the page that follows. as the mandatory ones have default values. but these are intended for future JSP tools. Possible directives in JSP 1.1. Each directive has an optional XML equivalent. you'll be able to define similar action tags and put their functionality in a tag library. The general syntax of a JSP directive is <%@ directive { attribute=”value” } %>. Specifying these is optional.html in PDF format.com/products/jsp/syntax. .0 are : • Page – information for that page • Include – files to be included verbatim • Taglib – the URI for a library of tags that you'll use in the page (unimplemented at the time of writing) As is to be expected. so we won't consider them here. Something I've found very useful to have around while coding is the syntax crib sheet available at http://java.

JSP Attributes .

. Scriptlets are defined as any block of valid Java code that resides between <% and %> tags. int count = 0.JSP Attributes A JSP declaration can be thought of as the definition of class-level variables and methods that are to be used throughout the page. To define a declarative block. <%! String var1 = "x". } %> Note that you put semi-colons after each variable declaration. private void incrementCount() { count++. just as if you were writing it in a class. begin the block of code with <%! declaration>. This is how you would define the optional jspInit() and jspDestroy() methods that we mentioned earlier.

println(var1). out.Description The following snippet shows both how to get a named parameter from the request object. There are also a host of implicit objects available to a scriptlet from the servlet environment. and how to pass a string to the output stream for the page.getParameter("lname"). Implicit Objects . <% String var1 = request. Code that is defined within a scriptlet can access any variable and any beans that have been declared. %> .This code will be placed in the generated servlet's _jspService() method.

// servlet request.0 reference implementation. ServletException { JspFactory factory = JspFactory. pageContext. Object page = this. from which the other implicit objects are obtained for the duration of the _jspService() method. // Initialize implicit variables for scripting environment HttpSession session = pageContext. try { // Body of translated JSP here. public void _jspService(HttpServletRequest request. // errorPageURL false.Having discussed implicit objects.handlePageException(e). response. true // autoFlush ). HttpServletResponse response) throws IOException.close().getOut(). } finally { out.getSession().getDefaultFactory(). } catch (Exception e) { out. . we're in a better position to understand the code featured in the comment for the PageContext source from the JSP 1. PageContext pageContext = factory. null.0 reference engine injects into the JSP page's _jspService() method.clear(). JspWriter out = pageContext. // needsSession JspWriter. factory..releasePageContext(pageContext).DEFAULT_BUFFER. } } JspFactory returns the pageContext implicit object. This shows the code that the JSP 1..getPageContext( this.

it is a good idea to try and put all of your business logic inside reusable components. So. when setting up an application development architecture that involves JavaServer Pages. The "third way" is a mixture of presentation-based calls to a Bean or servlet. Anything between <%= and %> tags will be evaluated. So from the drudgery of coding HTML output in servlets. These components can then be 'plugged' into any JavaServer Page that requires them.getParameter("price") %> Something you'll want to note is that the expression doesn't end with a semi-colon. Note: The current reference JSP implementations don't automatically reload the new Bean if you recompile while the server is running. That's because the JSP engine will put the expression within an out.println() call for you. which components can be better tested. i < 10. You can then take advantage of HTML editors to develop your content. But don't be dragged too far the other way. You'll need to restart the servlet engine. The current price of item A100 is <%= request. Again and again. JSP expressions allow you to essentially parameterize HTML (just as you would parameterize a SQL query that differs by only a couple of values). i++) { %> <br> Counter value is <%= i %> <% } %> Coding JSP Pages A big advantage in developing a JavaServer Page is that you can code the HTML without enclosing it in Java code. . and untangling the meaning of that section you coded months back. converted to a string. we've arrived at the flexibility of coding Java snippets into the HTML page. Simply enclose the beginning and the ending of the condition or loop in separate pairs of <% and %> tags : <% for (int i = 0. Conversion from a primitive type to a string is handled automatically. as you must do in a servlet. This moves from embedding code to embedding components and action tags in the page. your code will set up conditions and loops using a one-line JSP scriptlet and then include the HTML code directly beneath it.A JSP expression is a very nice tool for embedding values within your HTML code. making improvements to them. it's debugging the pages. are well-encapsulated and good OOP citizens. Heard of the people who can't fit their ASP files into Notepad? And if there's one problem with ASP and JSP. and then displayed.

then their purpose is clearer. where the transactions and scaling issues are explicitly the problem of the container and not the bean. . I found that once I stopped thinking about these graphical tools and concentrated on it just being a class that follows a few design patterns. it saves its current state. The JavaBeans architecture uses reflection to infer the public methods. To show how to use a simple bean. The ultimate aim is to make them part of graphical application assembly tools. But it's not what they were originally designed for. A JavaBean is a Java class that fits the following criteria : • Public class. • Public set and get methods to simulate properties. unless it acts on an indexed property. • Public constructor with no arguments. Beans mean that your page isn't clogged with code. Most of the time beans are used to encapsulate visual and non-visual elements of a GUI. The presentation of the letters will remain the responsibility of the JSP page. simple encapsulations of Java code. two methods must exist. Properties are always set and retrieved using a common naming convention. for a richer user interface. Typically. will be another expression of their code.and complexity-wrapping role. There's some snazzy stuff to link beans up.What is a JavaBean? The Java language has implemented the idea of a component as something called a JavaBean. The current state of a bean is defined by the current values of its public properties. When a bean component is serialized. called BeanName BeanInfo to give more explicit information. to implement drag-and-drop and to save the state of a bean between instances. but the color mapping will be the bean's job. a bean component is imported into a program. The get method has no arguments. Apart from that a bean is just like any other Java class.they work well. For each property. If we think of them as components. That kind of heavyweight use may be necessary sometimes but I think that beans will stay around for the lighter work we show here. its properties are set and its methods are called. A bean can also be serialized and saved for later use. we're going to develop the alphabet example from earlier. But you can provide a BeanInfo class. Don't get me wrong . and associate each letter with a color. It does this by implementing the Serializable interface. Beans don't sit obviously in JSP. a getxxx() and setxxx() method (where xxx is the name of the property). things were easier to understand! Because of this history. Much of the business logic we're hinting at might be better placed in an Enterprise JavaBean. And beans as graphical components of your final web page.

} } public void setCharacter(String nextChar) { this.9f.c = (char)(FIRST_LETTER + i). float h = (float)i/ALPHABET_LENGTH. static int ALPHABET_LENGTH = 26.util.map. char c = 0.package com.getRGB() . i++) { this. b)).9f. float b = 0. s. import java.*.wrox. public AlphabetCode() { this. for (int i = 0. this.toString()).awt. public class AlphabetCode { HashMap map.getHSBColor(h.c)).toHexString(rgb. import java.Color. } public String getColor() { Color rgb = (Color)map.c). StringBuffer htmlColor = new StringBuffer( colorNumber. static int FIRST_LETTER = 0x41. Color.map = new HashMap(ALPHABET_LENGTH).jspexamples. i < ALPHABET_LENGTH.put(new Character(c).charAt(0).c = nextChar. Integer colorNumber. } public String getCharacter() { return (new Character(this.get(new Character(this. float s = 0.

return htmlColor.It uses plain method calls to the Bean --> <%@ page language="java" %> <%! char c = 0.AlphabetCode" /> <% for (int i = 0. htmlColor. Character thisChar = new Character(c). and the set and get methods. j++) { c = (char)(0x41 + (26 . & 0x00ffffff)). The class sets up the color of each character in the constructor.toString(). // toHexString() won't preserve leading zeros. "\"#").i + j)%26). .append("\"").length() != 6) { htmlColor. and then returns the color of the current character as an HTML color. } else htmlColor. if (htmlColor. so need to add them back in // if they've gone missing. %> <jsp:useBean id="letterColor" scope="application" class="com.. i < 26. i++) { for (int j = 0. j < 26.insert(0.wrox. "\"#00").This page generates a series of rainbow colored letters --> <!-..insert(0. The modified JSP page looks like : <html> <head> <title>Color demo I</title> </head> <body> <!-.jspexamples. } } The bean things to note are the public class and constructor.

getColor() %> > <%= letterColor.toString()).getCharacter() %> </font> <% } %> <BR> <% } %> </body> </html> Giving the result : .setCharacter(thisChar. %> <font color=<%= letterColor. letterColor.

startserver includes jsp1.0 reference implementation. Let's look at the attributes : . so let's look at that : <jsp:useBean id="letterColor" scope="application" class="com. If it can't find one it instantiates the named class. />.0/examples/WEB-INF/jsp/beans).these are only executed when a new instance is created. In the JSP 1.AlphabetCode" /> The jsp:useBean tag first searches for a bean instance that matches the scope and class. the server looks for your packages in the CLASSPATH environment variable (on my machine.jspexamples.wrox. no-args constructor. The only new syntax is <jsp:useBean . Screenshot The JSP page uses straight method calls ( setCharacter(). If there are any initialization time properties you need to set. getCharacter() and getColor()) to the bean... using its public. you can place the appropriate tags between <jsp:useBean> and </jsp:useBean> .

jsp:getProperty and jsp:setProperty : <html> <head> <title> Color demo </title> . JavaBean Attributes Scope on a JSP page goes something like this : JavaBean Scope We're not finished in our tour of tags. With a couple of changes to our JSP code. we can show you two more . though.

but it's not a particularly good design. Then the code to actually manipulate the model is in the bean. To show this simply.AlphabetCode" /> <% for (int i = 0. It shows off the various JSP elements quite well.toString() %>" /> <FONT COLOR=<jsp:getProperty name="letterColor" property="Color" /> > <jsp:getProperty name="letterColor" property="Character" /> </FONT> . If we look at the MVC pattern.2. let's design a file viewer bean that will read a specific directory ( C:\jdk1. Ideally. Note that the property name is the setCharacter() method without the prefix. and the page is both the view and the controller (using the HTTP request). i++) { for (int j = 0. The <jsp:setProperty . %> <jsp:setProperty name="letterColor" property="Character" value="<%= thisChar. j++) { c = (char)(0x41 + (26 .. their size (if they're files) and their timestamp : ..i + j)%26). There's a little too much code in the page in the last example. i < 26.It uses the JSP property set and get tags --> <%@ page language="java" %> <%! char c = 0..This page generates a series of rainbow colored letters --> <!-. </head> <body> <!-. We'll see an alternative version of the jsp:setProperty tag later.jspexamples. the property name and the value with which to set the property. %> <jsp:useBean id="letterColor" scope="application" class="com. the page should be almost all presentation with simple JSP elements (methods and properties) to control the bean. Character thisChar = new Character(c). <jsp:getProperty .1) and output the file and directory names. but the control rests with the page. j < 26.wrox.. /> is self- explanatory. /> needs the bean name.. The question is how to prevent the control code taking over the page.. we see that the bean is the model.

import java.wrox. } public void refreshList() { .getPath(). File[] contents. public FileViewerBean() { myDir = new File("C:\\jdk1.Date. Iterator currentFileView.package com.util. import java.jspexamples.Vector. import java.Iterator. import java.util.util. vectorList = new Vector().io.1"). Vector vectorList.2.File. File currentFile. } public String getDirectory() { return myDir. public class FileViewerBean { File myDir.

} return false. } public String getFileName() { return currentFile.iterator().next().hasNext()) { currentFile = (File)currentFileView.listFiles(). return true. for (int i = 0. } .add(contents[i]).length. vectorList. i++) vectorList. contents = myDir. } public boolean nextFile() { while (currentFileView. i < contents.clear().getName(). currentFileView = vectorList.

} public boolean getFileType() { return currentFile.jspexamples. we have the FileView.toString().FileViewerBean" /> <hr> .isDirectory().jsp code : <html> <head> <title> A JSP file viewer </title> </head> <body> <!-. public String getFileSize() { return new Long(currentFile. } } The idea here is to make the interface to the bean as simple as possible.lastModified()). order the vector by different criteria and so forth. Therefore.This page allows you to see files in selected parts of the drive --> <%@ page language="java" %> <jsp:useBean id="fileViewer" scope="session" class="com. a full-featured file viewer bean might have further methods to detail a file's attributes. so we need to support the different requirements of JSP pages. To put the bean to work.length()).toString(). } public String getFileTimeStamp() { return new Date(currentFile.wrox.

getFileSize() %> <% } %> </td> <td> <%= fileViewer. see their tables .getFileTimeStamp() %> </td> </tr> <% } %> </table> </body> </html> The page is much clearer here.getFileName() %> </td> <td> <% if (!fileViewer. The fine-grained properties simplify the page further. while(fileViewer.refreshList(). with the bean almost acting as an iterator over the directory listing.nextFile()) { %> <tr> <td> <%= fileViewer.getFileType()) { %> <%= fileViewer. To illustrate more functionality of JavaServer Pages. <jsp:getProperty name="fileViewer" property="Directory" /> <table> <% fileViewer. we will build an example that allows you to select from available databases.

• Self-contained parts of the application each have their own JSP.jsp page.jsp . The <jsp:forward . <%@ page language="java" errorPage="ErrorPage.hasMoreElements() == false) { %> <jsp:forward page="/jsp/data/List1. We'll repeat this code on each page. And I'm not interested in wrapping all that functionality in a bean when it's already available. so I've decided to handle it in the page.the main application page. • List3.getParameterNames().jsp" /> <% } %> We have already sorted out an errorpage in the page directive for all error reporting. This is fixed by the sys- admin and is essentially HTML.Shows the tables and their columns for the selected database. • Central error handling.Presents the available databases. Our JSP application will make use of a bean to access the database..jsp . and query them. Similar tags will enable JSPs to handle iterators. which has 22 getXxx() methods to work with. /> needs the . • List1.jsp . let's look at the requirements : • Consistent web interface across pages.jsp for the case where the client has just typed http://URL/DataList..in that we'll be able to define actions that return ResultSet objects for the page to retrieve values from.jsp and needs the menu of databases.The header for all the application pages. so we can forward the work to the List1.Where all the exceptions end up. The parts of the project are : • DataList. It decodes GET requests and passes them to the relevant pages.and column names. I tried various architectures as I developed the application. We'll start DataList. • Same bean code used for different client requests.Shows the result of a SQL query. to receive all requests. as I saw how things panned out and learnt how to use more tags! The client's request should yield a ResultSet object. • Header. We want one page to coordinate the application. • ErrorPage. Working backwards. This is where the tag extension mechanism will prove its worth .jsp .jsp" %> <% if (request.jsp .html . The request object will have no parameters for the plain URL. • List2. their origin suitably noted.

you can use a regular servlet instead.odbc. From this they can formulate a query. You can mix and match servlets and JSPs depending which is most appropriate.JdbcOdbcDriver <option>com.jsp.imaginary. Note: DataList.jsp"> Database URL:<select name=DbURL size=1> <option>jdbc:odbc:employee <option>jdbc:odbc:techlib <option>jdbc:odbc:this_should_break </select> <p> Database driver:<select name=DbDriver size=1> <option>sun. We've sorted out the consistent web interface for the application by using the <%@ include %> . Now we'll code the List1.jsp is only used for checking parameters and forwarding to the right page.html" %> Choose database: <form method="GET" ACTION="DataList. or browse those databases : <html> <head> <title> Database Search </title> </head> <body> <%@ page language="java" errorPage="ErrorPage.jdbc. In this case that's /jsp/ employee/List1.URL relative to the servlet context / application.MsqlDriver </select> <p> Input SQL if you know your query: <p> <input type=text name=inputSQL size=40> <p> <input type=submit> </form> </body> </html> This is straightforward HTML for the most part.jsp page that shows the client what choice they have.msql.jsp" %> <%@ include file="Header.sql.

It should be possible to make this a static HTML file.html.getParameterNames().getParameter("inputSQL") != null)) { %> <jsp:forward page="/jsp/data/List3. Plus if it all goes wrong the error handling needs to be informative.jsp" /> <% } %> Browsing our JDBC tutorials.getParameter("DbDriver") != null) && (request. import java. or report why it didn't work.jsp are the following : <%@ page language="java" errorPage="ErrorPage. we have specified that DataList.*. query the database. we could let the main page (or servlet) create beans with all available databases and drivers and let this page use the bean to generate the database option lists. but the JSP engine complained mightily when I tried.hasMoreElements() == false) { %> <jsp:forward page="/jsp/data/List1. Something for the future. we start to construct a bean that can connect to the specified database URL with the specified driver.jsp form are filled in.jsp" /> <% } else if ((request. .wrox. Finally.jsp needs to forward the request to a page that can display the ResultSet of the query. DataList. The changes to DataList. I've put in databases and a driver I don't have.jsp receives any submissions from this page.sql.tag to include Header. I'm informed that support for forwards to a static page is a matter of interpretation of the specification at this time.getParameter("DbURL") != null) && (request. to test the error handling later.jspexamples. To make this example a bit more realistic. and provide suitable methods to display the returned data. package com. Assuming all three sections of the List1.jsp" %> <% if (request.

close().getDbDriver()).jdbc.forName(this. } public boolean connect() throws ClassNotFoundException.odbc.executeQuery(sql). dbCon = DriverManager.io. public class DbBean { String dbURL. return (r == null) ? null : r.getConnection(this.JdbcOdbcDriver". private Connection dbCon. ResultSet r = s. public DbBean() { super().import java. } public void close() throws SQLException { dbCon. return true.*. . String dbDriver = "sun.getDbURL()). SQLException { Class. } public ResultSet execSQL(String sql) throws SQLException { Statement s = dbCon.createStatement().

The context of the error is better handled in the JSP where the call was made. } } Note that we've not wrapped the ResultSet.jspexamples.sql. import com.DbBean.dbDriver.wrox.dbURL. Let's write a test class to test out the methods and get the error handling sorted : import java. as it's the view of the data that the page will manipulate.*.dbDriver = newValue. bar the mandatory declaration of throws clauses.dbURL = newValue. } public String getDbDriver() { return this. public class TestDbBean { public static void main(String[] argc) . There's also no error handling in here. } public void setDbURL(String newValue) { this. } public String getDbURL() { return this. } public void setDbDriver(String newValue) { this.

ResultSetMetaData rsmd = null. } catch (SQLException e) { System.odbc. int numColumns = 0. try { myDbBean.{ DbBean myDbBean = new DbBean(). } catch (SQLException e) { System.execSQL(sql). String sql = "select authid.println("execSQL() SQLException: " + e). } try . } try { rs = myDbBean.setDbDriver("sun.JdbcOdbcDriver").connect().out.setDbURL("jdbc:odbc:techlib"). myDbBean. lastname.out.out. firstname from authors".println("connect() SQLException: " + e).println("connect() ClassNotFoundException: " + e). ResultSet rs = null. myDbBean. } catch (ClassNotFoundException e) { System.jdbc.

column++) { System. for (int column = 1.getColumnCount().println("Problems with the database . column++) { System. we can reuse the logic in the JSP file. { rsmd = rs.out. column <= numColumns. .out. column <= numColumns. numColumns = rsmd. and we've got the makings of the error handling.close(). } catch (SQLException e) { System. The possible errors are : • The drivers for the database are unavailable ( ClassNotFoundException) . } while (rs.println(rsmd.out.getString(column)).getColumnName(column)).SQLException: " + e).next()) { for (int column = 1. } } } Now we know it works.println(rs. We want to tell the client what went wrong. and show them how to correct it if possible.getMetaData().which only a swift kick to the system administrator will remedy. } } myDbBean.

sql.jsp" %> <%@ include file="Header.wrox.that's something that the user should be able to sort out. • The DriverManager.DbBean" /> <jsp:setProperty name="db" property="*" /> <%! int numColumns.*" errorPage="ErrorPage.getConnection() fails because the dbURL is incorrect . and should be shown as such. ResultSet rs = null. • The call to execSQL() can throw a SQLException if the query is invalid . ResultSetMetaData rsmd = null. • The rest are database or page errors.jsp : <html> <head> <title> Database Search </title> </head> <body> <%@ page language="java" import="java. %> <center> <h2>Results from</h2> <h2><%= request.getParameter("inputSQL") %></h2> <hr> <br><br> <table border="1" bgcolor="#cccc99" bordercolor="#003366"> <tr> .html" %> <jsp:useBean id="db" scope="request" class="com.another job for the sys admin. we can code List3. Finally.jspexamples.

execSQL(sql). e). " + "Do you want to browse the database? " + "If so. } try { rs = db.<% String sql = request. } catch (SQLException e) { throw new ServletException("Your query isn't working.connect(). e). } catch (ClassNotFoundException e) { throw new ServletException("Database drivers not available". } try { rsmd = . leave the SQL input empty". e). } catch (SQLException e) { throw new ServletException("Database URL is wrong". try { db.getParameter("inputSQL").

for (int column = 1.rs.getColumnName(column) %></th> <% } %> </tr> <% while (rs. column++) { %> <td><%= rs.getString(column) %></td> <% } %> </tr> <% } .getColumnCount().next()) { %> <tr> <% for (int column = 1. numColumns = rsmd. column++) { %> <th><%= rsmd. column <= numColumns. column <= numColumns.getMetaData().

getParameter("DbDriver") %>> <input type=hidden name=DbURL value=<%= request. <jsp:setProperty name="db" property="*" /> This matches request parameters with the property names of the db bean instance. db. " + "but the display didn't".getParameter("DbURL") %>> Input SQL:<input type=text name=inputSQL size=40> <p> <input type=submit> </form> </body> </html> There are a couple of noteworthy things in the code. e). DbDriver and DbURL will match.close().jsp"> <input type=hidden name=DbDriver value=<%= request.close(). The query worked. First is the alternative use of jsp:setProperty tags. } %> </table> </center> <p> <form method="GET" action="DataList. This is a shorthand form of . } catch (SQLException e) { throw new ServletException("Database error. rs. and so both these will be set with the values in the request.

java. <html> <title> DataList Error Page </title> <body> <%@ include file="Header. The errorpage for the application must declare itself with the isErrorPage page directive set to true.Need an error page to handle the exception message --> <!-.What error page does an error page use? --> <%@ page language="java" isErrorPage="true" import="java.The fully-qualified class that is the exception --> <%= exception. querying and display parts of the page.getMessage() %> <p> <a href="DataList.jsp file will display.*. Then we output the implicit exception object. <jsp:setProperty name="beanName" property="propertyName" param="parameterName" /> where propertyName and parameterName are identical.jsp">Want to try again?</a> .The exception's message to the world --> <%= exception. And just to see where we came from and what we've brought with us.html" %> <!-. we cycle through the parameter and attribute names. each throwing a different ServletException that the ErrorPage.*" %> <br> <h4>Exception details:</h4> <p> <!-.util. In order that users can requery the database we have an input form that uses the current DbURL and DbDriver values as hidden input and takes a new SQL query. The error handling is split into the connection.sql.toString() %> <br> <!-.

hasMoreElements()) { %> <%= attributeList. We . %> <p> <h4>Parameter listing: </h4> <p> <% parameterList = request.toString() %> <br> <% } %> </body> </html> What if the user selects one of the available databases. while (parameterList.nextElement(). because they don't have the table details. %> <%! Enumeration attributeList.hasMoreElements()) { %> <%= parameterList. and the driver. while (attributeList.getParameterNames(). <p> <%! Enumeration parameterList.getAttributeNames(). but doesn't enter an SQL query.toString() %> <br> <% } %> <p> <h4>Attribute listing: </h4> <p> <% Enumeration attributeList = request.nextElement().

need to decode that, and then show the user the database information they
need to form a query.
First off, how do we look at the tables of a database? Reaching for Chapter
19 of Beginning Java 2, I see that you need the metadata of the connection
- encapsulated in the java.sql.DatabaseMetaData object. The following code
snippet shows this :
private DatabaseMetaData dbMetaData;
static String[] tableTypes = {"TABLES"};

...

dbMetaData.getTables(catalog, schema, tableName,
tableTypes)
dbMetaData.getColumns(catalog, schema, tableName,
columnName)
Here are the two new DbBean methods we need to return the appropriate
ResultSets to the JSP,
public
ResultSet getTables() throws SQLException
{
dbMetaData
= dbCon.getMetaData();
return
dbMetaData.getTables(null, null, null, tableTypes);

}
public ResultSet getTable(String tableName) throws
SQLException
{
return
dbMetaData.getColumns(null, null, tableName, null);

}
with tableTypes and dbMetaData declared as above. Note how both methods
can throw a SQLException.
Having added the declarations and methods to the DbBean class, here's the
new code for the test bean :
while
(rs.next())
{
for
(int column = 1; column <= numColumns; column++)

{

System.out.println(rs.getString(column));
}

}

}
catch
(SQLException e)
{

System.out.println("Problems with the database - SQLException: " +
e);

}

// Test for List2.jsp
ResultSet
tables = null;
try
{
tables =
myDbBean.getTables();

}
catch
(SQLException e)
{

System.out.println("getTables() SQLException: " + e);

}
try
{
while
(tables.next())
{

String current_table = tables.getString("TABLE_NAME");

System.out.println(current_table);

System.out.println(" ");
ResultSet table =
myDbBean.getTable(current_table);
while (table.next())
{

System.out.println(table.getString("COLUMN_NAME"));

}
System.out.println(" ");

}
myDbBean.close();
} catch (SQLException e) {

System.out.println("Table listing failed: " + e);

}

}
}
From this, we can create the List2.jsp file. This will display every table in the
database, plus the names of the columns in that table.
<html>
<head>
<title>
Database Details
</title>
</head>
<body>

<%@ page language="java" import="java.sql.*"
errorPage="ErrorPage.jsp" %>

<%@ include file="Header.html" %>

<jsp:useBean id="db" scope="request"
class="com.wrox.jspexamples.DbBean" />

<jsp:setProperty name="db" property="*"
/>

getTables(). } try { ResultSet tables = db. %> The database (<%= request. e). while (tables. String current_table. } catch (ClassNotFoundException e) { throw new ServletException("Database drivers not available". %> <p> <h4><%= current_table %> </h4> <table . e).getParameter("DbURL") %>) you have selected has the following tables: <% try { db.next()) { current_table = tables.connect(). } catch (SQLException e) { throw new ServletException("Database URL is wrong".<%! int numColumns.getString("TABLE_NAME").

next()) { %> <td><%= table. db. } catch (SQLException e) { throw new ServletException("Database problems".border="1" bgcolor="#cccc99" bordercolor="#003366"> <tr> <% ResultSet table = db.getString("COLUMN_NAME") %></td> <% } %> </tr> </table> <% table. // Loop through columns and get their names and characteristics while (table.close().getTable(current_table). } tables.close(). } %> <p> <form method="GET" action="DataList. e).close().jsp"> .

The code for the final DataList.jsp looks like : <%@ page language="java" errorPage="ErrorPage.getParameter("DbDriver") %>> <input type=hidden name=DbURL value=<%= request. The value is an empty string if the user has not entered anything.getParameter("DbURL") %>> Input SQL:<input type=text name=inputSQL size=40> <p> <input type=submit> </form> </body> </html> When you have a text field.jsp to do this. you need to check for a non-empty string that isn't all space characters. the browser will always send a parameter with the same name as the text field element. To check if inputSQL contains something that could be SQL. <input type=hidden name=DbDriver value=<%= request.jsp" %> <%! boolean emptySQL(String sql) { if (sql != null) { if (sql. } return . I've created a convenience method in DataList. but it's hard to see if there are just a couple of space characters in the field.trim(). else return false.length() == 0) return true.

jsp" /> <% } else if ((request. We'll look at these in more detail in Chapter 11. To recast the code as a servlet.jsp file which just forwards requests to the right JSP page.. it's very easy to mix JSP and servlets as and when the need arises.getParameter("DbURL") != null) && (emptySQL(request. An ideal candidate is the DataList. } %> <% if (request.getParameter("DbDriver") != null) && (request. We need one instance for each forward request.hasMoreElements() == false) { %> <jsp:forward page="/jsp/data/List1. /> and <%@ include .jsp" /> <% } %> As we mentioned at the start of this example.getParameter("inputSQL")) == false)) { %> <jsp:forward page="/jsp/data/List3..getParameter("inputSQL")))) { %> <jsp:forward page="/jsp/data/List2..jsp files to point to the servlet. %> tags we've used previously. we need to use RequestDispatcher classes.getParameter("DbURL") != null) && (emptySQL(request. true.getParameterNames(). I installed the servlet in examples\WEB-INF\servlets of the reference .getParameter("DbDriver") != null) && (request. Note: Remember to change the ListX. but they are essentially the servlet equivalent of the <jsp:forward .jsp" /> <% } else if ((request..

getParameterNames(). response).getParameter("DbURL") != null) && (emptySQL(request.servlet.*. import javax.jsp").http.getServletContext().io. IOException { RequestDispatcher firstListRD = this. .servlet. HttpServletResponse response) throws ServletException. RequestDispatcher thirdListRD = this.getParameter("inputSQL")))) { secondListRD.*.jsp"). import javax.forward(request.getParameter("DbDriver") != null) && (request.forward(request. if (request.implementation and pointed my browser at http://localhost:8080/examples/ servlet/DataList.jsp").*. } else if ((request. getRequestDispatcher("/jsp/data/List2. response). import java. RequestDispatcher secondListRD = this.getServletContext().hasMoreElements() == false) { firstListRD. public class DataList extends HttpServlet { public void doGet(HttpServletRequest request. getRequestDispatcher("/jsp/data/List1. getRequestDispatcher("/jsp/data/List3.getServletContext().

. } return true.length() == 0) return true. } } Note: Note that you can't forward the request if you have an open output stream or writer. </jsp:plugin> tag included in JSP 1.getParameter("inputSQL")) == false)) { thirdListRD.trim(). This means that you can't include a file and then forward the request. For example : <jsp:plugin type="applet" code="NervousText.. and so the DataList servlet can't act as a template file.forward(request.0 (but not currently implemented) allows you to specify an applet's or bean's place in the final page. response). } else if ((request. The <jsp:plugin> .class" .getParameter("DbURL") != null) && (emptySQL(request. } } boolean emptySQL(String sql) { if (sql != null) { if (sql.getParameter("DbDriver") != null) && (request. else return false.

dynamic user interfaces within a web page. take a look at the following JSP tag : <star:secondtag> <p align="center">Date value retrieved from JSP Tag : <%= time %></p> </star:secondtag> . If the file changes. Summary JavaServer Pages technology brings together the power of Java Servlets and the ease of HTML coding to give developers a powerful method in which to create server-side web applications. It is currently one of the most exciting and fast-changing topics in the Java world. • The JSP engine performs a first-time compile on a JSP file which generates a new servlet with the desired content. Introducing Scripting Variables in JSP Tags This tutorial builds on the " Building Your first custom JSP Tag" article. • JavaBeans can be used within a JSP file to help split presentation and logic into their component parts. content. then a new servlet is generated. But when we talk of them in context of JSP pages we mean the page level variables declared by JSP tags. In this chapter. To illustrate my point. we learned the following : • A JavaServer Page file consists of standard markup tags. JSP directives. What are Scripting Variables ? Well scripting variables are variables declared in any scripting language. JSP scriptlets and actions tags. otherwise the compiled version is used. JSP declarations.getWhackyText() %>" > </params> <fallback> <p>It's messed up - apologies</p> </fallback> </jsp:plugin> This holds out the potential of creating very rich. In that article we learned that JSP tags are simple Java classes with attributes as properties and must implement Tag or BodyTag interface. In this tutorial we will learn what are scripting variables and how to make use of them in JSP tags. codebase="/applets/NervousText" height="50" width="375" /> <params> <param name=text value="<%= someObject.

public final class SecondTag implements Tag { private PageContext pc = null. } public void setParent(Tag t) {} public Tag getParent() { return null. import javax. import javax. Following are the topics we will cover in this tutorial : • Overview ( this page ) • Java class which implements Tag interface • Java class which extends TagExtraInfo class • Tag Library Descriptor • JSP page which calls the Tag • Summary SecondTag JSP Tag Create a new . time.*. Copy the following text in it and save it as SecondTag.java. But the true potential of scripting variables will only be realized when you read my forthcoming article on iterating JSP tags which iterate and display content from database.util. } public int doStartTag() throws JspException { .e.stardeveloper. Isn't it nice that the tag makes us available scripting variable which we can use anywhere in our JSP page? Whether you get the point or not this technique of declaring scripting variables by JSP tags and then using them on the JSP page is very useful. package com.java source file in the /WEB-INF/classes/com/stardeveloper/ tag/test folder of your web application.*.test.servlet.jsp.jsp.tagext. public void setPageContext(PageContext p) { pc = p.Above is a JSP tag whose body content contains simple HTML tags along with a single scripting variable i.*. it is important that you read this article carefully. In this tutorial I'll describe making use of these scripting variables with a simple example. import java.servlet.tag. Those JSP tags will make different scripting variables available to the JSP page to be placed anywhere we like. To make that use of scripting variables.

stardeveloper.getTime(). import javax.*. Let us see how we implement all of them in our SecondTag class. we have to implement all of the six methods of Tag interface which are : • setPageContext(PageContext p) • setParent(Tag t) • getParent() • doStartTag() • doEndTag() • release() I have listed the methods above in the order they are called by the JSP page. Explanation of SecondTag. Our class implements Tag interface.class file will be created.setAttribute("time".jsp. telling that SecondTag belongs to com.test. Then comes our class declaration. Then we import the packages we will be using in this class. I used it because final classes are more efficient than non-final classes.jsp. We chose Tag becaues it is simpler and does the job we are looking for.tag.servlet.java Source Code First line is the package statement. pc. private PageContext pc = null. package com.*.toString()). } public void release() { pc = null. Like I said in the "Building Your first custom JSP Tag" article.getInstance().tagext. Notice the "final" keyword? it is not required for creating JSP tags. import java.test package. public final class SecondTag implements Tag { Then we declare the sole class-level variable for our SecondTag Java class. import javax. } public int doEndTag() throws JspException { return EVAL_PAGE. As we learned in the last article. } } Now compile SecondTag. return EVAL_BODY_INCLUDE. our JSP class must implement Tag or BodyTag interface.tag. .java and SecondTag.servlet. cal.util. Calendar cal = Calendar.*.stardeveloper.

getInstance().toString()). public int doStartTag() throws JspException { Calendar cal = Calendar. Calling toString() method of retrieved Date object gives us current date and time. return EVAL_BODY_INCLUDE. } Another useful method in Tag interface is doEndTag(). The whole point of this tutorial is to describe how to declare a scripting variable from the JSP tag. Remember that this PageContext object is provided by the JSP tag and this is the first method which is called by JSP page. This method is called when PageContext and parent Tag objects have been set. Other possible return value is SKIP_BODY which causes JSP page to skip the body content of the tag. Once done.setAttribute("time".getTime(). Since in SecondTag there is no parent tag enclosing it. pc. Since we already have a private reference to PageContext object for the current JSP page. To make this scripting variable available to the JSP page we have to make use of setAttribute() method of PageContext object. we don't care about these methods and implement the minimum possible for them. cal. } setParent() and getParent() are for setting the parent Tag reference. This current date and time will be the value of our time variable. thus making us PageContext object available to be used by later methods if we want. A parent tag is a JSP tag which is enclosing the current tag. To do that we create an instance of Calendar object and use it's getTime() method to get Date object. Remember body content of a tag is the content present between it's starting and ending tags. we use it's setAttribute() method to set the value of time variable to current date and time we calculated above. public void setPageContext(PageContext p) { pc = p. But we don't need that here.setPageContext() is pretty simple so we set the private class variable to the provided PageContext object. we return EVAL_BODY_INCLUDE to tell the JSP page to show the body content of the JSP tag. } Now doStartTag() is the real useful method we should talk about. There isn't much we want to do in this method so we simply return an EVAL_PAGE value . public void setParent(Tag t) {} public Tag getParent() { return null. the body content will not be shown to the user. To illustrate that we will declare a single scripting variable called time.

override one of it's methods and that's it.indicating to the application server to continue evaluating the JSP page.tagext. public class SecondTagTEI extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo("time". SecondTagTEI Class Create a new .test.java file in the /WEB-INF/com/stardeveloper/tag/test folder. It is the same folder where we kept the SecondTag class.java.NESTED) }. . true. One last thing to do to declare scripting variables from a JSP tag is to create a new Java class which extends TagExtraInfo class and overrides one of it's methods. In the last comes release(). we just have to extend it. our main JSP tag class.String". package com. On the next page we learn about TagExtraInfo class. but that we don't want here.stardeveloper. TagExtraInfo class as it's name suggests is an "extra info" class which is *required* when declaring scripting variables from JSP tags.servlet.*. Let us now create our SecondTagTEI class which extends TagExtraInfo and overrides it's getVariableInfo() method. Now copy and paste the following text in it and then save it as SecondTagTEI. import javax. The only thing to do here is to release the reference to PageContext object. cal. getVariableInfo().getTime().lang.tag. Other legal value is SKIP_PAGE. VariableInfo. public int doEndTag() throws JspException { return EVAL_PAGE. "java. which will cause the JSP page to skip further processing of the page.jsp. } We are done with SecondTag.toString()).setAttribute("time". } public void release() { pc = null. TagExtraInfo Class If you have followed the earlier article then you would have noticed that the only thing different we have done till now for declaring scripting variables in JSP tag is to put following line in our main class's doStartTag() method : pc.java.

NESTED Variable is visible between start/end tags. Now compile this SecondTagTEI class too to get SecondTagTEI. Let's complete this tag by updating the DemoTags.AT_BEGIN Variable is visible after start tag.sun. Since we have only one scripting variable.tld in the /WEB-INF/tlds/ folder. Ours is of type String.dtd"> <taglib> <tlibversion>1. our SecondTagTEI class extends TagExtraInfo class and overrides it's getVariableInfo() method. In this method we return an array of VariableInfo classes.stardeveloper.tld Create a new file ( or use the one created in the first article ) and save it as DemoTags. • VariableInfo. Fourth and the last one is the scope argument. VariableInfo. Copy and paste the following text in it : <?xml version="1. there is only VariableInfo class returned in the array. which in our case is time. } } Explanation As you can see. We are done with creating Java class files for our JSP tag.com/j2ee/dtds/web-jsptaglibrary_1_1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems.AT_END Variable is visible after end tag. First is obviously the name of the scripting variable that you want to make available.NESTED) }.lang.String". time to declare.//DTD JSP Tag Library 1. Third argument is a boolean value asking if this scripting variable needs to be declared? our answer is yes. public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo("time".0</tlibversion> <jspversion>1.1//EN" "http://java. DemoTag. true. • VariableInfo. This scope argument can be one of the following three types : • VariableInfo.com</uri> <info>Demo Tags Library</info> . Next argument is the type of that variable. "java. } There are four arguments to the VariableInfo constructor. Inc.tld ( Tag Library Descriptor ) file we created in the earlier article.class file.1</jspversion> <shortname>DemoTags</shortname> <uri>http://www.

<tag> <name>secondtag</name> <tagclass>com.TLD file.1//EN" "http://java.stardeveloper.stardeveloper.test.dtd"> <taglib> <tlibversion>1.tag.test.stardeveloper.tag.SecondTag</tagclass> <teiclass>com.SecondTag</tagclass> <teiclass>com.com/j2ee/dtds/web-jsptaglibrary_1_1.tag. How? take a look at following file where firsttag tag definition from the first article has been added on top of secondtag definition : <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems.stardeveloper.test.com</uri> <info>Demo Tags Library</info> <tag> <name>firsttag</name> <tagclass>com. Inc.test.1</jspversion> <shortname>DemoTags</shortname> <uri>http://www.tag.stardeveloper.FirstTag</tagclass> <bodycontent>empty</bodycontent> <info>Your first JSP Tag</info> <attribute> <name>name</name> <required>false</required> </attribute> </tag> <tag> <name>secondtag</name> <tagclass>com.SecondTagTEI</teiclass> <bodycontent>JSP</bodycontent> <info>Your second JSP Tag</info> </tag> </taglib> .//DTD JSP Tag Library 1.SecondTagTEI</teiclass> <bodycontent>JSP</bodycontent> <info>Your second JSP Tag</info> </tag> </taglib> Remember you can add more than one tag definition in one .test.sun.stardeveloper.0</tlibversion> <jspversion>1.tag.

b { font-family:Tahoma. The value of uri attribute in the taglib directive is the complete local address to the .jsp JSP page Create a new . The second one is the secondtag which we have built in this tutorial. see the first article.TLD definition for secondtag is that there is also a tag <teiclass />. which in our case is SecondTagTEI class. Ok we are done with DemoTags. This tag is *required* when you are declaring scripting variables from your JSP tags. I chose "star". Then save it as SecondTag. } b { font-weight:bold. } </style> </head> <body> <p align="center"><em><u>Your second JSP tag : SecondTag</u></em></p> <%@ taglib uri="/WEB-INF/tlds/DemoTags.Explanation To see what each of above tags mean. For example's purpose I assume you placed it in /web/jsp folder. font-size:10pt. <%@ taglib uri="/WEB-INF/tlds/DemoTags. In short there is a Tag Library Descriptor file above with details of two tags.jsp in whatever folder your application server can access. SecondTag.tld" prefix="star" %> . The only thing different you get in the .Sans-Serif.TLD file ( DemoTags. No need to repeat that explanation here. The value of prefix attribute can be anything.tld tag library in our JSP page. <html> <head> <title>Your second JSP tag : SecondTag</title> <style> p.tld" prefix="star" %> <star:secondtag> <p align="center">Date value retrieved from JSP Tag : <%= time %></p> </star:secondtag> </body> </html> Explanation We use JSP taglib directive to import the DemoTags.tld ).tld file. It's value is the complete address of your class which extends TagExtraInfo class.jsp file and copy/paste the following code in it.

To make that JSP tag we had to go through following steps : • Created main SecondTag class which implements Tag interface. But this . • Created SecondTag. click here. Anatomy of a JSP page If you rename a . To see the online demo.Then we write some HTML text to the client between the star:secondtag tags.jsp page will be using default features provided to a JSP page and will not be doing anything useful. • Click here to see the online demo. In our case we returned a single VariableInfo object for our time variable.jsp and you should see the JSP page showing you current date and time. In the <tag> tag. Examining Java Server Pages in detail In this article we will study the anatomy of a JSP page and how you can use each of these elements for your own use. <star:secondtag> <p align="center">Date value retrieved from JSP Tag : <%= time %></p> </star:secondtag> Now run this JSP page using some URL like http://localhost:8080/web/jsp/ SecondTag. We then created a JSP tag which declares single scripting variable time for us.jsp JSP page which called the tag library and showed a live demo for secondtag JSP tag. One other thing to keep in mind is that all JSP pages are compiled to Java Servlet classes. <teiclass> to point to our SecondTagTEI class. • Created SecondTagTEI class which extends TagExtraInfo class and overrides it's getVariableInfo() method to return an array of VariableInfo objects.html file to a . Within the tags we also write the time variable's value out to the user. Summary In this step by step tutorial we learned that scripting variables are page- level variables which are declared and instantiated by JSP tags. so inherently JSP pages are actually Java Servlets. a must if you want to declare variables from JSP tags. It was done for us by the JSP tag which also set it's value to current date and time. we used another tag. A JSP page consists of following parts : • Directives • Scripting Elements • JSP Tags .jsp file then that page is a valid JSP page and will compile and run successfully. See! we neither declared nor initialized the time scripting variable.tld Tag Library Descriptor File. • Created DemoTags.

Following are the different attributes available to you along with the values you can use in your JSP page. If set to false then an exception will be generated on buffer overflow. Default is 8KB. Directives Directives as their name implies are compile time control tags. If this JSP page is the error page where other JSP isErrorPage true | false page's un-handled exceptions will be sent then set it to true. They allow you to customize how your JSP pages are compiled to Java Servlets. interfaces and import importList packages you want to use in your JSP page. Default is true. If set to true. Default is true. There are currently of three types : • Page Directive • Taglib Directive • Include Directive i. otherwise false. info servletInfo Returns info about the JSP page. scripting elements and expressions lie in between the <% and %> tags. If set to true then the JSP engine will send all the requests as they come to the same instance of the isThreadSafe true | false Servlet. If you want to use session then set it to true. . The Page Directive This directive is placed at the top of a JSP page and allows you to customize different features of your JSP page. The URL to the JSP page where all un-handled errorPage pageURL exceptions will be sent. Default language scriptingLanguage is Java. It's syntax is as follows : <%@ page attribute-name="value" %> All JSP directives. Default is true. once buffer is full it will be sent to the autoFlush true | false client. Attribute Value Description The language you are using on the JSP page. A comma separated list of classes. session true | false otherwise false. If false then request will be sent to the Servlet one at a time.We will now take each one of them in detail. Set it to none if you don't want to use buffering or set buffer none | sizeInKB it to a value greater than 8KB. The Java class which your generated Servlet will be extends className extending.

It requires two attributes and it's syntax is as follows : <%@ taglib uri="tag-lib-uri" prefix="tag-prefix" %> The uri attribute contains the location of the tag library TLD ( Tag Library Descriptor ) file... We will learn more about these custom JSP tags in some later tutorial.g.txt" %> </body> </html> Above code adds the copyright info to the current JSP page.g. Default is pageEncoding encodingInfo ISO-8859-1.This is a JSP Comment --%> . Scripting Elements The scripting elements in a JSP page comprise of four types : • Comments • Class level declarations • Expression • Scriptlets Lets look at all of them one by one. Comments Like other Java classes you can add comments in a JSP page. . The Taglib Directive It is used to incorporate custom tags in a JSP page. while prefix is the tag prefix you want to use for your custom tag e. <%@ taglib uri="/WEB-INF/tlds/mytag. Default is contentType content/type text/html. The syntax of JSP comment is as follows : <%-. Comments are useful as it makes your code more understandable. Some HTML and JSP code above <%@ include file="/misc/copyright.tld" prefix="star" %> <star:time /> Above code describes a tag with prefix 'star' which displays current time. The content-type for the current JSP page. It's syntax is as follows : <%@ include file="localOrAbsoluteURL" %> During compilation the content of the file specified in the file attribute will be added to the current JSP page e. iii. Character encoding for the JSP page. The Include Directive The include directive allows insertion of the content of another file into the JSP page at compilation time. i. ii.

ii.Date(). %> Above code first declares a name variable with value of "Faisal Khan" and then displays it to the user screen. Scriptlets Within scriptlets you can add whatever Java code you like. %> Above code declares a class level variable named author with a value of "Faisal Khan".toString() %> Above code displays the current date and time to the user. It's syntax is as follows : <%= statement %> The value of the Java statement is displayed to the user. It's syntax is as follows : <%! Declaration Statement %> For example : <%! String author = "Faisal Khan". <%= new java. We will look into accessing database with JSP in detail in some other article. All this code will go inside the _jspService() method.println("My name is " + name). It's syntax is as follows : <% statements %> For example : <% String name = "Faisal Khan". JSP Tags As we saw earlier we can create and use our own custom tags inside a JSP page using the taglib directive.g. iii. With that there are quite a few standard JSP tags which are part and parcel of the JSP specification and provide really useful functionality : • <jsp:include> • <jsp:forward> • <jsp:param> • <jsp:plugin> . iv. out. Class Level Declarations This feature allows you to add your own class level methods and variables which can be accessed by the scriptlets. so you cannot declare class level methods or variables within scriptlets ( see above ). e. Expression It is a short hand for writing output directly to the output stream.util. If you have been following some of my tutorials on accessing database with Java Servlets then you can just put all that JDBC code inside JSP Scriptlets and it will work.

The <jsp:forward> Tag This tag allows you to forward the control to a given page. Servlet or a simple HTML/text file ).1. The <jsp:param> Tag This tag is used inside the <jsp:include>.e.0 ) you can set the flush attribute to false. <jsp:include page="file.jsp page can access the value of this paramter by : <% String name = request.g. It's syntax is as follows : <jsp:plugin type="bean | applet" code="className" codebase="path to root directory containing classes" align="top | middle | bottom | left | right" archives="jar files required for this app" height="height in pixels" width="width in pixels" hspace="horizontal space in pixels" vspace="vertical space" jreversion="the JRE version required" name="name of object" . i. It's syntax is as follows : <jsp:include page="pathToFile" flush="true | false" /> The page attribute contains the path to the given file you want to include ( which can be a JSP page. file. The <jsp:include> Tag This jsp:include tag allows inclusion of the content of the given file within the JSP page at the request time.g. Like <jsp:include> tag you can also use <jsp:param> to provide parameters to the forwarded page. It's syntax is as follows : <jsp:forward page="pathToFile" /> Where pathToFile is the path to the page you want control to be forwarded to. ii.getParamter("name"). <jsp:forward> and <jsp:plugin> tags.We now look at them one by one.jsp" flush="true" %> <jsp:param name="name" value="Faisal Khan" /> </jsp:include> In the code above a parameter with the name 'name' and a value of "Faisal Khan" has been provided to the included JSP page. In JSP 1. The <jsp:plugin> Tag This tag allows you to embed Java applets or beans in a web page.2 compatible application servers ( e. Flush attribute should be set to true for compatibility with JSP 1. Notice that it is different from the include directive we studied above where the content of the file was included at translation time. It defines and sets different parameters with their values . Tomcat 4. iv. %> iii.jsp. The file.

Summary In this article we briefly had a look at all of the different elements which constitute a JSP page. JDBC. We first learned about three types of directives and then moved forward to learn about four types of scripting elements. Java Bean Tags There is one other small group of tags which allow the incorporation of Java beans in a JSP page. We will look Java beans and bean tags in detail in some other article as this topic deserves some more attention. </jsp:fallback> </jsp:plugin> Almost all the attributes for the <jsp:plugin> tag above are self explanatory. custom tags. . you can move forward to learn about Java beans. In the end we discussed what are built-in JSP tags which are provided to us as part of the JSP specification. Two things that we didn't discuss were : • Custom Tags • Java Beans I deliberately left the above two topics because they deserve more attention and don't worry we will be giving them due attention in my next articles. nspluginurl="URL for Netscape plugin" iepluginurl="URL For IE plugin" > <jsp:params> <jsp:param name="name" value="value" /> </jsp:params> <jsp:fallback> Sorry your browser doesn't support Java applets. This article provides a strong foundation for future JSP articles and once you have understood these simple JSP elements. XML and frameworks for web application architectures.