如何防止在页面刷新时执行commandbutton中的操作?

时间:2012-10-17 15:07:56

标签: java jsf action

我正在使用JSF创建一个应用程序。我遇到的问题是每次刷新页面时都会执行commandbuton的操作(ProjectEntityHandlerBean.insertNewProject),导致数据库中出现多个不需要的条目。我找了一个相关的帖子,但在我的情况下没有帮助:

How to avoid re-execution of last form submit action when the page is refreshed?

下面是.xhtml代码,bean的代码。如果有人可以提供帮助,我将不胜感激......

public String insertNewProject()
{   
    System.out.println("Enter insert method");
    Project project = new Project();
    project.setProjectName(this.projectName);
    project.setDescription(this.description);
    project.setDuration(this.duration);
    ProjectHandler ph = new ProjectHandler();
    ph.create(project);
    return "viewid?faces-redirect=true";


}

<p:tab title="Insert">
            <h:form style="height: 500px; ">
                Insert new Project
                    <h:panelGrid border="2" columns="2" style="height: 200px; width: 383px; ">
                        <h:outputText value="project name"></h:outputText>
                        <h:inputText value="#{ProjectEntityHandlerBean.projectName}"></h:inputText>
                        <h:outputText value="project description"></h:outputText>
                        <h:inputText value="#{ProjectEntityHandlerBean.description}"></h:inputText>
                        <h:outputText value="project duration (Months)"></h:outputText>
                        <h:inputText value="#{ProjectEntityHandlerBean.duration}"></h:inputText>
                    </h:panelGrid>
                    <h:commandButton value="Submit" action="#{ProjectEntityHandlerBean.insertNewProject}"></h:commandButton>
            </h:form>       
        </p:tab>

3 个答案:

答案 0 :(得分:1)

如果您发布数据,然后刷新页面,浏览器将重新发送数据。有些人会先警告。

防止这种情况的一种方法是使用ajax进行发布,但是后发布后的导航是有限的。可以通过commandButton的简单<p:ajax process="@form" update="@form"/>子项或使用primefaces自己的命令按钮<p:commandButton ajax="true" process="@form" update="@form"/>来启用Ajax。

答案 1 :(得分:1)

始终使用表单的Post-Redirect-Get模式。

答案 2 :(得分:0)

在任何Web应用程序中解决此问题的一般方法是将POST重定向到GET以显示结果。然后可以刷新GET而不影响您的数据库。