Reputation: 9065
In my spring mvc application, I have the following login form:
<!--LOGIN FORM-->
<form name="login-form" class="login-form" action="usuario_login.html" method="post">
<!--HEADER-->
<div class="header">
<!--TITLE--><h1>Login Form</h1><!--END TITLE-->
<!--DESCRIPTION--><span>Fill out the form below to login to my super awesome imaginary control panel.</span><!--END DESCRIPTION-->
</div>
<!--END HEADER-->
<!--CONTENT-->
<div class="content">
<!--USERNAME--><input name="username" type="text" class="input username" value="Username" onfocus="this.value=''" /><!--END USERNAME-->
<!--PASSWORD--><input name="password" type="password" class="input password" value="Password" onfocus="this.value=''" /><!--END PASSWORD-->
</div>
<!--END CONTENT-->
<!--FOOTER-->
<div class="footer">
<!--LOGIN BUTTON--><input type="submit" name="submit" value="Login" class="button" /><!--END LOGIN BUTTON-->
</div>
<!--END FOOTER-->
</form>
the page usuario_login.html is configured in the DispatcherServlet in this way:
@RequestMapping(value="/usuario_login", method=RequestMethod.POST)
public ModelAndView usuario_login(@RequestParam("username") String username, @RequestParam("password") String password) {
UsuarioDAO usuario = new UsuarioDAO(username, password);
if(usuario.getUsuario() == null) {
String message = "oops! não foi possivel efetuar o login. Confira seu login e senha e tente novamente.";
return new ModelAndView("","message",message);
}
else {
this.sessao = new Sessao(usuario.getUsuario());
return new ModelAndView("usuario_start","usuario",usuario.getUsuario());
}
}
My question is: In case of login fail (the condition usuario.getUsuario() == null how i can redirect to my file index.jsp, where the login form is placed? I want send a message explaining the situation, to be displayed in this page, too.
Upvotes: 2
Views: 27629
Reputation: 753
I would seriuosly recommend using Spring Security for this, it is very easy to implement. Take a look at it here: Spring Security
Still, what you want to do can me done by doing
new ModelAndView("redirect:YOUR_REQUEST_MAPPING_HERE");
Also, for the message, I would recommend taking a look at Redirect Attributes
From the link above:
@RequestMapping(value = "/accounts", method = RequestMethod.POST)
public String handle(Account account, BindingResult result, RedirectAttributes redirectAttrs) {
if (result.hasErrors()) {
return "accounts/new";
}
// Save account ...
redirectAttrs.addAttribute("id", account.getId()).addFlashAttribute("message", "Account created!");
return "redirect:/accounts/{id}";
}
After the redirect, flash attributes are automatically added to the model of the controller that serves the target URL.
That means that for the example above, you can show the message in the JSP by doing ${message}, bacause a variable with name message is added to the model.
Upvotes: 5