Wednesday, January 16, 2008

Accessing JSF Backing Beans from JSP

As sophisticated as it sounds, I don't really have much clue about what I'm talking here. Starting with very little knowledge on either JSF or JSP, I struggled with one simple problem for almost a week. That much searching in darkness at least deserves a blog entry I guess.

To make the long story short, in one of my CIMA portal renovations, I have a backing bean that takes a string parameter from the JSF/JSP front end, and generates an URL to be dispatched/forwarded/redirected by JSF/JSP. Stunningly, I couldn't find appropriate JSF tags that meet exactly what I need. After studying all possibilities listed in a very good summary given my restricted environment, I gave up and took the brute force approach of accessing the backing bean attribute from JSP directly:
<%
cima.jsf.managedbeans.MyBean mbean = (cima.jsf.managedbeans.MyBean) request.getAttribute("MyBean");
String url = mbean.get_url();
response.sendRedirect(url);
%>


However the above code gives NULL pointer exception because MyBean was not initialized for request, likely because JSF <managed-beans> declaration in faces-config.xml didn't fall though JSP invocation path -- I encountered some statements like that out on the web. Finally I settled with a simple solution buried in a helpful discussing thread, which is to insert the following line before trying to grab MyBean object out of request:
javax.faces.context.FacesContext.getCurrentInstance().getApplication().getVariableResolver().resolveVariable(javax.faces.context.FacesContext.getCurrentInstance(), "MyBean");


Worked like charm, if only I understood every piece of the complete mystery.

1 comment:

Anonymous said...

Amiable brief and this post helped me alot in my college assignement. Thanks you as your information.