Javascript 使用ModelMap重定向Post方法以获取Spring中的方法
因此,我有以下代码Javascript 使用ModelMap重定向Post方法以获取Spring中的方法,javascript,java,spring,spring-mvc,Javascript,Java,Spring,Spring Mvc,因此,我有以下代码 @RequestMapping(value = "/api/store") @ResponseBody public ModelMap doSomething( HttpServletResponse response, @RequestParam String a, @RequestParam(defaultValue = "false") final boole
@RequestMapping(value = "/api/store")
@ResponseBody
public ModelMap doSomething(
HttpServletResponse response,
@RequestParam String a,
@RequestParam(defaultValue = "false") final boolean x,
) {
ModelMap model = new ModelMap();
if (x) {
throw new throw new Exception("You already submitted your data!");
}
model.put("a", a);
return model;
}
现在的场景是,当用户填写表单并单击submit时,请求通过这个映射,它工作正常,x将被分配为true
现在的问题是:当用户刷新页面时,将向该映射发送另一个POST方法,因此将向用户显示一个错误(因为if语句)
现在我想,我必须使用PRG模式,并将用户重定向到GET(来自POST),但是示例主要使用ModelAndView,因为我使用ModelMap,我不知道如何使用ModelMap实现它
这个后端API然后连接到一些JS前端
我假设,我必须创建两个方法,一个GET方法和一个POST方法,在GET方法中我必须实现逻辑和所有内容,在POST中我必须简单地重定向到GET方法
更新:
我添加了以下get方法:
@GetMapping(value = "/api/store")
public ModelAndView doSomethingGet(
HttpServletResponse response,
@RequestParam final String code,
@RequestParam(defaultValue = "false") final boolean x
) {
return new ModelAndView("redirect:/api/store");
}
我还将post方法更改为:
@PostMapping(value = "/api/store")
public ModelMap doSomething(
HttpServletResponse response,
@RequestParam String a,
@RequestParam(defaultValue = "false") final boolean x,
) {
ModelMap model = new ModelMap();
if (x) {
throw new throw new Exception("You already submitted your data!");
}
model.put("a", a);
return model;
}
你说得对。您需要使用
GET
和POST
注释创建两个方法
@GetMapping(value=“/api/store”)
-只需返回视图即可@PostMapping(value=“/api/store”)
-实现业务逻辑谢谢你的回答。如何在GetMapping中返回视图?在
@GetMapping
方法中返回ModelAndView
,并且不要在该方法上使用@ResponseBy
。返回重定向:/api/store“
将导致无限重定向到同一页面。在此检查如何使用model和view