tags:

views:

77

answers:

1

I am working on a preexisting web application built with JSP, which uses an external Java library. I want to make some JavaBeans that were instantiated with jsp:useBean tags available to the Java code.

What would be a good practice to do that? I suppose I can pass the objects in question to every function call that requires them, but I'd like to avoid that.

+1  A: 

Application scoped objects are stored as attributes of the ServletContext. If the "function call" has access to the ServletContext, then it can just grab them as follows:

Bean bean = (Bean) servletContext.getAttribute("beanname");

I of course expect that the "function" is running in the servlet context. I.e. it is (in)directly executed by a servlet the usual way.

BalusC
Actually, I don't think it is. The appropriate classes are imported in the JSP (via `<%page import%>` directives), and called. How can they run in a servlet context?
FrontierPsycho
Ouch, poor practice. Anyway, the servlet context is available in JSP *scriptlet* as well by the implicit `application` reference. E.g. `<% Bean bean = (Bean) application.getAttribute("beanname"); %>` and so on.
BalusC
So what you're saying is that I have to pass the Bean to the function, unless I redesign the application. :) In brief, how would I correct the design?
FrontierPsycho
Either pass bean or `ServletContext` to function, yes. As to correcting the design, don't do that on existing webapps. It's a waste of time. As to how to design properly, check the "front controller pattern" and "MVC pattern". This site brings you step by step in a correct manner to a good MVC approach: http://courses.coreservlets.com/Course-Materials/csajsp2.html
BalusC
I am familiar with MVC design, I just don't know how to implement it in JSP. Unfortunately this app was given to me as is. Thank you for the help!
FrontierPsycho