Jim Driscoll's Blog

Notes on Technology and the Web

Redirecting from a JSF 2.0 Ajax Request

leave a comment »

Somewhat recently, I had a user of JSF 2.0 ask how to do a redirect from a JSF 2.0 Ajax request. Here’s one way, that I’ve lifted from one of our tests:

First, the bean that does the work:

public class RedirectBean {

    public String redirect() {

        FacesContext ctx = FacesContext.getCurrentInstance();

        ExternalContext extContext = ctx.getExternalContext();
        String url = extContext.encodeActionURL(ctx.getApplication().getViewHandler().getActionURL(ctx, "/ajax/redirecttarget.xhtml"));
        try {

        } catch (IOException ioe) {
            throw new FacesException(ioe);

        return null;

Hopefully, I don’t have to explain what this is doing – it’s sending a redirect request – regardless of whether it’s an Ajax request or not.

Next, the code that’s calling it:

    <title>Ajax Redirect</title>
    <h:form id="form">
        <h:commandButton id="redirect" value="Redirect" action="#{redirectBean.redirect}">
             <f:ajax execute="@this" render="@none"/>

So, what’s happening here? Well, once the bean sends the redirect, the ajax client receives a message from the server telling the client to redirect to a new page – all invisibly to the user. In case you’re curious, here’s what’s going back to the client along the wire:

"<?xml version="1.0" encoding="utf-8"?>
  <redirect url="/contextpath/faces/ajax/redirecttarget.xhtml">

So, a simple ajax request can redirect you to a new page. Like most of the new JSF 2 stuff, we’ve tried to make things “just work” as much as possible.

A little more edgecase than some of my previous blogs perhaps, but probably a useful trick to keep in mind. The code was originally written by Ryan Lubke, BTW, just to make sure that credit lands where it’s due.

Now that our big push for JavaOne is wrapping up, I’m hoping to have more time to blog in the immediate future. Stay tuned.

(This article originally published on my java.net blog on May 15, 2009.)


Written by jamesgdriscoll

February 9, 2010 at 8:45 PM

Posted in ajax, JSF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: