Spring Boot - 重定向到不同的控制器方法 [英] Spring Boot - redirect to a different controller method

查看:73
本文介绍了Spring Boot - 重定向到不同的控制器方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating a very basic application with SpringBoot and Thymeleaf. In the controller I have 2 methods as follows:

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

Method1 - This method displays all the data from the database:

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

Method2 - 此方法向数据库添加数据:

Method2 - This method adds data to the database:

@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.

HTML files are present corresponding to these methods i.e. show_data.html and add_data.html.

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

Once the addData method completes, I want to display all the data from the database. However, the above redirects the code to the static add_data.html page and the newly added data is not displayed. I need to somehow invoke the showData method on the controller so I need to redirect the user to the /showData URL. Is this possible? If so, how can this be done?

推荐答案

试试这个:

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

    //your code

    return "redirect:/showData";
}

这篇关于Spring Boot - 重定向到不同的控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆