0

I am working on a JSF application whose homepage has a search input field with a command button to submit the search. Once the user clicks the search button it should search and show the results page. I am having problem with passing the parameter from the home view to the results view. My code is as follows :

<h:form id="searchForm">
<p:inputText styleClass="enterSearch" size="50" value="#{searchController.searchText}" onkeypress="if (event.keyCode === 13) {document.getElementById('searchForm:submitSearch').click();
    return false;
 }"/>
<p:commandButton id="submitSearch" styleClass="enterSearch" value="Search" label="Search" action="#{searchController.search(searchController.searchText)}" />
</h:form>    

Bean is

@ManagedBean(name = "searchController")
@ViewScoped
public class SearchController implements Serializable {
.....
public String search(String query) {            
//What goes here?   Use FacesContext Attributes?  
return "searchResults";
}
...

The search method returns searchResults.xhtml page This page displays the search results. How can I pass the search query to the searchResults view and initialize the backing bean for searchResults? Any ideas please?

vinay
  • 950
  • 1
  • 11
  • 27

1 Answers1

2

If I understand you correctly, SearchController should actually pass the results (not the query) to the searchResults view. The way I'd do this is by moving the search method to the results page:

searchResults.xhtml:

<f:metadata>
  <f:viewParam name="searchQuery" value="#{searchController.searchText}" />
  <f:viewAction listener="#{searchController.update()}" />
</f:metadata>

<h:dataTable value="#{searchController.results}">
  <!-- your data -->
</h:dataTable>

SearchController.java:

@ManagedBean
@ViewScoped
public class SearchController implements Serializable {
    private String searchText; // +getter/setter
    private List<String> results; // +getter

    public void update() {            
        results = Arrays.asList(new String[] {"My", "Results"});
    }
}

Now you should be able to simply point your search form to the searchResults site:

<h:inputText value="#{searchController.searchText}" />
<h:commandLink action="searchResults" value="Search" />

Note that this is kind of a hack, so let me suggest alternatives:

  1. Stay on the same page. Since you can conditionally render elements, just hide your result display with a rendered="#{not empty searchController.results}". So easy.

  2. Don't use POST, but GET. This is exactly what this question is about (and a lot more).

Community
  • 1
  • 1
mabi
  • 5,279
  • 2
  • 43
  • 78