gpt4 book ai didi

java - Spring MVC 转发到新 URL 并保持现有状态

转载 作者:行者123 更新时间:2023-11-30 04:00:11 26 4
gpt4 key购买 nike

我试图重定向到上一页,但域对象无效。例如,使用地址域对象。

@Autowired 
private Address address;
@RequestMapping(method = RequestMethod.GET)
public String addressPage(
ModelMap model
) throws StdAddFault {
model.addAttribute("address", address);
return TILE_GET_STARTED_ADDRESS;
}
@RequestMapping(value = "/validate", method = RequestMethod.POST)
public String selectAddress(
@Valid Address address,
BindingResult result,
Model model,
HttpSession session
) throws StdAddFault {
if(result.hasErrors()) {
model.addAttribute("address", address);
return "/address";
}
...
}

问题是在请求之后,而不是/address,而是/address/validate。这似乎有点误导,但如果我使用重定向或转发,我就会丢失我的信息。

有什么方法可以将 url 设置在 Controller /地址之后(仅适用于无效数据)?

更新

我确认以上方法不起作用。这确实有效,但我担心一个请求可能会覆盖另一个请求的地址。这是一个合理的担忧吗?

if(result.hasErrors()) {
this.address = address;
return "redirect:/get-started/address";
}

最佳答案

我认为您想要的是存储在 session 中的“地址”模型属性。这将保留每个用户 session 的唯一地址对象

@Controller
@SessionAttributes({"address"})
@RequestMapping("/address")
public class AddressController {

/**
* Injected model reference will contain 'address' if it exists in session
*/
@RequestMapping(method = RequestMethod.GET)
public String addressPage(Model model) {
if(!model.containsAttribute("address"))
model.addAttribute("address", new Address());
return "address";
}

/**
* This handler maps to form selecting / updating the address object
* at the end of this method the address object is automatically
* stored in session
*/
@RequestMapping(value = "/validate", method = RequestMethod.POST)
public String selectAddress(@ModelAttribute("address") Address address) {
// do stuff with the newly updated address..
}
}

如果在任何其他处理程序中您需要地址对象,您所需要做的就是在参数上注入(inject) @ModelAttribute("address") Address address

关于java - Spring MVC 转发到新 URL 并保持现有状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22157525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com