开发者

Determining if this is the first time servlet has run

Is there a way to properly tell if "this is the very first time" a servlet has run once an app start开发者_开发问答s? I'm currently using a request parameter, detecting if it's null, and if so running logic that's needed only the first time through.


What's wrong with the init() method?


A request parameter is pretty clumsy. It's also spoofable. A class variable is also not useful if you have multiple servlets. I'd rather set an attribute in the ServletContext. Maybe in a Filter, depending on the functional requirement.

if (servletContext.getAttribute("firstTime") == null) {
    servletContext.setAttribute("firstTime", true);
    // Do your first-time stuff here.
}

I am however curious about the functional requirement behind for which you think that this is the solution. Is it to do some initialization stuff on webapp's startup irrespective of the servlet used and you don't need the HttpServletRequest/HttpServletResponse at all, for example? For that a ServletContextListener would be a much better solution. It provides methods to hook on webapp's startup and shutdown.

@WebListener
public class Config implements ServletContextListener {

    @Override 
    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp's startup.
    }

    @Override 
    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp's shutdown.
    }

}


"The first time" is a fuzzy concept; what does it mean on multiplexed servers, for example? You first need to decide what this means, exactly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜