• Post Reply Bookmark Topic Watch Topic
  • New Topic

jsp:useBean Vs importing class file and using new

 
Gandhi Anil
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I write a java class named myClass file and it has a method myMethod.
I want to call myMethod from jsp. I believe, we can do it using two ways.
1. I use <jsp:useBean id="myC" class="com.myClass" scope="session" />
and
<%
myC.myMethod();
%>

2. Another way I can call the class is

<%@ page import="com.myClass">
<%
myClass myC=new myClass();
myC.myMethod();
%>

When I run my JSP using first point 1, it runs fine, where as if I use point 2 (above) it fails with stack trace : value is null.

Can someone tell what is the difference between two approaches, which is better (provided there is solution to fix approach 1) of the two.

Thanks
Anil
 
Atul Prabhu
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anil,

In case of the first one <jsp:usebean>
if(object is not present in scope)
{
create a new object.
}
else
{
returns the object from the specified scope(by default request)
}

Where as in the second case u just create the object irrespective whether u have created it in the other jsp page.

Obviously the first one is better.
 
Anil Gandhi
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Atul,

Thanks for ur answer, it is good, I am still wondering why should the first approach give me null as the output with stack trace whereas when same bean is used in JSP using new, it works fine. any clues..

regards
Anil


Originally posted by Atul Prabhu:
Hi Anil,

In case of the first one <jsp:usebean>
if(object is not present in scope)
{
create a new object.
}
else
{
returns the object from the specified scope(by default request)
}

Where as in the second case u just create the object irrespective whether u have created it in the other jsp page.

Obviously the first one is better.
 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Anil,

I had a quick play with your examples and came up with the following:

My JSP

My Bean

As far as I can see, both methods work fine, though option 1 is more JSP, less Java. There is a minor syntax error in your posting which, in my Tomcat 5, causes a compilation error in the JSP (Unterminated page tag). If you were getting an error other than that it may be due to something in your bean method as there's nothing wrong with the JSP in principle.

Check out my code - it should run "as is", to see if you get the same problem.

Regards

Jules
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!