FacesContext and “Servlet” Context

醉酒当歌 提交于 2019-12-07 12:35:26

问题


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.


回答1:


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);



回答2:


ServletContext servletContext = (ServletContext)FacesContext.getCurrentInstance().getExternalContext().getContext();


来源:https://stackoverflow.com/questions/3754327/facescontext-and-servlet-context

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!