如何使用重定向使方法返回null

时间:2014-01-13 21:31:17

标签: java redirect jsf-2

在jsf中我想回到同一页面但是有重定向。因此,如果用户点击刷新,我不希望再次提交表单。

public String changeLanguage() {
    if (locale == Locale.ENGLISH)
        locale = new Locale("ar");
    else
        locale = Locale.ENGLISH;
    return null;
}

查看代码: - mybean sessionscope

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"
    xmlns:m="http://medicalgate.com/facelets" xmlns:h="http://java.sun.com/jsf/html">

<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>#{msg.hello}</title>
</h:head>
<h:body>
    <f:view locale="#{mybean.locale}">
        <h:form>
            <h:commandLink value="lang" action="#{mybean.changeLanguage}"></h:commandLink>
        </h:form>
    </f:view>
</h:body>
</html>

2 个答案:

答案 0 :(得分:0)

不幸的是,答案并不像看起来那么简单。 JSF是一个严重基于状态的框架,而你想要的P-R-G模式并不适合它。

如果你绝对必须这样做,那么你需要使你的bean请求作用域并使用视图参数来保持状态。

基本上,您需要进行以下更改:


MyBean.java

@RequestScoped
public class MyBean {
    public string submit() {
        String outcome = "MyView?faces-redirect=true&includeViewParams=true";
        return outcome;
    }
/* Bean goes here */
}

MyView.jsf

<html>
    <f:metadata>
        <f:viewParam name="fname" value="#{myBean.firstName}"/>
    </f:metadata>
    <h:body>
        <h:form>
            <h:inputText value="#{myBean.firstName}"/>
            <h:commandButton value="Submit" action="#{myBean.submit}"/>
        </h:form>
    </h:body>

不幸的是,这有一个缺点,那就是你的参数将被放入GET参数(http://mysite/MyView.jsf?fname=test),但你的页面也不会有回发问题。

因此,权衡是你做出决定,有条不紊地打破后退按钮,或无国籍和额外的工作与JSF的状态本质作斗争以避免回发。

答案 1 :(得分:0)

试试这个SSCCE。您将看到如何根据当前区域设置页面标题。当您单击该链接时,该方法将被调用一次,即使您刷新页面也不会再次调用该方法。请注意,mybean替换为myBean

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:h="http://java.sun.com/jsf/html">

<f:view locale="#{myBean.locale}" encoding="UTF-8"
    contentType="text/html">
    <h:head>
        <title>#{myBean.locale}</title>
    </h:head>
    <h:body>
        Selected locale: #{myBean.locale}
        <h:form>
            <h:commandLink value="lang" action="#{myBean.changeLanguage}" />
        </h:form>
    </h:body>
</f:view>
</html>
@ManagedBean
@SessionScoped
public class MyBean {

    Locale locale = Locale.ENGLISH;

    public String changeLanguage() {
        System.out.println("Method called");
        if (locale == Locale.ENGLISH)
            locale = new Locale("ar");
        else
            locale = Locale.ENGLISH;
        return null;
    }

    public Locale getLocale() {
        return locale;
    }

}