Solved

Running JSP+Beans under Tomcat

Posted on 2000-05-12
9
496 Views
Last Modified: 2013-11-24
In reference to :

    September 21, 1999 | Gamelan.Com
    Start serving Java Server Pages: Introduction
    by Piroz Mohseni


The example he provided in "Mixing Beans and JSP"
is about getting and setting the State and Rate (TaxRate bean).

I tried running it under Tomcat 3.1 :}. I read all the FAQs and HOWTOs
on setting up a webapp under tomcat but cant seem to
figure out the problem :(. I even tried modifying the jsp
and the beans "patterning" (if there is such a word) from other example files that came with
Tomcat 3.1 beta.

The Error page is giving me :

Error: 500
Location: /myjsp/TaxRate.jsp
Internal Servlet Error:

org.apache.jasper.JasperException: Cannot find any information on property 'State' in a bean of type 'tax.TaxRate'
      at org.apache.jasper.runtime.JspRuntimeLibrary.getReadMethod(Compiled Code)
      at org.apache.jasper.compiler.GetPropertyGenerator.generate(GetPropertyGenerator.java:101)
      at org.apache.jasper.compiler.JspParseEventListener$GeneratorWrapper.generate(Compiled Code)
      at org.apache.jasper.compiler.JspParseEventListener.generateAll(Compiled Code)
      at org.apache.jasper.compiler.JspParseEventListener.endPageProcessing(JspParseEventListener.java:169)
      at org.apache.jasper.compiler.Compiler.compile(Compiled Code)
      at org.apache.jasper.runtime.JspServlet.loadJSP(JspServlet.java:412)
      at org.apache.jasper.runtime.JspServlet$JspServletWrapper.loadIfNecessary(JspServlet.java:147)
      at org.apache.jasper.runtime.JspServlet$JspServletWrapper.service(JspServlet.java:159)
      at org.apache.jasper.runtime.JspServlet.serviceJspFile(JspServlet.java:259)
      at org.apache.jasper.runtime.JspServlet.service(Compiled Code)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:865)
      at org.apache.tomcat.core.ServletWrapper.handleRequest(Compiled Code)
      at org.apache.tomcat.core.ContextManager.service(ContextManager.java:523)
      at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:146)
      at org.apache.tomcat.service.TcpConnectionThread.run(SimpleTcpEndpoint.java:334)
      at java.lang.Thread.run(Thread.java:479)

yes, im sure i configured context info correctly.
can you please at least decode the error for me on what the error means? its greek to me.


my file structure is :

webapps\
     MYJSP\
         TaxRate.jsp
         web-inf\
               classes\
                     tax\
                         Taxrate.class
                         Taxrate.java

hmm.. do I need the "web.xml" in web-inf\ directory?


Thanks in advance.

Stephen


-----SOURCE LISTING------

package tax;

public class TaxRate {

    String State;
    double Rate;

    public TaxRate() {
          this.State = "NY";
          this.Rate = 8.5;
    }

    public void setState (String stateName) {
          this.State = stateName;
    }

    public String getState() {
          return (this.State);
    }

    public void setRate (double rateValue) {
          this.Rate = rateValue;
    }
   
    public double getRate () {
          return (this.Rate);
    }
}

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

<HTML>
<HEAD>
<TITLE>
Tax Rate
</TITLE>
</HEAD>

<BODY>

<%@ page language="java" import="tax.TaxRate" %>

<jsp:useBean id="taxbean" scope="application" class="tax.TaxRate" />

<% taxbean.setState("NJ");
   taxbean.setRate(6.5);
%>

<b> Using method 1:</b> <p>
State is: <%= taxbean.getState() %> <br>
Rate is: <%= taxbean.getRate() %>

<p>
<% taxbean.setState("TX");
   taxbean.setRate(5.5);
%>

<b> Using method 2:</b> <p>
State is: <jsp:getProperty name="taxbean" property="State" />
<br>
Rate is: <jsp:getProperty name="taxbean" property="Rate" />

</BODY>
</HTML>
0
Comment
Question by:ibo
9 Comments
 
LVL 3

Expert Comment

by:Laminamia063099
Comment Utility
Yes, you do need the web.xml in the Web-INF directory.  Other than that, your code looks good.

Laminamia :)
0
 

Expert Comment

by:erlingd
Comment Utility
Works fine with Orion!

But gives that error on Tomcat!

Tomcat is case sensitive
....
<b> Using method 2:</b> <p>
State is: <jsp:getProperty name="taxbean" property="state" />
<br>
Rate is: <jsp:getProperty name="taxbean" property="rate" />
....

See that "state" and "rate" starts with an small letter.
0
 
LVL 3

Author Comment

by:ibo
Comment Utility
its in Caps.. as in "State" and "Rate"
:)
check the code i posted.. again :).
0
 

Accepted Solution

by:
erlingd earned 50 total points
Comment Utility
I made it work under Tomcat 3.1 !
I just used small-caps - as in my posted code!

Orion is case insensitive!
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Expert Comment

by:erlingd
Comment Utility
A little more explanation:

when you use
> property="state"
the JSP engine will find a matching
getState() function!

This is described in:
http://developer.iplanet.com/viewsource/fields_jspcomp/fields_jspcomp.html

....
 Building Your Own JSP Components

By Duane K. Fields and Mark Kolb



--------------------------------------------------------------------------------
Send comments and questions about this article to View Source.
--------------------------------------------------------------------------------


[Editor's note: This article is adapted from a chapter of the book Web Development with JavaServer Pages, to be published in May 2000 by Manning Publications Co. It appears here with the permission of the publisher. More information about this book is available at Manning's web site.]

The JavaServer Pages (JSP) component model is centered on Java software components called Beans, which must adhere to specifications outlined in the JavaBeans API. The JavaBeans API, created by Sun Microsystems with industry cooperation, dictates the rules that software developers must follow to create stand-alone, reusable Java software components. By using JSP's collection of Bean tags, content developers can use the power of Java to add dynamic elements to their pages without writing a single line of code.

This article is written for developers who want to create their own Beans for use as JSP components, and for interested web designers who want to understand how these components are implemented behind the scenes. It is not necessary to understand the details of Beans development to work with JSP. As component architectures go, the interface between JSP and Beans is quite simple, as we will see.

WHAT MAKES A BEAN A BEAN?
So, what makes a Bean so special? You might be surprised to learn that a Bean is simply a Java class that follows a set of simple naming and design conventions outlined by the JavaBeans specification. Beans are not required to extend a specific base class or implement a particular interface. If a class follows the Bean conventions, and you treat it like a Bean, then it is a Bean. A particularly good thing about the Bean conventions is that they are rooted in sound programming practices that you may already be following to some extent. In the next section, we will discuss these conventions and show you how to create your own Beans.
The JavaBeans API
Following the conventions specified by the JavaBeans API allows the JSP container to interact with Beans at a programmatic level, even though the container has no real understanding of what the Bean does or how it works. For JSP, we are primarily concerned with the aspects of the API that dictate the method signatures for a Bean's constructors and property access methods.
Bean Are Just Objects
As with any other Java class, instances of Bean classes are simply Java objects. As a result, you always have the option of referencing Beans and their methods directly through Java code in other classes or through JSP scripting elements. Since they follow the Bean conventions, we can work with Beans without having to write Java code. Bean containers, such as a JSP container, can provide easy access to Beans and their properties. Following the JavaBeans API coding conventions, as we will see, means creating methods that control access to each property we wish to define for our Bean. Beans can also have regular methods like any other Java object. However, JSP developers will have to use scriptlets, expressions, or custom tags to access them, since a Bean container can manipulate a Bean only through its properties.
Class Naming Conventions
You might notice that in most examples Bean classes often include the word Bean in their name, such as UserBean, AlarmClockBean, DataAccessBean, and so forth. While this is a common approach and lets other developers immediately understand the intended role of the class, it is not a requirement in order for a Bean to be used inside a JSP page. Beans follow the same class naming rules as other Java classes: they must start with an alphabetic character, contain only alphanumeric and underscore characters, and be case-sensitive. Additionally, like other Java classes, it is common (but not required) to start the name of a Bean class with a capital letter.
BEAN CONVENTIONS
The Bean conventions are what enable us to develop Beans, because they allow a Bean container to analyze a Java class file and interpret its methods as properties, designating the class as a Bean. The conventions dictate rules for defining a Bean's constructor and the methods that will define its properties.
The Bean Constructor
The first rule of JSP Bean building is that you must implement a constructor that takes no arguments. It is this constructor that the JSP container will use to instantiate your Bean through the <jsp:useBean> tag. Every Java class has a constructor method that is used to create instances of the class. If a class does not explicitly specify any constructors, a default zero-argument constructor is assumed. Because of this default constructor rule, the following Java class is perfectly valid and technically satisfies the Bean conventions:
public class DoNothingBean { }
This Bean has no properties and cannot do or report anything useful, but it is a Bean nonetheless. We can create new instances of it, reference it from scriptlets, and control its scope. Here is a better example of a class suitable for Bean usage; it has a zero-argument constructor that records the time of its instantiation:
public class CurrentTimeBean {
   private int hours;
   private int minutes;

   public CurrentTimeBean() {
      java.util.Date now = new java.util.Date();
      this.hours = now.getHours();
      this.minutes = now.getMinutes();
   }
}
In this example, we have used the constructor to initialize the Bean's instance variables hours and minutes to reflect the current time at instantiation. The constructor of a Bean is the appropriate place to initialize instance variables and prepare the instance of the class for use. Of course, in order for it to be useful within a JSP page, we will need to define some properties for the Bean and create the appropriate access methods to control them.
The Magic of Introspection
You may be wondering how the JSP container can interact with Bean objects without the benefit of a common interface or base class to fall back on. Java manages this little miracle through a process called introspection that allows a class to expose its properties on request. The introspection process happens at run time, controlled by the Bean container.
One way that introspection can occur is through a mechanism known as reflection, which allows the Bean container to examine any class at run time to determine its set of properties. The Bean container determines what properties a Bean supports by analyzing its public methods for the presence of property access methods that meet criteria defined by the JavaBeans API. For a property to exist, its Bean class must define an access method to return the value of the property, change the value of the property, or both. It is the presence alone of the specially named access methods that determines a Bean class's properties.

Specifying a Bean's Properties
As we have mentioned, a Bean's properties are defined simply by creating appropriate access methods for them. Access methods are used to either retrieve a property's value or make changes to it. A method used to retrieve a property's value is called a getter, while a method that modifies its value is called a setter. Together these are generally referred to as access methods - they provide access to values stored in the Bean's properties.
To define properties for a Bean, simply create a public method with the name of the property you wish to define, prefixed with the word get or set as appropriate. A getter method should return the appropriate data type, while the corresponding setter method should be declared void and accept one argument of the appropriate type. It is the get or set prefix that is Java's clue that you are defining a property. The signature for property access methods, then, is as follows:

public void setPropertyName(PropertyType value);
public PropertyType getPropertyName();
For example, to define a property called rank, which can be used to store text and is both readable and writeable, we would need to create methods with these signatures:
public void setRank(String rank);
public String getRank();
Likewise, to create a property called age that stores numbers:
public void setAge(int age);
public int getAge();
Making your property access methods public is more than a good idea, it's the law! Exposing your Bean's access methods by declaring them public is the only way that JSP pages will be able to access them. The JSP container will not recognize properties without public access methods.
Conversely, if the actual data being reflected by the component's properties is stored in instance variables, it should be intentionally hidden from other classes. Such instance variables should be declared private, or at least protected. This helps ensure that developers restrict their interaction with the class to its access methods and not its internal workings. Otherwise, a change to the implementation might negatively affect code that is dependent on the older version of the component.
 

Let us revisit our previous example and make it more useful. We will add a couple of properties to our CurrentTimeBean, called hours and minutes, that will allow us to reference the current time in the page. For Java to recognize the existence of these properties, they will have to follow the getter method signatures defined by the JavaBeans design patterns. These methods should therefore look like this:

public int getHours();
public int getMinutes();
In our constructor, we store the current time's hours and minutes in instance variables. We can have our properties reference these variables and return their values where appropriate:
public class CurrentTimeBean {
   private int hours;
   private int minutes;

   public CurrentTimeBean() {
      java.util.Date now = new java.util.Date();
      this.hours = now.getHours();
      this.minutes = now.getMinutes();
   }

   public int getHours() {
      return hours;
   }

   public int getMinutes() {
      return minutes();
   }
}
That's all there is to it. The two methods simply return the appropriate values as stored in the instance variables. Since these methods meet the Bean conventions for naming access methods, we have just defined two properties that we can access through JSP Bean tags. For example:
<jsp:useBean id="time" class="CurrentTimeBean"/>
<HTML>
<BODY>
It is now <jsp:getProperty name="time" property="minutes"/>
      minutes past the hour.
</BODY>
</HTML>
Properties should not be confused with instance variables, even though instance variables are often mapped directly to property names. Properties of a Bean are not required to correspond directly with instance variables. A Bean's properties are defined by the method names themselves, not the variables or implementation behind them. This leaves the Bean designer free to alter the inner workings of the Bean without altering the interface and collection of properties exposed to users of the Bean.
As an example of dynamically generating property values, here is a Bean that creates random numbers in its property access methods instead of simply returning a copy of an instance variable:

public class DiceBean {
   private java.util.Random rand;
   
   public DiceBean() {
      rand = new Random();
   }

   public int getDieRoll() {
      // return a number between 1 and 6
      return rand.nextInt(6) + 1;
   }
   
   public int getDiceRoll() {
      // return a number between 2 and 12
      return getDieRoll() + getDieRoll();
   }
}
In this example, our dieRoll and diceRoll properties are not managed by instance variables. Instead, we create a java.util.Random object in the constructor and call its random number generator from our access methods to dynamically generate property values. In fact, nowhere in the Bean are any actual static values stored for these properties - their values are recomputed each time the properties are requested.
You are not required to create both getter and setter methods for each property you wish to provide for a Bean. If you wish to make a property read-only, define a getter method without providing a corresponding setter method. Conversely, creating only a setter method specifies a write-only property. The latter might be useful if the Bean uses the property value internally to affect other properties but is not a property you want clients accessing directly.

Property Name Conventions
A common convention is that property names are mixed-case, beginning with a lowercase letter and uppercasing the first letter of each word in the property name. For the properties firstName and lastName, for example, the corresponding getter methods would be getFirstName() and getLastName(). Note the case difference between the property names and their access methods. Not to worry: the JSP container is smart enough to convert the first letter to uppercase when constructing the target getter method. If the first two or more letters of a property name are uppercased - for example, URL - the JSP container assumes that you really mean it, so its corresponding access methods would be getURL() and setURL().  
....
0
 
LVL 7

Expert Comment

by:Ravindra76
Comment Utility
WOW. What a long explanation ??

:) :) ;)
0
 
LVL 3

Author Comment

by:ibo
Comment Utility
ok ok sorry erlingd, i thought u were saying the code i posted is in small caps and i should make it in Caps ").
i made it work now.. thanks to you :).
btw, laminamia, i was able to make it work w/o the web.xml.. maybe i dont need it for this example :).
im just wondering why those fieds  (State, Rate) should be lowercase (in jsp) since Java in particular, is case-sensitive. The declaration inside the bean (class file) is, it is in Caps (first letter)... "State" and "Rate".

thx for the additional info but i already have that article "Building Your Own JSP Components" hehe.. i just havnt read it yet :).
0
 

Expert Comment

by:erlingd
Comment Utility
Sorry about the long explanation - me and my mouse can't make that "Cut'n paste" work ;)
0
 

Expert Comment

by:jimjamjoh
Comment Utility
I'm having the exact same error using Tomcat 3.1.  It's sporadic, however, and appears to have something to do with server caching, though I haven't tracked it down as yet.  If you copy the code to a different class name (and edit your .jsp file to reference the new classname), you might find the code works fine...also, if you change the "id" attribute in your "useBean" codepiece (and it's corresponding "name" attributes in the "setProperty" and "getProperty" codepieces), you might find it displays properly...

This is a FRUSTRATING error...
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Java virtual machine monitoring tools 3 39
topping2 challenge 13 55
unix in java example 9 37
advertisement module in core php 4 79
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now