2017-02-06 3 views
2

私はPRGパターンを理解しようとしており、ユーザーの名前と年齢を受け入れる簡単なフォームを作成しました。私はそれをウェルカムユーザ名を表示したいと提出した後、それを維持する必要があります。ここではすべてのヘルプはにappriciatedされますポストリダイレクトの使い方spring mvcを使用しますか?

@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; 
} 

コード

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> 

コントローラー・コードです。前もって感謝します。

答えて

0

フラッシュの属性はページの更新の間に保存されません。必要なものを実現するために、セッション属性を使用できます。実装する最も簡単な方法は、コントローラクラスに@SessionAttributes( "userName")を追加することです。あるいは、リクエストオブジェクトを使って手動で操作することもできます:request.getSession.setAttribute( "userName"、s);

+0

suggestion.canに感謝します。コードスニペットで私を助けてください。 – jagga

+0

コントローラクラスが定義されている場所で、@Controllerアノテーションの後の次の行に@SessionAttributes( "userName")を追加するだけです。 – loredana

0

成功メッセージが含まれている完全に新しいページにリダイレクトするか、HTTPセッションに直接設定されている属性より短いLiveサイクルを持つsession attributeとして成功メッセージを保存してください。見てくださいthis question

+0

全く新しいページsucces.jspにリダイレクトしています。希望の出力が得られない – jagga

関連する問題