1

I m creating an app using JSF. The problem I have is that every time I refresh the page the action of the commandbuton is executed (ProjectEntityHandlerBean.insertNewProject) resulting in multiple unwanted entries in Database. I looked to a related thread but didnt help in my case :

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

Below is the .xhtml code, the bean`s code. If anybody can help, I would be grateful...

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>
Community
  • 1
  • 1
panipsilos
  • 2,219
  • 11
  • 37
  • 53

3 Answers3

1

If you post data, then refresh the page, browsers WILL resend the data. Some will warn first.

One way of preventing this is to use ajax for post, but then navigation after post is limited. Ajax can be enabled by a simple <p:ajax process="@form" update="@form"/> child of the commandButton, or by using primefaces own commandbutton <p:commandButton ajax="true" process="@form" update="@form"/>.

Rasmus Franke
  • 4,434
  • 8
  • 45
  • 62
1

Always use the Post-Redirect-Get pattern for forms.

Dragos Bulugean
  • 349
  • 2
  • 7
0

The general way to solve this in any web application is to have your POST redirect to a GET to display the results. Then the GET can be refreshed without affecting your database.

Skip Head
  • 7,580
  • 1
  • 30
  • 34