Spring Boot - 重定向到不同的控制器方法

问题描述 投票:0回答:5

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

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

  @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
5个回答
50
投票

试试这个:

@RequestMapping(value = "/addData", method = RequestMethod.POST)
public String addData(@Valid Data data, BindingResult bindingResult, Model model) {

    //your code

    return "redirect:/showData";
}

18
投票

麻雀的解决方案对我不起作用。它只是渲染了文本“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>";
}

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 也是可能的。


0
投票

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


0
投票

如何重定向的示例

  1. / -> /swagger-ui/index.html
  2. /swagger -> /swagger-ui/index.html
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class RedirectController {

    private static final String SWAGGER_URL = "/swagger-ui/index.html";

    @GetMapping("/")
    @ResponseBody
    public void root(HttpServletResponse httpResponse) throws IOException {
        httpResponse.sendRedirect(SWAGGER_URL);
    }

    @GetMapping("/swagger")
    @ResponseBody
    public void swagger(HttpServletResponse httpResponse) throws IOException {
        httpResponse.sendRedirect(SWAGGER_URL);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.