Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can anyone tell me how i could refe

Status
Not open for further replies.

blues77

Programmer
Jun 11, 2002
230
CA
Can anyone tell me how i could reference a javabean in a servlet? basically i have a bean that calculates the total of some purchases and i want to use this bean in a servlet. Any suggestions?
 
Well the most difficult part of that is the CLASSPATH type of issues. In other words getting the bean (class/jar) file in the proper location under the Web Server to be visible to the Server Engine and Servlet.

After that you just use it as you would any Java class in your Servlet code:

MyBean mb = new MyBeen();
.... etc.

-pete
 
Hi blues77:

It also depends on what type of bean are you trying to instantiate. For example, if you want to instantiate a session bean, you shouldn't create one every time, only if it hasn't been created, depending on the scope. Here is an example:
Code:
YourSessionBean yourSessionBean = null;
synchronized (session) {
        yourSessionBean = (YourSessionBean)
        pageContext.getAttribute("yourSessionBean",PageContext.SESSION_SCOPE);
        if ( yourSessionBean == null ) {
                try {
                        yourSessionBean = (YourSessionBean) Beans.instantiate(
                                                                getClassLoader(), 
                                                                "YourSessionBean"
                                                                );
                }catch (Exception exc) {
                        throw new Exception(" Cannot create bean of class YourSessionBean \n"+exc);
                }
                pageContext.setAttribute("yourSessionBean", 
                                        yourSessionBean, 
                                        PageContext.SESSION_SCOPE
                                        );
        }
}

Note that YourSessionBean is a bean and yourSessionBean is an instance of that bean.

For a stateless Bean the process would be different.

Hope it helps. Pedro Andrés Solorzano
Pontificia Universidad Javeriana
Bogotá, Colombia, SurAmérica.

Let me know if this post have actually helped you, by clicking the purple star.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top