【问题标题】:How can I call a method from the controller into thymeleaf without changing the URL如何在不更改 URL 的情况下将控制器中的方法调用到 thymeleaf
【发布时间】:2019-02-13 13:23:58
【问题描述】:

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

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

【问题讨论】:

  • without the /assService in the URL NSFW?

标签: java spring thymeleaf request-mapping


【解决方案1】:

使用重定向

modelAndView.setViewName("redirect:/");

并定义您的网址“/”

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

【讨论】:

    【解决方案2】:

    假设您使用 Spring MVC,您应该将 RequestMethod 更改为 POST,因为您正在发布一个表单。否则请求不会被正确处理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-29
      • 2014-11-22
      • 2019-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-12
      • 2016-06-09
      相关资源
      最近更新 更多