如何使用发布重定向获取使用弹簧 MVC



我正在尝试理解PRG模式并创建了一个简单的表单,该表单接受用户的名称和年龄。提交后,我希望它显示欢迎用户名,并且在刷新选项卡时它应该保持不变。但刷新后,它只显示欢迎。这是代码

演示表单.jsp

<form action="/Spring_Hibernate_RegistrationAndLogin/prg1" method="post">
Name:  <input type="text" name="uname"><br/><br/><br/>
Age:   <input type="text" name="age"><br/><br/><br/>
<input type="submit" value="Done"/>

成功.jsp

<h3>Hello  ${name}</h3>

控制器代码

@RequestMapping(value="prg",method={RequestMethod.GET})
public ModelAndView demoForm(){
    System.out.println("in get");
    ModelAndView model=new ModelAndView("demoForm");
    return model;
}
@RequestMapping(value="/prg1",method={RequestMethod.GET})
public ModelAndView doGet(@ModelAttribute ("userName") String s){
    System.out.println("in get1");
    //String name=s;
    ModelAndView model=new ModelAndView("succes");
    model.addObject("name", s);
    return model;
}

@RequestMapping(value="/prg1",method={RequestMethod.POST})
public ModelAndView doPost(@RequestParam(name = "uname") String s,final RedirectAttributes redirectAttribute){
    System.out.println("in post1");
    ModelAndView model=new ModelAndView("redirect:/prg1");
    //model.addObject("uname", s);
    redirectAttribute.addFlashAttribute("userName",s);
    return model;
}

任何帮助都将得到认可。提前谢谢。

Flash 属性在页面刷新之间不保存。要实现所需的目标,您可以使用会话属性。最简单的实现方法是在控制器类上添加 @SessionAttributes("用户名"(。或者您可以使用请求对象手动操作它:request.getSession.setAttribute("userName",s(;

重定向到包含成功消息的全新页面,或者将成功消息存储为会话属性,该属性的生存周期比直接设置为 HTTP 会话的属性短。看看这个问题

最新更新