Java Spring MVC PRG模式在重新加载时保留数据



我目前正在研究一个springmvc项目。我有一个带有表单的页面,它代表一个配置程序。用户可以在一堆选择字段中选择一些数据,然后继续下一步,在那里他得到相同的jsp页面,但有更多的字段,这取决于他所做的输入。这将重复几次,直到他在另一页上得到结果。每次将执行POST。

现在,如果用户使用浏览器的后退功能,他不会到达上一页,而是到达浏览器默认的"后退";"断页";,其中Chrome例如说类似于";请确认重新提交表格数据&";。要真正重新提交数据,他必须按重新加载并确认弹出窗口。

重新提交本身并不是一个真正的问题,因为数据不会变得不一致,它只是对后端执行另一个调用并接收它提供的数据。真正不可行的是,用户必须手动刷新页面,并且偶然会被默认的浏览器页面弄糊涂。

我做了一些研究,发现PRG(后重定向-获取(模式可能会解决这个问题。事实上,我现在可以在浏览器中导航或重新加载页面,并且不会得到弹出或损坏的页面,因为它现在当然是一个get请求。

现在的问题是,如果我向后导航,最后一页不包含以前包含的数据,但现在是空的,因为根本不存在任何数据。我知道现在这是一个GET请求,没有发布任何数据,但我认为上一页会是";"重复使用";,如图所示。

现在有了PRG模式,应用程序的处理就更糟糕了,因为如果用户重新加载或导航回来,他基本上必须从头开始。

我是不是误解了这个图案的意思?

快速查看一些代码,我是如何实现的:

@PostMapping("/config")
public String handlePostRequestConfig(RedirectAttributes redirectAttributes, ProductForm productForm){
//Handle productForm and add additional content to it
if(noMoreStepsLeft){
return "redirect:/result";
}
redirectAttributes.addFlashAttribute("form", productForm);
return "redirect:/config";
}
@GetMapping("/config")
public String handleGetRequestConfig(Model model, @ModelAttribute("form") ProductForm productForm{
model.addAttribute("form", productForm);
return getJsp("product");
}

内部JSP:

<form method="post" action="/config">
<c:foreach items="${form.selectFields}" var="selectField">
<input...>
</c:foreach>
<button type="submit">Submit</button>
</form>

PRG中,P不是用户操作流的第一步PRG是全流的一部分。

以下显示了流程以及PRG如何融入其中:

用户将点击URL。例如:http://localhost:8080/myContextPath/config。这将使用GET处理程序进行处理:

@GetMapping("/config")
public String show(ModelMap model) {
// code

model.put("form", productForm);
return "product";    // returning view name which will be resolved by a view resolver
}

product.jsp:

<form commandName="form" method="post">
<c:foreach items="${form.selectFields}" var="selectField">
<input...>
</c:foreach>
<input type="submit" value="Submit"/>
</form>

提交操作将由POST处理程序处理:

@PostMapping("/config")
public String submit(@ModelAttribute("form") ProductForm productForm, 
RedirectAttributes redirectAttributes){

// code, may be service calls, db actions etc
return "redirect:/config";
}

重定向/config将由/configGET处理程序再次处理。(当然,您也可以重定向到任何GET处理程序(

最新更新