I have a servlet in my program, which receives messages from clients. The servlet instantiates a parser, which reads the messages and invokes other objects. The problem is that, the "other objects" I mentioned have already been instantiated, and I have to pass them as parameters to servlet, but I can't. Because the container handles the servlet instantiation.
To visualize it:
public class ClientListenerServlet extends HttpServlet { //.. public void doPost(HttpServletRequest req, HttpServletResponse resp) { //.. Parser p = new Parser(); p.parse(message); //..etc } //.. }
public class Parser() { public void parse(String s) { otherObject.doSomething(); // ==> I can't pass otherObject as parameter to Parser and Servlet } }
One idea is to use the ServletContext (sort of 'global variable' storage for your servlet....anyway).
You can set attributes in this, just like with the request, and access them anytime in the servlet. This way you can make the "other objects" parmeters to the Parser (or inject them via setters), that you get out of the context along with grabbing the message:
example:
public void doPost(HttpServletRequest req, HttpServletResponse resp) { // for thoroughness ;) .. HttpSession session = req.getSession(); ServletContext context = session.getServletContext(); OtherObject other = (OtherObject) context.getAttribute("other");
// note no binding of parser to context
Parser p = new Parser(); p.setOtherObject(other); p.parse(message); //..etc }
... and Parser ...
public class Parser { this.other; // ...
public void setOtherObject(OtherObject other) { if (null != other) { this.other = other; } }