Reputation: 1741
In my web application I have two servlets which act as a controller. One servlet is used to handle web requests and another servlet is used to handle AJAX requests.
//This servlet manages web requests, and forwards to JSP to display data
WebController extends HttpServlet:
// This servlet manages AJAX requests. And returns JSON to user
AJAXController extends HttpServlet: This servlet manages
In my web.xml
I have the following mapping defined:
<servlet>
<servlet-name>WebController</servlet-name>
<servlet-class>com.frontend.WebController</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WebController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>AJAXController</servlet-name>
<servlet-class>com.AJAXController</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AJAXController</servlet-name>
<url-pattern>*.xhr</url-pattern>
</servlet-mapping>
So you can see I load WebController
before AJAXController
.
In the init()
method of webController
, I do all the initialization tasks.
loading the database driver
initializing the configuration
and other stuff that I need for my web application
The load-on-startup makes sure that before any AJAX request come to the server, the web app is initialized and I can be sure to make database access.
However, I do not like the idea of initializing web application in one servlet. I am thinking of having a separate servlet called InitServlet
and move the code from WebController
's init method to InitServlet
's init()
method
I will send HttpServletResponse.SC_FORBIDDEN
in their doPost()
and doGet()
method. But if possible I want ths servlet not to be mapped to anything.
Upvotes: 0
Views: 108
Reputation: 993
I think it is not necessarily a bad idea. Just define your initialization server to load first in the web.xml. As far as the entry goes, it needs to define the servlet class, of course and the load on startup order.
Put your initialization code in an implemented init method. Leave the doGet doPost methods empty so if they get called nothing happens. The init method will only get called once when the servlet is loaded.
The only issues I see is if this is being run into the context of a clustered set of application servers and you have resources that are truly singleton (like a connection pool), but in that case you can initialize these through application configuration in the application server. They will get intialized when the application starts and before the servlets are loaded.
Upvotes: -1
Reputation: 9162
It's a better idea to move your initialize code to ServletContextListener.
When your app starts it will execute contextInitialized(ServletContextEvent sce)
and you'll get a chance to init everything.
And this is how you hook it to your web.xml
Upvotes: 2