2017-02-06 38 views
2

我想了解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。提前致謝。

回答

0

頁面刷新之間不保存Flash屬性。爲了實現你想要的,你可以使用會話屬性。最簡單的實現方法是在控制器類中添加@SessionAttributes(「userName」)。或者你可以使用請求對象手動操作它:request.getSession.setAttribute(「userName」,s);

+0

感謝您的建議。請你用代碼片段幫我。 – jagga

+0

在您的控制器類定義的地方,只需在@Controller註釋之後的下一行添加:@SessionAttributes(「userName」)。 – loredana

0

要麼重定向到包含您的成功消息的全新頁面,要麼將您的成功消息存儲爲session attribute,其活動週期比直接設置爲HTTP會話的屬性短。看一看this question

+0

我正在重定向到一個全新的頁面succes.jsp。但沒有得到所需的輸出 – jagga