The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.

Thursday, October 11, 2007

Calling a Servlet From a JSF managed bean

Cases when you simply want to call a servlet for doing tasks like database interactions etc and you do not want to use a framework like ADF-BC, EJB-toplink(may be because your requirements are too small ) you can do it in the following way:

Say there is a bean like:

public class SubscribeBean {
.. some code

public void validateConfirmEmailId(FacesContext facesContext,
UIComponent uiComponent, Object object) {

//to call servlet use below code
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest)fc.getExternalContext().getRequest();
HttpServletResponse resp=(HttpServletResponse)fc.getExternalContext().getResponse();

Command cmdSub = new DoSubscribe();
cmdSub.execute(req, resp); //this is a servlet defined as below
}catch(Exception e){
System.out.println("exception in SubscriberBean.java");


Please note that the two lines in the try catch block are specific to your needs. Like here DoSubscribe is another class implementing a servlet execute(request, response).

You can also use following code to call a servlet:
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();

For further help you can post a comment on this post....

Post a Comment