Back to the Web Developer's Journal Main Page
internet.com
side nav bar

A detailed look at building JSP pages. Should you use JSP or servlets? It mainly depends on the ratio of markup to code. Here you'll also find a guide to the different varieties of tag, and details about the main tags such as <jsp:useBean> and <jsp:setProperty>.
Java Articles at the Web Developer's Journal - Java programming tutorials, applets, beans, servlets and more.
Back to the Web Developer's Journal Main Page
internet.com
side nav bar










We've tried to assemble a collection of articles about Java to help the beginner or the real Java gurus. If you have questions (or answers) concerning Java, please visit our Java Discussion Group.

HOW DID THEY DO THAT???

Find out in:
Amazing HTML



Site Map


Jobs at webdeveloper.com
Check out our Web-based
Discussion Groups:

Check out and join our email-based Mailing Lists for Web developers.

Ask the JavaScript Weenie:

For news and reviews of the latest computer audio tools, visit: The Tapeless Studio
Java Resources for Web Developers

Java Hub

If you have questions about Java development you have arrived at the right place. Scroll down for articles about servlets, product reviews and "how to do it" articles. We also maintain a Java discussion group.

 In This Section

 Java

  • Taking Notes on Java
    Edward Tanguay sings the praises of a very important language.

  • The Bluffer's Guide to Java
    Can't tell your Beans from your Applets? Wondering if a Servlet is a small server waiting to grow up? Read our compact guide to Java and you'll soon be dropping JAR, JVM and JSDK into casual conversations along with the best of them. Nobody will bother listening to you, but they'll still be mightily impressed.


  • Java: Coming to a TV near you!
    The new Java TV API holds the promise of Java-based interactive television using set-top boxes.


  • Java vs Other Web Application Technologies
    (The JavaBoutique) Selena Sol, author of JavaBoutique's Introduction to Java, gives an in-depth comparison of Java and other development languages such as dHTML, ASP, and Perl.
  • Agent Communication
    Agent technology is becoming more prevalent as the availability of network access, and the demand for the end-uses of agents, become greater.

  • Java Web Server in Brief
    A simple, dependable, and inexpensive ecommerce solution for small businesses is proposed.


  • JD WorkShop vs Cafe
    Two Java Tools Compared

 Java Server Pages

  • JSP: The Back Door into Java
    Edward Tanguay discovers JSP, and finds it finally allows him to put his theoretical knowledge of Java to use, and hence, get a foot into the Java programming world.

  • Building Java Server Pages
    A detailed look at building JSP pages. Should you use JSP or servlets? It depends on the ratio of markup to code. Here you'll also find a guide to the different varieties of tag, and details about the main tags such as <jsp:useBean> and <jsp:setProperty>.

  • Site User Logon with XML, Java Beans and JSP
    During this tutorial we will use XML and Java Server Pages to verify a user's logon - and then store the results in a session Java Bean for easy access.

  • Serving Dynamic WAP Content with Java Server Pages
    Here's how to create dynamic content for WAP-enabled mobile phones using the Wireless Markup Language (WML) and Sun Microsystems' Java Server API. Our Java Server Pages application displays regularly updated appointment data for someone on the move, such as an appliance engineer making house calls.

  • Object Persistence Made Easy
    With object serialization, your Java applets and applications can save and load the state of objects to disk or over a network. In this article, we'll examine the benefits of object serialization, and how to implement it in your own programs.

 Servlets

  • Intro to Servlets
    Java servlets are making headlines these days, claiming to solve many of the problems associated with CGI and proprietary server APIs. In this article I will describe the overall servlet architecture and what you need to develop your application with servlets. I will use several code examples to show you how to use the Servlet API, and compare it with CGI and proprietary server APIs where appropriate.

  • Internationalizing Servlets
    How to use the Java Internationalization API to build server-side code that alters its output based on the location and language of the user. We demonstrate the use of the API by building a simple method which displays a product entry for a shopping cart application.

  • Using the HttpSession object of the Servlet API
    The Java Servlet API represents an elegant and powerful way to shift processes from client to server, and offers a number of advantages over CGI. These advantages have certainly been enumerated so that most developers are aware of the servlet advantage. However, some of the details of the servlet architecture may at first seem daunting. Here's a short introduction on one aspect of writing servlets: the HttpSession object.

  • Improved Performance with a Connection Pool
    Establishing a connection once and then using the same connection for subsequent requests can dramatically improve the performance of a database-driven Web application. Since Servlets can keep information between requests, a database connection pool is a straightforward solution.

  • Servlets Are for Real!
    Servlets are on duty now at a Web site near you.

  • Netscape-Flavored Servlets
    How to implement server-side Java using Netscape's implementation of Java within the Enterprise Server.

 Java Discussion Group

  • Java Discussion Group
    Test the experts who hang out here with your toughest Java questions. You can also sign up for our Java E-mail Discussion List.
 

 

 Archive



Back to the Web Developer's Journal Contact WDJ   •    Suits!   •    Propheads!   •    Ponytails!
Discuss   •    Subscribe   •    Search

Be a Commerce Partner                       
HOW DID THEY DO THAT???

Find out in:
Amazing HTML



Site Map

Jobs at webdeveloper.com


Check out our Web-based
Discussion Groups:

Check out and join our email-based Mailing Lists for Web developers.


Developer Channel
FlashKit
Jobs.webdeveloper
JavaScript.com
JavaScriptSource
JustSMIL
ScriptSearch
Streaming Media World
WebDeveloper.com
WebReference
XMLFiles
WDVL
Discussion Groups Book Reviews Software Reviews Download Web Tools

Getting To Grips With JSP

Building Java Server Pages

by Mark Webber

If you've ever used Microsoft's very popular Active Server Pages (ASP) then you'll have a good idea of what JSP is. It consists of HTML or XML markup into which special tags and code blocks are inserted. The code is executed on the server and the result is a dynamic page that is returned to the client browser. Although JSPs are simple to build they have at their disposal the full power of object-oriented Java and the Java Server API. JSPs make heavy use of Java Beans, which are classes that follow a standard pattern of a no-argument constructor (required in JSPs) and public GET and SET methods.
May 24, 2000

A JSP is first parsed into a java source file which is then compiled into a servlet class. This occurs when the page is first requested, so there is a performance hit at that point. But if you design your JSP carefully the performance of the class, once compiled, should be equal to that of a purpose-built servlet. It is possible to view the servlet source code that is generated by the parser, but it's not recommended that you alter it.

JSPs are supported by a wide number of web servers through the use of plugins or modules. One of the best implementations so far is that developed for the Apache web server (see http://jakarta.apache.org). The Sun Microsystems Java Server Web Development Kit (JSWDK) available from http://java.sun.com contains all you need to start developing JSPs and servlets, including a JSP parser and a simple HTTP server. The API is undergoing constant development and this article is based on version 1.0.1.

JSP vs. Servlets

There are both advantages and disadvantages when using JSP in place of servlets, and the decision concerning which to choose is sometimes difficult, especially if you don't start out with a good idea of how the page is going to develop.

A basic consideration is the ratio of markup to code: the more markup the greater the case for a JSP, and the more code the greater the case for a servlet. By "code" here I am referring to that which is used in outputting page content such as loops and conditionals that surround blocks of HTML. This sort of code cannot be locked away inside a bean, whereas much else can. In fact it is a design goal of JSP development to keep as much code as possible out of the page and in a bean or other class which is then referenced in the page. The code sections of a JSP can quickly become unmanageable and difficult to debug, especially since the compiler is working on the generated ".java" source file and not directly on the JSP. But for a page with simple server-side functionality, such as altering output based on a few request parameters, a JSP can be much simpler and quicker to build than a servlet.

An advantage of JSPs is that they can be given to web designers who are not Java programmers. As long as they are careful they can load the JSP into a design tool to change the HTML. This may be preferable to altering a servlet source file which has multiple calls to out.print() or functions that append() to StringBuffer objects. Much is made these days of the separation between presentation and business logic, and JSPs can help enforce this model throught their use of component beans.

One brief point before we continue: every JSP contains implicit references to API objects that do not need to be declared. They are:
request
response
pageContext
session
application
out
config
page
exception

The Different Varieties of Tag

Let's begin by looking at the different kinds of tag that can be found in a JSP.

DIRECTIVES

Directives are instructions that are processed when the page is compiled. They begin with <%@ and end with %>. Examples are the <%@ page %> and the <%@ include %> directives.

HIDDEN COMMENTS

These are used to document the page and are not sent to the client. The form is <%-- comment --%>. Any characters may be used in the body of the comment except the closing "--%>" marker which should be escaped as "--%\>".

DECLARATIONS

These are used to declare variables or methods that have scope throughout the page. The opening tag is <%! and the closing tag is %>. For example:

<%! String strMyString = "hello";

private void doSomething() {
//
}
%>

EXPRESSIONS

The result of an expression is cast to a String and inserted into the output stream at the place where it occurs. The form is <%= expression %>. For example:
<%= strMyStringVariable %>
<%= getData() %>
Note that the expression is not terminated with a semicolon. This is because the parser simply wraps an out.print() or similar around the expression, and a colon will produce a compiler error (the second example would be parsed to "out.print(getData(););", which is invalid). The expression can appear anywhere within the HTML of a page. For example:

<INPUT TYPE="TEXT" NAME="COUNTRY" VALUE="<%= strCountry %>">

Expressions can sometimes be used as attribute values within JSP elements. You should consult the API reference for details.

SCRIPTLETS

Scriptlets are code fragments that can contain any valid code enclosed between <% and %>. Code here can access any declared variable or bean, and is executed at request time. A typical use of a scriptlet is to wrap a conditional or a loop around a block of HTML. An example:

<% if(request.getParameter("user").equals("new")) { %>
<B>Please sign up!</B>
<% } else { %>
<B>Welcome back!</B>
<% } %>

The output will vary depending on the value of the request parameter. Note the use of the implicit request object which does not need to be declared. Here is an example that combines scriptlets and expressions:

<% for(int i=1; i<11; i++) { %>
The current number is: <%= i %><BR>
<% } %>

ACTIONS

There are also a number of XML-type tags that begin with "<jsp:" and are sometimes called "actions". Some of these will be explored below.

The Main Tags

Rather than exhaustively list all tags and attributes we will instead focus on some of the main aspects. In fact, if you consult Sun's JSP documentation, you may be surprised at how just little there is to the API.

<%@ page %>

At the top of each JSP is the page declaration. Here is an example:
<%@ page
language="java"
import=". . ."
errorPage=". . ."
contentType=". . ."
%>

At present only the Java language can be used in a JSP, so the language attribute should be as shown. The import attribute contains a comma-delimited list of packages or classes to import for the compiler. The errorPage attribute is interesting - it is the path to a page to which the client is redirected when an exception occurs. The error page can use the built-in exception object to decide what to display to the user. The contentType attribute is self-explanatory.

<jsp:useBean> and <jsp:setProperty>

Here is an example of how to set up a bean instance in a JSP:

<jsp:useBean
id="beanInstanceName"
scope="page|request|session|application"
class=". . ."
>
<jsp:setProperty
name="beanInstanceName"
property="propertyName" value="theValue"
/>
</jsp:useBean>

The JSP engine will look for a bean instance that matches the scope. If it cannot find one it will instantiate a new one using the no-argument constructor. The id attribute is the name of the variable to use for referencing the bean within the page. The scope attribute is very important and has the following values:

page

The bean can be used within the page until the client response is sent.

request

The bean can be used in any JSP that is processing the same request.

session

The bean can be used in any page that participates in the client session.

application

The bean can be used in any page in the current application.

One important use of beans is to store data between client requests. Depending on the usage, if you do not set the right scope attribute you may produce an unecessary performance hit. An example is a bean that contains a HashMap of data that is fetched from an updated file every few minutes, such as an FTP news headline or stock price feed. The scope of the bean should be set to "application" for optimal performance, since a new instance is not required for each client request.

The <jsp:setProperty> is used to set the value of a bean property using its SET methods. A useful shortcut is to use an asterisk for the property attribute: property="*". This will take all of the client request parameters which have the same name as a bean property and set them all in one go, performing type conversion if necessary.

<jsp:getProperty>

This tag retrieves the value of a bean property and displayes it in the page. However it cannot handle indexed bean properties. The format is:
<jsp:getProperty name="beanInstanceName" property="propertyName"/>
The name atribute points to the bean with the same id attribute in the <jsp:useBean> tag, and the property attribute is the name of the bean property you wish to display (it must have a corresponding GET method in the bean).

<%@ include %>

This directive inserts the contents of a file into the JSP at compile time. The text becomes part of the JSP page. It is useful for including code that is common to a number of pages, but for which you do not want to use a bean. The format is:
<%@ include file="relativeURL" %>

<jsp:include>

This tag is used to include either static or dynamic content in the output stream. If the file is dynamic, you can use the <jsp:param> tag to pass parameters to it. For example:

<jsp:include page="/login.jsp">
<jsp:param name="username" value="Fred"/>
</jsp:include>

It is important to distinguish between the <jsp:include> tag and the <%@include %> directive. The former is for including content at request time, whereas the latter should be used for static content at compile time.

<jsp:forward>

This tag takes the implicit request object (which contains the client request parameters and other CGI-type data) and forwards it to a target file which can either be an HTML page, a servlet, or another JSP file. The target must be in the same application context. For example:
<jsp:forward page="relativeURL|<%= expression %>">
<jsp:param name=". . ." value=". . ."/>
</jsp:forward>
The <jsp:param> tag is used to pass additional parameters to the target. Note the way in which the tag is closed at the end - this is standard XML. This <jsp:forward> is also an example of a tag that can contain an expression as a part of it.

Java Server Pages are a simple yet powerful way of developing dynamic server-side applications, and are rapidly becoming the system of choice for many web developers due to their ease of use and their separation of presentation and functional logic through the use of bean components.

Links

There are two very useful pieces of documentation currently at http://java.sun.com/products/jsp/. The first is the detailed Syntax Reference Guide which covers most of the tag details. The second is the JSP Syntax Card which is available as a PDF document. I always keep a printed copy of this to hand when I am coding JSP.



Mark Webber is a Web Developer with Demon Internet, a brand of Thus plc. He is a Sun Certified Java Programmer.
Back to the Web Developer's Journal
Contact WDJ   •    Suits!   •    Propheads!   •    Ponytails!
Discuss   •    Subscribe   •    Search


internet.com

IT | Developer | Internet News | Small Business | Personal Technology | International | Search internet.com | Advertise | Corporate Info
Newsletters | Tech Jobs | E-mail Offers

internet.commerce
Be a Commerce Partner                                
  

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers