I have my business logic in the service(HttpServletRequest request, HttpServletResponse response) method, when my serlvet is loaded automatically when Weblogic restarted, I want to call the service() method automatically. The reason I have my logic in the service() method instead of init() is I want to be able to run it manually from the Web as well.
how do I call service() from within the init() method please?
You can't. There may be no request happening when the init() method is called.
But it sounds like you just have code in the wrong place. If you have code in the service() method which should be run when the init() method is run, that just means that code should be in the init() method.
1. No no no no no you have the wrong idea
2. Put your business logic that must be called on initialization in a separate method, preferably in a separate class which can be tested outside the servlet environment. You can call that from init. Really, I'm serious about this - test outside the servlet environment if at all possible.
3. Do NOT modify the service method, for a web application extend HttpServlet with your custom class.
4. Provide for calling this magic method from doGet or doPost - suitably protected.
Joined: Jan 24, 2008
Thanks. I will put my business logic in a separate method/class and call it from init() and doGet(). Inside my business logic, I need to pass in HttpSession object
I can get it easily from doGet since I have the HttpServletRequest object already and I can get it as below
HttpSession session = request.getSession(true);
How do I get the HttpSession from init(ServletConfig config);
Ong Vua wrote:Thanks. I will put my business logic in a separate method/class and call it from init() and doGet(). Inside my business logic, I need to pass in HttpSession object
You can't have it both ways. Either this "business logic" has to be done once when the servlet is initialized, or it has to be done every time there is a request. If it's the former, call it from init(). If it's the latter, call it from service().
If it's something else, then you should explain the actual requirements.
Joined: Jan 24, 2008
Basically what this business logic does is very simple
1) Create a Quartz scheduler
2) Schedule a job
3) Start the scheduler
I want to store the Scheduler object in a session of some sort so every subsequent calls (via doGet), it will just get the existing Scheduler instead of creating new one. That's why I'm thinking of storing it in the HttpSession object. I did some more research and there's another object which is ServletContext that I can set attributes on. I can get this one via both init() and doGet(). I might use this ServletContext to store my Scheduler since this Scheduler object is not specific to each user session. Everyone will use the same Scheduler object.
What do you think? Or there's a better way that you can recommend?