Apps
Apps

Reputation: 3389

Accessing FacesContext in servlet

I'm working on a JSF (v1.2) application. In my application I need a generic servlet which could serve any resource (PDF, Images, Excel, etc). My idea is to ask the caller to send the required information so that I can find out the correct delegator class using some configurations.

This delegator class will take care of serving the correct resource.

For example this is the request url

http://example.com/servlet?delegatorid=abcd

My Servlet code is something like this.

protected void doGet(HttpServletRequest request, HttpServletResponse response){
 String delegatorID=request.getParameter("delegatorid");
//Get the configuration from Configuration table
configuration=getConfiguration(delegatorID);
//invoke the method of the delegator class based on this configuration
Object result=invokeMethod(configuration);
//write the response to the stream
}

My question is what is the best way to do this in a JSF project?

  1. Should I completely avoid JSF dependency in this operation? I can find the delegator method and class and invoke it using reflection. Will there be any potential restrictions in future if I avoid JSF dependency. [One problem which I can think about is, in one of the code, I need to get the user information from session. I'm doing this through FacesContext. Since FacesContext is not available, it will fail, I should have another option to get the session.
  2. If I have to introduce JSF dependency, how do I get the FacesContext here? As far as I know, only the beans that are stored in application scope can be accessed here. I don't want to do that. Is there any other way of getting it?
  3. Instead of using a servlet, can I do this by invoking a ManagedBean method directly using the URL? This will give me FacesContext. I think I need to have a dummy JSP page for the managed bean method to get invoked.

Could you please let me your thoughts on this?

Upvotes: 4

Views: 7482

Answers (1)

BalusC
BalusC

Reputation: 1108722

The FacesContext (and ExternalContext) is just a facade over HttpServletRequest, HttpServletResponse, HttpSession, ServletContext, etcetara along with some JSF specifics which you don't need at all in a plain vanilla servlet. The ExternalContext#getSessionMap() is nothing more than an abstract mapping of HttpSession#get/setAttribute().

In a plain vanilla servlet, the session is just available by request.getSession() and the application by getServletContext() the usual way. See also among others this related question: Get JSF managed bean by name in any Servlet related class.

You can also just refactor code which needs to be shared by JSF and Servlet into an utility method which doesn't have any dependencies on javax.faces.* nor javax.servlet.* classes (or at most only javax.servlet.*) and finally let the callers each pass the necessary information through.

Upvotes: 8

Related Questions