1

How can I propertly redirect to a servlet by a backing method?

class MyBean{ 
    public String doRedirect() {
        //some conditions
        return "newlocation";
    }
}


<h:commandButton value="Test" action="#{myBean.doRedirect}" />

This would redirect my to a newlocation.xhtml.

But what if I have a WebServlet?

@WebServlet(urlPatterns = "/newlocation")

How can I then redirect to the servlet instead to an xhtml file?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

2

You cannot use JSF navigation handler to navigate to a non-JSF resource.

Just use the ExternalContext#redirect() method directly:

public void doRedirect() throws IOException {
    FacesContext.getCurrentInstance().getExternalContext().redirect("newlocation");
}

Or if you're unsure about the current request path:

public void doRedirect() throws IOException {
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    ec.redirect(ec.getRequestContextPath() + "/newlocation");
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Ok cool, thanks for this hint! Is it better to use `.redirect` or `.dispatch`? – membersound Aug 21 '12 at 21:49
  • 1
    The `dispatch()` does a forward, not redirect. You explicitly asked "redirect" which is an entirely different process. See also http://stackoverflow.com/questions/11277366/jsf-redirect-options – BalusC Aug 21 '12 at 23:32
-1

You can access the raw HTTPServletResponse and do a redirect using its API

HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.sendRedirect(URL);
Community
  • 1
  • 1
JustinKSU
  • 4,875
  • 2
  • 29
  • 51