andrea
andrea

Reputation: 57

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;
}

Upvotes: 0

Views: 3314

Answers (2)

Trần Quốc Vũ
Trần Quốc Vũ

Reputation: 467

Use redirect

modelAndView.setViewName("redirect:/");

And define your url "/"

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

Upvotes: 1

Toriho
Toriho

Reputation: 11

Assuming that you use Spring MVC you should change your RequestMethod to POST, because you're POSTing a form. Otherwise the request is not handled correctly.

Upvotes: 1

Related Questions