Search code examples
javaspringthymeleafrequest-mapping

How can I call a method from the controller into thymeleaf without changing the URL


I have a html page with Thymeleaf and i have a button in that page. That button it is calling a method from the controller that i have mapped with /addService but it return the /index page(Because I'm already in that page and i want to remain in it). Therefore, when i press the button it is redirecting me to the index page but the URL is changed with /addService. I would like to remain in the index page without the /assService in the URL. Below my code of the form and of the controller. How can I avoid this behaviour? Thanks in advance.

My index.html

<form action="#" th:object="${serviceOffered}" th:action="@{addService}" method="POST">
    <input type="hidden" th:value="${serviceOffered.name}" name="name"/>
    <button type="submit" class="btn">
        <i class="fas fa-plus"></i>
    </button>
</form>

My controller

@RequestMapping(value="addService", method = RequestMethod.GET)
public ModelAndView getServiceSelected() {

    ModelAndView modelAndView = new ModelAndView();
    ServiceOffered serviceOffered = new ServiceOffered();

    modelAndView.addObject("serviceOffered", serviceOffered);

    modelAndView.setViewName("/index");
    return modelAndView;
}

Solution

  • Use redirect

    modelAndView.setViewName("redirect:/");
    

    And define your url "/"

    @GetMapping("/")
    public String indexPage() {
        return "index":
    }