Skip to content

Instantly share code, notes, and snippets.

@navin-mohan
Last active November 1, 2024 01:47
Show Gist options
  • Save navin-mohan/aaa6155bd49a436590905d0cacbfb115 to your computer and use it in GitHub Desktop.
Save navin-mohan/aaa6155bd49a436590905d0cacbfb115 to your computer and use it in GitHub Desktop.

This is an example of using Play framework to implement the GET method for submitting search queries.

The URL http://localhost:9000/search will give you the search box. Upon on clicking the search button, the browser will append ?q=<whatever search query that was entered> to the URL and refreshes the page.

The new URL after submission will be http://localhost:9000/search?q=<whatever search query that was entered> and play framwork renders the result page as defined in the controller.

Code Snippets:

# conf/routes
# Routes file
# Accepts an optional query parameter "q"
GET     /search                     controllers.HomeController.search(q: java.util.Optional[String])

// HomeController.java

public Result search(Optional<String> query) {
    if (query.isPresent()) {
        // renders the page with search results if a query is provided
        return ok("searching for " + query.get());
    }
    
    // renders the normal search box when no query is provided
    return ok(views.html.search.render());
}
@*  views/search.scala.html *@
@*  The search form *@

@()

@main("Search") {
    <form method="get">
        <input type="text" name="query" />
        <input type="submit" value="Search"/>
    </form>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment