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

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

问题描述

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



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

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

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

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

返回 add_data.html;
}

存在与以下方法相对应的HTML文件,即show_data.html和add_data.html



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

解决方案

尝试一下:



< pre $ = lang-java prettyprint-override> @RequestMapping(value = / addData,method = RequestMethod.POST)
public String addData(@Valid Data data,BindingResult bindingResult,模型模型){

//您的代码

return redirect:/ showData;
}


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

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 - 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 files are present corresponding to these methods i.e. show_data.html and add_data.html.

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?

解决方案

Try this:

@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天全站免登陆