如何在不更改URL的情况下从控制器调用方法到thymeleaf

时间:2019-02-13 13:23:58

标签: java spring thymeleaf request-mapping

我有一个带有Thymeleaf的html页面,并且该页面中有一个按钮。该按钮正在从我已使用/ addService映射的控制器中调用方法,但它返回/ index页面(因为我已经在该页面中并且我想保留在其中)。因此,当我按下按钮时,它会将我重定向到索引页面,但URL已使用/ addService更改。我想保留在索引页面中,而URL中没有/ assService。在我的表单和控制器代码下面。我如何避免这种行为? 预先感谢。

我的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>

我的控制器

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

2 个答案:

答案 0 :(得分:1)

假设您使用的是Spring MVC,则应将RequestMethod更改为POST,因为您正在发布表单。否则,该请求将无法正确处理。

答案 1 :(得分:1)

使用重定向

modelAndView.setViewName("redirect:/");

并定义您的网址“ /”

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