Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to integrate JSF with custom servlets?

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

like image 923
Jerome Baum Avatar asked Dec 30 '22 00:12

Jerome Baum


2 Answers

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?

like image 92
BalusC Avatar answered Dec 31 '22 12:12

BalusC


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.

like image 43
Bozho Avatar answered Dec 31 '22 14:12

Bozho