【问题标题】:Spring Boot - redirect to a different controller methodSpring Boot - 重定向到不同的控制器方法
【发布时间】:2017-04-14 07:52:25
【问题描述】:

我正在使用 SpringBoot 和 Thymeleaf 创建一个非常基本的应用程序。在控制器中,我有两种方法如下:

Method1 - 此方法显示数据库中的所有数据:

  @RequestMapping("/showData")
public String showData(Model model)
{
    model.addAttribute("Data", dataRepo.findAll());
    return "show_data";
}

方法2 - 该方法将数据添加到数据库中:

@RequestMapping(value = "/addData", method = RequestMethod.POST)
public String addData(@Valid Data data, BindingResult bindingResult, Model model) {
    if (bindingResult.hasErrors()) {
        return "add_data";
    }
    model.addAttribute("data", data);
    investmentTypeRepo.save(data);

    return "add_data.html";
}

HTML 文件对应于这些方法,即 show_data.html 和 add_data.html。

一旦 addData 方法完成,我想显示数据库中的所有数据。但是,上面将代码重定向到静态 add_data.html 页面,并没有显示新添加的数据。我需要以某种方式调用控制器上的 showData 方法,因此我需要将用户重定向到 /showData URL。这可能吗?如果是这样,如何做到这一点?

【问题讨论】:

    标签: spring-boot controller thymeleaf


    【解决方案1】:

    以下解决方案对我有用。 getAllCategory() 方法显示数据,createCategory() 方法将数据添加到数据库。使用 return "redirect:categories";,将重定向到 getAllCategory() 方法。

    @GetMapping("/categories")
    public String getAllCategory(Model model) {
        model.addAttribute("categories",categoryRepo.findAll());
        return "index";
    }
    
    @PostMapping("/categories")
    public String createCategory(@Valid Category category) {
    
        categoryRepo.save(category);
        return "redirect:categories";
    }
    

    或者使用 ajax jQuery 也是可能的。

    【讨论】:

      【解决方案2】:

      sparrow 的解决方案对我不起作用。它只是渲染了文本“redirect:/”

      我可以通过将HttpServletResponse httpResponse 添加到控制器方法标头来使其工作。

      然后在代码中,将httpResponse.sendRedirect("/");添加到方法中。

      例子:

      @RequestMapping("/test")
      public String test(@RequestParam("testValue") String testValue, HttpServletResponse httpResponse) throws Exception {
          if(testValue == null) {
              httpResponse.sendRedirect("/");
              return null;
          }
          return "<h1>success: " + testValue + "</h1>";
      }
      

      【讨论】:

        【解决方案3】:

        试试这个:

        @RequestMapping(value = "/addData", method = RequestMethod.POST)
        public String addData(@Valid Data data, BindingResult bindingResult, Model model) {
        
            //your code
        
            return "redirect:/showData";
        }
        

        【讨论】:

        • 如果您尝试将请求从一个 RestController 重定向到另一个 RestController,这将不起作用
        • 这对我来说毫无意义
        【解决方案4】:

        您应该从您的 addData 请求中返回一个 http 状态代码 3xx,并将重定向 url 放入响应中。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-24
          • 2019-01-03
          • 2020-09-25
          • 2020-03-09
          • 1970-01-01
          • 2015-06-02
          • 1970-01-01
          相关资源
          最近更新 更多