views:

546

answers:

2

I'm just getting started on JavaServer Faces and it looks very attractive. However I'd like to use my own servlets in the same web application as JSF.

This might be really obvious, but what are the best practices for integrating JSF with a "normal" servlets-based application? This would include accessing JSF data from the servlets (read and write).

A: 

You don't have to integrate servlets with JSF. This is contrary to the nature of JSF, which is "component based" rather than "action based".

JSF has managed beans whose methods get called when you press a button. You have both the request and response available (using FacesContext.getCurrentContext().getExternalContext()), but they shouldn't really be needed - all the data is automatically populated by JSF in the fields of the managed bean.

If you want servlets that do not integrated with JSF but work in the same application, then you just have to map them to a url that doesn't conflict with the url of the JSF servlet.

Bozho
+1  A: 

If your servlets are well-written, they should already not have any business logic inside, but just pure request/response controlling/preprocessing/postprocessing logic. The business logic should already be placed in standalone javabean-like domain/model classes. The database logic should already be placed in standalone DAO classes. And so on. You can just reuse them all in JSF.

That said, it may be good to know that JSF (when running on top of Servlet API --the common case) manages request scoped beans as attributes of HttpServletRequest, the session scoped beans as attributes of the HttpSession, the application scoped beans as attributes of ServletContext. It may also be good to know that all of those request, session and application attributes are accessible by ExternalContext#getRequestMap(), #getSessionMap() and #getApplicationMap(). You should now realize that you can just access them the usual way from inside a servlet.

In any case, when there is technical need to access the FacesContext inside a Servlet or a Filter, then immediately stop coding it and rethink your approach based on the above facts. Shouldn't it better be done in a new managed bean? Or maybe a PhaseListener?

BalusC
Agreed on the business logic in beans. My scenario was more among the lines of how I can send a user to a servlet and provide that servlet with (potentially many) parameters. I guess it makes sense to put them in the request and just forward to the servlet.I was sort of scared that JSF might be using some strange naming conventions or something (you know, the "_id0:_id0" thing) so I was expecting to have to hack around to find the real name of the "user" bean. Your answer clarifies this. Thanks!
Jerome Baum