Close

Java Servlet - @WebListener Examples

Java Servlet JAVA EE 

This example demonstrate how to use ServletContextListener along with Servlet 3.0 annotation @WebListener. This examples assumes a requirement where a global cache is needed by multiple servlets and other components during client requests. Guava Cache is used and initialized during the web application startup time in a ServletContextListener implementation.

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.concurrent.TimeUnit;

@WebListener
public class AppContextListener implements ServletContextListener {

@Override
public void contextInitialized (ServletContextEvent event) {
System.out.println("context initialized " + this);

LoadingCache<String, Object> cache =
CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterAccess(30, TimeUnit.MINUTES)
.build(new CacheLoader<String, Object>() {
@Override
public Object load (String s) throws Exception {
System.out.println("getting data for " + s);
/**
* In real situations will get data from database
* etc.
*/
return "Cached data for " + s;
}
});

event.getServletContext()
.setAttribute("GLOBAL_CACHE", cache);
}

@Override
public void contextDestroyed (ServletContextEvent sce) {

}
}
Original Post




This example shows the use of ServletContext#setSessionTrackingModes.

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.SessionTrackingMode;
import javax.servlet.annotation.WebListener;
import java.util.EnumSet;

@WebListener
public class SessionTrackingModeSetter implements ServletContextListener {

@Override
public void contextInitialized (ServletContextEvent event) {
System.out.println("--------\ncontext initialized\n------\n " + this);
System.out.println("The default session tracking modes: " +
event.getServletContext()
.getDefaultSessionTrackingModes());

event.getServletContext()
.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.URL));
}

@Override
public void contextDestroyed (ServletContextEvent sce) {
}
}
Original Post




See Also