开发者

ajax redirect not working

This is my jsf code :-

  <h:commandButton id="cmdLogin" value="Login" actionListener="#{indexBean.login}">
                            <f:ajax execute="@form" render="@all" />
                        </h:commandButton>

This is my login method of indexBean :-

 public void login(){

                HttpServletResponse objHttpServletResponse = (HttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
                objHttpServletResponse.sendRedirect("Restricted/Home.jsf");

    }

I get one alert in javascript emptyResponse: An empty response was received from the server. Check server error logs.. Why does this type of redirect not work?

EDIT :- Interestingly, when i redirect from faces-config.xml, it works!

<faces-config version="2.0"
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">

    <navigation-rule>
        <from-view-id>/index.xhtml</from-view-id>
        <navigation-case>
            <from-outcome>Home</from-outcome>
            <to-view-id>/Restricted/Home.jsf</to-view-id>
            <redirect/>
        </navigation-case>
    </navigation-rule>

</faces-config>

And obviously, i changed actionListener of commandbutton to action and changed return type of login to String and returned home from login method. Can anybody tell now, if this is the desired behaviour in JSF ? How come redirect from faces-config.xml works and simple redirect in managedbean 开发者_Go百科doesn't?


HttpServletResponse objHttpServletResponse = (HttpServletResponse)
                              FacesContext.getCurrentInstance()
                                          .getExternalContext()
                                          .getResponse();
objHttpServletResponse.sendRedirect("Restricted/Home.jsf");

Here, you leave the JSF API and cast down to the servlet API where JSF will not handle anything you do. When you invoke this method, the server returns a 302 response instead of the AJAX response the JavaScript API was expecting.

The correct mechanism to perform a programmatic redirect in JSF is to use the ExternalContext:

FacesContext.getCurrentInstance()
            .getExternalContext()
            .redirect("yourUrl");

If you use this mechanism with an AJAX call in JSF 2.0, the server will send a response like this:

<?xml version="1.0" encoding="utf-8"?>
<partial-response><redirect url="yourUrl"></redirect></partial-response>

You can use tools like Firebug and Fiddler to inspect your server's responses.


Note that this method signature is incorrect: public void login(). The specification states that action methods must declare an object return type (the fact that your implementation doesn't throw an error just means you got lucky).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜