Spring Boot控制器未正确重定向

时间:2020-06-05 19:57:30

标签: forms spring-boot redirect controller thymeleaf

我在控制器类中重定向下面的方法时遇到问题。

当我单击“提交”按钮时,它不会将我重定向到http://localhost:8080/manager/customers,但是会重定向到http://localhost:8080/customer/1/manager/customers

注意:1是我选择向其添加订单的客户ID

我做错什么了吗?

@PostMapping(value = "/customer/{id}/orders")
    public String projectAddOrders(@PathVariable("id") Long customerId, @RequestParam Long orderId, Model model) {
        Order order = orderService.findOrderById(orderId);
        Customer customer = customerService.findCustomerById(customerId);

        if (customer != null) {
            if (!customer .hasOrder(order)) {
                customer .getOrders().add(order);
            }
            customerService.saveCustomer(customer );
            model.addAttribute("customer", customerService.findCustomerById(customer Id));
            model.addAttribute("orders", orderService.getAllOrders());
            return "redirect:manager/customers";
        }
        return "redirect:manager/customers";
    } 

这是来自以下位置的HTML:

<form th:action="@{/customer/{id}/orders(id=${customer.id})}" method="post">
    <div class="row">
        <div class="col-25">
          Customer name: <b th:text="${customer.name}" /><br/>
        </div>
    </div> 
    <div class="row">       
         Customer orders:
            <b><span th:each="order, iterStat : ${customer.orders}">
                <span th:text="${order.name}"/><th:block th:if="${!iterStat.last}">,</th:block>
            </span></b>
        </div>      
    </div>
  <br/>
  <div class="row">
    <div class="col-25">
      <label for="user">Add Order</label>
    </div>
    <div class="col-75">
        <select name="orderId">
            <option th:each="order: ${orders}" 
                th:value="${order.id}" 
                th:text="${order.name}">
            </option>
        </select>
    </div>
  </div>

  <div class="row">
    <input type="submit" value="Add Order">
  </div>
  </form>

2 个答案:

答案 0 :(得分:1)

尝试转弯

return "redirect:manager/customers";

进入

return "redirect:/manager/customers"; 

注意'redirect:'和'manager'之间的斜线。 能行吗?

答案 1 :(得分:0)

我通过添加

对其进行了修复
registry.addViewController("**/manager/customers").setViewName("redirect:/manager/customers");
我的 ApplicationWebMvcConfigurerAdapter中的

实现了WebMvcConfigurer