Search code examples
formsurlspring-mvcactiontiles2

Spring MVC 3 and tiles : allow the controller to change the displayed url


Let's say I have a simple search page like this :

<form:form id="productsForm" method="post" modelAttribute="productsFormBean">
      <form:label path="name">Name : </form:label>
      <form:input path="name" />
      <button id="filterSubmit" type="submit">Submit</button>
</form:form>

A user can enter a name and submit the page, but he can also submit the page without entering anything.

Is it possible to obtain a RESTful url like this :

  • the user enters the name "xyz" and submits the page : www.mywebpage.com/products/name/xyz/
  • the user submits the page without a name : www.mywebpage.com/products/

Here's my controller :

    @RequestMapping(params = "search=true", value = "/**", method = RequestMethod.POST)
    public String searchHandler(@Valid final ProductsFormBean productsFormBean, final Model model) {
        // (...)
        return "productsSearch";
    }

If I change the "action" attribute of the form, the url changes. I already achieved that with javascript, by changing the action on the onSubmit event. But it's not a clean solution. Is it possible to achieve that directly in the controller ?


Solution

  • @RequestMapping(value="/", method=RequestMethod.POST)
    public String findProduct(@RequestParam String search)
    {
      if(search.isEmpty())
      {
        return "redirect:/"
      }
      else
      {
        return "redirect:/"+search;
      }
    }
    

    This should get you started, you'd still need to implement a method for handling the REST url for the search param.

    Also, don't know if it's 100% accurate, but should be pretty close.