• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Acessing the Java API through JSP

Fabio Fonseca
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello, guys!
I�m a total N00B trying to get more information that any human head can handle. Everything was turning out alright until I had to create a random banner to my company.

What I did was:

<jsp:useBean id="random" class="java.util.Random">
<jsp:setProperty name="random" property="nextInt"/>
<c:set var="bidresult" value="${random.nextInt}"></c:set>

Is it even possible to do something like that? What I cant really grasp is: what do I do in order to access something from the java api using JSLT and EL?

p.s. What I was trying to accomplish with the last code was this:

<% int random = (int)(Math.random() * 2 + 1); out.println(random); %>
Thanks a lot!
[ January 19, 2006: Message edited by: Fabio Fonseca ]
Bear Bibeault
Author and ninkuma
Posts: 65275
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Fabio, welcome to the Ranch.

The EL was specifically designed not to be a general programming language and as such has purposeful limitations on the type of access it can perform. It, along with the JSTL, is clearly designed to move JSP authors along to a place where JSPs serve as the "view" portion of an application leaving any processing to be factored out into servlet controllers and/or beans.

One limitation you are running against is that the EL is specifically geared towards accessing elements of the Java Collection classes and objects that are patterned using the JavaBean conventions.

java.util.Random is none of those things.

The notation ${random.nextInt} will, since random is not a Collection or a Map, try to access the getNextInt() method of the object. And of course, that method does not exist. There is no means in the EL to make calls to general-purpose methods such as those exposed by java.util.Random.

I strongly recommend reviewing the EL portion of the JSP 2.0 Specification to become more familiar with the access mechansims of the EL.

Which is not to say you cannot do what you want to do. You've just got to start thinking in a more JSP 2.0-esque way.

Approaches I would consider:

1) Wrap the java.util.Random functionality in a class that follows the JavaBean convention so that the functionality you desire is exposed in an EL-friendly manner.

2) Perform the processing in the servlet controller for the JSP page. This assumes a Model 2 patterned application (which I strongly endorse).

3) Create your own custom action to do whatever you want.

4) Create an EL function to do whatever you want.
[ January 19, 2006: Message edited by: Bear Bibeault ]
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic