我想了解PRG模式並創建了一個簡單的表單,它接受用戶的姓名和年齡。提交後,我希望它顯示歡迎用戶名,並在刷新選項卡上應保持相同。但刷新後它只顯示歡迎。下面是代碼如何使用後重定向獲取使用彈簧mvc?
demoForm.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"/>
succes.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;
}
任何幫助將appriciated。提前致謝。
感謝您的建議。請你用代碼片段幫我。 – jagga
在您的控制器類定義的地方,只需在@Controller註釋之後的下一行添加:@SessionAttributes(「userName」)。 – loredana