Reputation: 11
I have several jsp pages which all have a javabean in them with scope="application". The first called page instantiates the object (let's call it obj1) and all the pages share it from then on (great!).
However, I also have some Servlet Mappings to that class. Whenever one of these calls is made, a second instance of that class is instantiated (call this one obj2). Further calls using the particular servlet-mapping are serviced by obj2.
How can I get Tomcat to use obj1 to handle the servlet mapping calls?
Upvotes: 1
Views: 4054
Reputation: 1108722
You need a ServletContextListener
to create it.
@WebListener
public class Config implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("data", new Data());
}
// ...
}
This way you can grab it in every servlet as follows
Data data = (Data) getServletContext().getAttribute("data");
// ...
And access in every JSP as follows
${data}
Note that you do not need the old fashioned <jsp:useBean>
tag for this all.
Upvotes: 2
Reputation: 7716
Based on your comment, your approach is wrong, servlets are not made to be used as a bean in an application. Sevlets act as the controller in the mvc pradigm and your application bean is part of the model. So you are coupling your controller with your model which is not good. Moreover, what you are trying to do simply doesn't work as you can see. See BalusC's answer for the correct implementation.
Upvotes: 0
Reputation: 15446
The question is not very clear. If you question is
How to make tomcat you the application created instance for servlet. This is the answer!
No the application cannot tell the container to use some application created instance as a servlet. The container will create the object and destroy on its own.
Upvotes: 0
Reputation: 9943
I think you will have to post parts of your web.xml file to get this solved, but if you are getting two instances of the same bean in the same application then it by definition is not application scoped.
Can you show us what your servlet mapping references look like? I suspect that they are being invoked in such a way that the context is different so the container doesn't see both references as being in the same application. It is either that or the bean's scope is not being declared correctly.
Upvotes: 0