2017-02-06 4 views
1
@RequestMapping(value = "/login", method = RequestMethod.POST) 
public ModelAndView loginPage(@Valid @ModelAttribute("user")User user, BindingResult result, ModelMap model) { 

    if(result.hasErrors()){ 
     model.addAttribute("failedLogin", "username or password is invalid"); 
    } 

    if(loginService.authenticateUser(user.getUsername(), user.getPassword())){ 
     model.addAttribute("username", user.getUsername()); 
     return new ModelAndView("redirect:/welcome"); 
    } 
    else{ 
     return new ModelAndView("login/login"); 
    } 
} 

@RequestMapping(value = "/welcome", method = RequestMethod.GET) 
public String welcomePage(@Valid @ModelAttribute("user")User user, BindingResult result, ModelMap model){ 
    model.addAttribute("username", user.getUsername()); 
    return "login/welcome"; 
} 

Iにログインすると、私はモデルをきれいにすることはできませんが、私はJSPファイルでusernameパラメータを使用してSpring MVCのは、パラメータ

'をhttp://localhost:8080/SpringMVC/welcome' を待っている間、私は 'http://localhost:8080/SpringMVC/welcome?username=volkansahin' を取得せずにリダイレクトします。

+1

model.addAttribute( "username"、user.getUsername()); ' –

+0

ここで何をする必要がありますか? –

+0

あなたは他のコントローラにリダイレクトしようとしていると思いました。 loginPage方法が代わりに変更されなければならない: ... loginPage(@Valid @ModelAttribute( "ユーザ")ユーザーのユーザー、BindingResult結果、ModelMapモデル、最終RedirectAttributesのredirectAttributes){ IF(result.hasErrors()){ model.addAttribute( "failedLogin"、 "ユーザー名またはパスワードが無効です"); } if(loginService.authenticateUser(user.getUsername()、user.getPassword())){ redirectAttributes.addFlashAttribute( "username"、user.getUsername()); 新しいModelAndViewを返します( "redirect:/ welcome"); } – youness

答えて

3

リダイレクト中に、あなたの属性を維持するために、あなたはRedirectAttributesこのような

を使用する必要があります。

@RequestMapping(value = "/welcome", method = RequestMethod.GET) 
public String welcomePage(@Valid @ModelAttribute("user")User user, BindingResult result, ModelMap model, **final RedirectAttributes redirectAttributes**){ 
    redirectAttributes.addFlashAttribute("username", user.getUsername()); 
    return "login/welcome"; 
} 

リダイレクトについての詳細情報のために次のURLを参照してください属性: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/support/RedirectAttributes.html

またはこの簡単な例に従う:

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/redirect-attributes/

+0

その後、jspページにアクセスできません。 –

関連する問題