How to access an object that was created in one servlet from another servlet
I have a problem. Lets say there are 2 servlets: Load() and Process(). During Load(), I want to create and initialize some objects. and During Process(), I want to use those objects for some other things.
Since there is no开发者_开发百科 main class in a servlet (as opposed to desktop programming), I don't think that I can return object created by Load() and pass it as argument to Process() from the main class.
So, how could I create an object in during one servlet call and use/access that object from other servlet?
Use the ServletContext
: getServletContext().setAttribute(..)
Also, consider placing the initialization code and the processing code in one servlet. If you are only having init()
in one of them, and doGet()
in the other, and these objects should be shared only between these two servlets, there is no point of this separation.
Update: if you want to reuse objects in successive requests by the same user (i.e. not initialize them once and use them everywhere), than instead of putting them in the ServletContext
, put them in a smaller scope - the HttpSession
(obtained by request.getSession()
)
Not sure i understand what you mean with Load() and Process(). Servlets are no functions. They are mapped to a certain URL and their service() funktion gets called by the servlet container. More than one servlet can be mapped to an URL and they are called in the order they are defined in the web.xml.
To anser your question: state is normaly stored the the Session object via setAttribute()
You can than access it in the other Servlet via getAttribute().
精彩评论