I\'m trying to create a web user interface for a Java application. The user interface is going to be very simple, consisting of a single page with a form for users to pose t
To expand in this point. When implementing JSPs, there are two models refered to as (with some inventiveness) as Model 1 and Model 2. See this explanation.
In the case of model 1 you tend to put code directly into the JSP, it's acting in a controller role. Persoanlly, even when dealing with small, quickly developed apps, I do not so this. I always use Model 2. However if you choose you can just put some Java into your JSP.
<% MyWorker theWorker = MyWorkerFactory.getWorker();
// theWorker.work();
%>
I woudl favour having a factory like this so that you can control the creation of the worker. The factory would have something like (to give a really simple example)
private static MyWorker s_worker = new MyWorker();
public static synchronized getWorker() {
return s_worker;
}
Alternatively you could create the worker when that method is first called.
In the case of model 2 you naturally have a servlet into which you are going to put some code, so you can just have
private MyWorker m_worker = MyWorkerFactory.getWorker();
This will be initialised when the servlet is loaded. No need to worry about setting it to load on startup, you just know that it will be initialsed before the first request is run. Better still, use the init() method of the servlet. This is guranteed to be called before any requests are processed and is the servlet API architected place for such work.
public class EngineServlet extends HttpServlet {
private Engine engine;
// init is the "official" place for initialisation
public void init(ServletConfig config) throws ServletException {
super.init(config);
engine = new Engine();
}