views:

90

answers:

1

Hi,

is there any equivalent to FacesContext, but in servlet environment?

I have some DAOSessionManager that handles transaction to my database. I can use the FacesContext to identify the current http request when the current page is written using JSF, but what about servlet ones ?

I can't find any way to get the current Servlet context, or httpRequest...

Thanks.

PS : yes, having a reference to FacesContext from my DAO layer is a shame, but that's a start.

A: 

It's the ServletContext. It's available inside servlet classes by the inherited getServletContext() method.

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    ServletContext context = getServletContext();
    // ...
}

The major difference with FacesContext is that the ServletContext isn't ThreadLocal, so you cannot obtain it "statically" from the current thread like FacesContext#getCurrentInstance() does. You really need to pass the ServletContext reference around into the DAO methods wherever you need it:

someDAO.doSomething(getServletContext());

Or better yet, to avoid tight coupling, just extract the desired information from it and pass it:

Object interestingData = getServletContext().getAttribute("interestingData");
someDAO.doSomething(interestingData);
BalusC
I perfectly understand your approach, but it won't fit in my architecture. I have 3 layers (dao, domain, and GUI -- no need for a dedicated control layer like in MVC/MVP).
Francois B.
So, my domain layer isnt and can't be aware of the servletcontext. I just want to call my repositories and some tech part of the dao layer will deal with transaction, persistence manager (but it must be the same within one "session"). In fact, I'm trying to mimic open session in view without spring : I'm not very skilled at java, and I'm using google app engine.
Francois B.
For that generally a combination of `Filter` and `ThreadLocal` is used. Be careful though.
BalusC