我有一个Post Controller,它接受一个输入表单字段,经过一些计算和检索db值后,它会重定向到带有两个参数的Get Controller。
@RequestMapping(value = "/user/calculate", method = RequestMethod.POST )
public String compareClients(@Valid UserInfo calculate, BindingResult bindingResult) {
/*some calculations*/
long firstClient=calculate.getFirstId();
long secondClient=calculate.getSecondId();
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("firstInfo",firstInfo);
modelAndView.addObject("secondInfo",secondInfo);
modelAndView.addObject("infoId",id);
return "redirect:/user/calculate?firstId=" + firstClient + "&secondId=" + secondClient;
我想将firstInfo,secondInfo和infoId传递给另一个控制器,以便从那里将它显示在百里香叶上
@RequestMapping(value = "user/calculate", method = RequestMethod.GET, params = { "firstId", "secondId" })
public ModelAndView comparison(@RequestParam(value = "firstId", required = true) String firstId,@RequestParam(value = "secondId", required = true) String secondId) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("firstClient", firstId);
modelAndView.addObject("secondClient", secondId);
return modelAndView;
}
我如何实现这一目标?请帮忙。 我尝试使用forward而不是重定向,但响应时间太长,并且它不会转发到Get Controller。 无法使用flashAttributes,因为如果我刷新页面,我需要Thymeleaf上的信息。 我无法通过网址传递所有5个对象。如果隐藏它,那就更好。
答案 0 :(得分:0)
我对Thymeleaf
没有太多了解,但您可以使用RedirectAttributes
将所需的值传递给另一个控制器。由于您的评论希望在刷新页面时保留该值。所以我使用SessionAttributes
public class YourInfo{
private String firstInfo;
private String secondInfo;
//setter and getter
}
您的控制器类添加会话属性注释
@Controller
@SessionAttributes("myInfo")
现在转到请求部分。
@RequestMapping(value = "/user/calculate", method = RequestMethod.POST )
public String compareClients(@Valid UserInfo calculate, BindingResult bindingResult, Model model) {
/*some calculations*/
long firstClient=calculate.getFirstId();
long secondClient=calculate.getSecondId();
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("firstInfo",firstClient);
modelAndView.addObject("secondInfo",secondClient);
modelAndView.addObject("infoId",id);
if(!model.containsAttribute("myInfo")){
YourInfo yourInfo = new YourInfo();
yourInfo.setFirstInfo(String.valueOf(firstClient));
yourInfo.setSecondInfo(String.valueOf(secondClient));
model.addAttribute("myInfo",yourInfo);
}
return "redirect:/user/calculate";
}
你的获取控制器(假设你的firstInfo和secondInfo将是字符串)
@RequestMapping(value = "user/calculate", method = RequestMethod.GET)
public ModelAndView comparison(@ModelAttribute("myInfo") YourInfo yourInfo) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("firstClient", yourInfo.getFirstInfo());
modelAndView.addObject("secondClient", yourInfo.getSecondInfo());
return modelAndView;
}