Execute servlet on startup of the application - java

I build a web application with JSPs and in my servlet I have:
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
init();
HttpSession session = request.getSession(true);
//more code...
}
}
Till now my serlvet is called, when the JSP page calls it like <a href="MyServlet..">. What I want is whenever the application starts, the servlet to be executed as well. I could have a button in my 1st page like "START" and there to call the servlet.. But, can I avoid this?

Whatever you want done on startup should be done by a class implementing ServletContextListener, so you should write such a class, for example:
public class MyContextListener
implements ServletContextListener{
#Override
public void contextDestroyed(ServletContextEvent arg0) {
//do stuff
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
//do stuff before web application is started
}
}
Then you should declare it in web.xml:
<listener>
<listener-class>
com.whatever.MyContextListener
</listener-class>
</listener>

You can configure it in Tomcat's web.xml (or corresponding configuration files in similar servers), like below using the tag <load-on-startup> :
<servlet>
<servlet-name>MyOwnServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

In my point of view, a good way is to implement a Servlet Context Listener. It listens to application startup and shutdown.
public class YourListener implements javax.servlet.ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
And then, you configure the listener in your web.xml () or with the #WebServletContextListener annotation.

Related

How to create a Java Class while Tomcat startup?

I have a main Java application running in a tomcat environment.
Now i have written a java class, put it into a JAR file and in the TCs lib folder. I can access that class now in the main app by importing the class and calling the constructer.
is there a way to create that class once at TCs startup. so i can access the classes variables?
Thanks!
e.
//EDIT 1
here is my example:
Beach.java
public class Beach {
public static void main(String []args) {
System.out.println("***********************");
}
}
MyAppServletContextListener.java
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyAppServletContextListener implements ServletContextListener{
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("**************** ServletContextListener started");
Beach x = new Beach();
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
}
}
all this goes into a jar file and into :
…/WEB-INF/lib/beach.jar
and this is my addition to Web.xml:
<web-app>
<listener>
<listener-class>
MyAppServletContextListener
</listener-class>
</listener>
</web-app>
and this is the server.log error:
10:42:26,440 | ERROR | [[/APP]] | Error configuring application listener of class MyAppServletContextListener
java.lang.ClassNotFoundException: MyAppServletContextListener
You can create a class implementing ServletContextListener
Once registered this class will allow you to invoke the desired constructor.
public class MyAppServletContextListener implements ServletContextListener{
#Override
public void contextInitialized(ServletContextEvent arg0) {
YourClass x = new YourClass();
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
}
}
You need to register this class into the web.xml:
<web-app ...>
<listener>
<listener-class>
com.yourpackage.MyAppServletContextListener
</listener-class>
</listener>
</web-app>

How to run the server class in gwt automatically at the time of apache starts

How to write and implement simple cronjob class in GWT?
It doesn't have any error but I need to know how to run the server class at time of apache starts.
Simply use ServletContextListener that will be called on the context initialization single time at time of server starts.
Put your logic inside contextInitialized() method.
web.xml
<listener>
<listener-class>com.x.y.z.AppServletContextListener</listener-class>
</listener>
Listener
public class AppServletContextListener implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
...
}
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
...
}
}

Trigger a function upon Weblogic termination

Is there anyway to capture weblogic termination event and trigger a Java function?
My weblogic version is V10.0
Thank you,
You could imlement a javax.servlet.ServletContextListener
public class MyServletContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent e) {
}
public void contextDestroyed(ServletContextEvent e) {
}
}
and add it to the web.xml.
<listener>
<listener-class>MyServletContextListener</listener-class>
</listener>
There you can handle the shutdwn of the weblogic container.

Guice3 Singleton is never instantiated in GAE project

I'm new to Guice and already stuck :)
I pretty much copied classes GuiceConfig, OfyFactory and slightly modified Ofy from Motomapia project (which you can browse) using it as s sample.
I created GuiceServletContextListener which looks like this
public class GuiceConfig extends GuiceServletContextListener
{
static class CourierServletModule extends ServletModule
{
#Override
protected void configureServlets()
{
filter("/*").through(AsyncCacheFilter.class);
}
}
public static class CourierModule extends AbstractModule
{
#Override
protected void configure()
{
// External things that don't have Guice annotations
bind(AsyncCacheFilter.class).in(Singleton.class);
}
#Provides
#RequestScoped
Ofy provideOfy(OfyFactory fact)
{
return fact.begin();
}
}
#Override
public void contextInitialized(ServletContextEvent servletContextEvent)
{
super.contextInitialized(servletContextEvent);
}
#Override
protected Injector getInjector()
{
return Guice.createInjector(new CourierServletModule(), new CourierModule());
}
}
I added this listener into my web.xml
<web-app>
<listener>
<listener-class>com.mine.courierApp.server.GuiceConfig</listener-class>
</listener>
<!-- GUICE -->
<filter>
<filter-name>GuiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GuiceFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<!-- My test servlet -->
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>com.mine.courierApp.server.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
OfyFactory looks like this
#Singleton
public class OfyFactory extends ObjectifyFactory
{
Injector injector;
#Inject
public OfyFactory(Injector injector)
{
this.injector = injector;
register(Pizza.class);
register(Ingredient.class);
}
#Override
public <T> T construct(Class<T> type)
{
return injector.getInstance(type);
}
#Override
public Ofy begin()
{
return new Ofy(super.begin());
}
}
Ofy doesn't have any Guice annotations at all...
public class Ofy extends ObjectifyWrapper<Ofy, OfyFactory>
{
// bunch of helper methods here
}
And finally test servlet where I'm trying to use injected field looks like this
public class TestServlet extends HttpServlet
{
#Inject Ofy ofy;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ofy.save(new Pizza());
}
}
Ofy ofy is always null. It's never injected. And it's not injected because OfyFactory is never instantiated, its constructor is never called.
Could you please point what I'm doing wrong? Why my singleton is never created?
Thanks a lot.
Instead of defining TestServlet in the web.xml file, try deleting its mapping from web.xml and adding this line in the configureServlets() method:
serve("/test").with(TestServlet.class);
You may also need to bind TestServlet as a Singleton either by annotating the class with #Singleton or by adding a
bind(TestServlet.class).in(Singleton.class);
line to one of the modules.
What's happening is that Guice is not actually creating your servlet so it isn't able to inject the Ofy object. Guice will only create servlets if it is instructed to do so using a serve(...).with(...) binding. Any servlets defined in the web.xml are outside of Guice's control.

Can webapplication be notified that the web container (ex. Tomcat) is reloading, unloading or shutting down

I have a Wicket Web Application running in Tomcat. The application uses Spring (via org.springframework.web.context.ContextLoaderListener) to initialise the application. This is all well and good for start up, but what I would also like is to receive some sort of notification that the Context is being destroyed so that I can shutdown spawned threads. Is there a way of receiving such a notification? I've included excerpts from my application to aid your understanding of my question.
web.xml extract
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:com/mysite/web/spring/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
Spring applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="MyWebService" class="com.mysite.web.MyWebApp">
</bean>
</beans>
MyWebApp.java extract
public class MyWebApp extends org.apache.wicket.protocol.http.WebApplication {
private MyWebServiceServiceAPI webservice =
MyWebServiceAppImpl.getMyWebService();
public MyWebServiceWebApp() {
}
#Override
public void init() {
super.init();
webservice.start();
}
}
MyWebServiceAppImpl.java extract
public class MyWebServiceAppImpl extends ServiceImpl
implements MyWebServiceServiceAPI {
// The ServiceImpl implements the Callable<T> interface
private static MyWebServiceServiceAPI instance;
private List<Future<ServiceImpl>> results =
new ArrayList<Future<ServiceImpl>>();
private ExecutorService pool = Executors.newCachedThreadPool();
private MyWebServiceAppImpl() {
super(.....);
}
public synchronized static MyWebServiceServiceAPI getMyWebService() {
if (instance == null) {
instance = new MyWebServiceAppImpl();
instance.start();
}
return instance;
}
#Override
public synchronized void start() {
if (!started()) {
pool.submit(this);
super.start();
}
}
Yes, you can implement your own ContextListener.
package myapp;
public class MyContextListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent arg0) {
//called when context is started
}
public void contextDestroyed(ServletContextEvent arg0) {
//called context destroyed
}
}
You need to add that listener to your web.xml
<listener>
<listener-class>myapp.MyContextListener</listener-class>
</listener>

Categories