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


Unknown said...

Hi Vik,

Gr8 Work !

But what i think why you need a sevlet again when you already have your request n response object at faces level.

instead of that i feel you just have to write a mehod in which u can make JDBC connection n follow your normal validation logic.

The sevlet call :
"Command cmdSub = new DoSubscribe();
cmdSub.execute(req, resp); //this is a servlet defined as below"

is not required.

If you have any reason for this , Kindly let us know.


Unknown said...

Hie Rajeev:

Well you are right for what you said. You can achieve everything from writing a simple POJO instead of a servlet. But things are much more easy in the database layer when u have a servlet context or application context to read stuff like property files.

Secondly, URL forwarding is another thing which is a bit easier to do from a servlet depending upon ur business logic rather using a plain java class.

Anonymous said...

Hey Vik,
Good to see so many things on yuor blog. And belive me they are very helpful.

To make them more useful, i would like if you post something on requestScope and pageFlowScope.

Many people ask me about this diff.

believe me , such small things are really helpful to people.

What i have given u is just an example.

Unknown said...

i m try to call servlet but it doesnt work and give msg
Invalid argumentsin call

public String mySrvlet() {

System.out.println("------------To callServlet");
try {
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
ServletRequest request = (ServletRequest)ectx.getRequest();
ServletResponse response = (ServletResponse)ectx.getResponse();
//request.setAttribute("test","some value to pass");
RequestDispatcher dispatcher = ((ServletContext)ectx.getContext()).getRequestDispatcher("/pentahoSearch.xhtml");//.getRequestDispatcher("/pentahoSearch.xhtml");

System.out.println("------------in try");

System.out.println("--after forward----------in try");
} catch (ServletException e) {
System.out.println(" **************error msg ");
} catch (IOException e) {
return "pentaho";

Unknown said...

Well Shweta at which line you are getting this error? try debugging it a bit.. is it a compile time error?

please mail me if u r not able to find the stuff at vik.ceo@gmail.com

Unknown said...

Hi Vivek,

This was very helpful information. Thanks for sharing this :)


Anonymous said...

Good Afternoon!!! adfjsf.blogspot.com is one of the best informational websites of its kind. I enjoy reading it every day. adfjsf.blogspot.com rocks!

Unknown said...

hi Vik
this my servlet i use it to read employee picture:
public class getImage extends HttpServlet {

private static final String CONTENT_TYPE =
"image/jpeg; charset=windows-1252";

public void init(ServletConfig config) throws ServletException {

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String empno = request.getParameter("Empno");
String where = "";
String amDef = "StdPortalPkg.StdPortalAppModuleDataControl";
String config = "StdPortalAppModuleLocal";
OutputStream os = response.getOutputStream();
ApplicationModule am;

HttpSession session = request.getSession();
String user = (String)session.getAttribute(Configuration.DB_USERNAME_PROPERTY);
String pass = (String)session.getAttribute(Configuration.DB_PASSWORD_PROPERTY);
am = Configuration.createRootApplicationModule(amDef, config, new DynamicJDBCEnvInfoProvider(user, pass,null));
.....My Code to read image Configuration.releaseRootApplicationModule(am, false);


the problem appear in my prepareSession when i call this method :
public void getStdInfo() throws SQLException {

CallableStatement cs = null;
ResultSet rs = null;
try {
cs =
getDBTransaction().createCallableStatement("begin STUDENT_GENERAL.StdMasterInfoWeb(?,?); end;",
cs.setLong(1, OracleTypes.NULL);
cs.registerOutParameter(2, OracleTypes.CURSOR);

rs = ((OracleCallableStatement)cs).getCursor(2);

if (rs.next()) {
FacesContext ctx = FacesContext.getCurrentInstance();
Map sessionState = ctx.getExternalContext().getSessionMap(); // here error java null pointer exception ???
StudentInfo stdinfo =
new StudentInfo(rs.getInt("STUDENT_NO"), rs.getString("STUDENT_A_NAME"),
sessionState.put("stdinfo", stdinfo);

} catch (Exception ex) {

finally {


Unknown said...



in this which part is giving you NPE, getExternalContext() or getSessionMap() ?