Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27276

How to set request attributes from a Servlet and retrieve them from a JSF (xhtml) page

I have been reading this similar SO question but some of the approaches suggested there don't seem to work for me. My stack is JSF2.0 (+ PrimeFaces) and I deploy to a JBoss 7 AS.

There's a Servlet that dispatches a request to a xhtml page (in the same war) but the latter is not able to retrieve the value of the attribute set there.

Here's the Servlet code snippet:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
    (...)
    request.setAttribute("foo", "foo test");
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
    dispatcher.forward(request, response);                                    
}

And here's the code on the xhtml page:

<p><h:outputText value="#{sessionScope['foo']}" /></p>   
<p><h:outputText value="#{param['foo']}" /></p>                          
<p><h:outputText value="#{request.getParameter('foo')}" /></p>

wherein nothing shows up in any of the three cases.

What DID work was to use a backing bean (as suggested in a response to the references SO article) where the attributes are obtained in a @PostConstruct method as follows:

@PostConstruct
public void init() {
    HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance()
                                               .getExternalContext().getRequest();
    message = (String) request.getAttribute("foo");
}  

... where the retrieved value is subsequently available in the xhtml page.

But why is one method working but not the other ?

Upvotes: 2

Views: 9182

Answers (1)

Sandeep Panda
Sandeep Panda

Reputation: 723

The problem is that you are setting an attribute in request scope in your servlet but in the xhtml page you are writing request.getParameter("foo") and sessionScope['foo'] to access it.

In the xhtml page write this: #{requestScope.foo} and it will show the value of attribute foo.

Upvotes: 3

Related Questions