Spring MVC password tag is used to show a password field on the UI
1 |
<form:password path="password" /> |
The HTML code that gets generated is
1 |
<input id="password" name="password" type="password" value=""> |
You can get more information on the various attributes that can be used in the password tag at the
Spring form TLD
Lets see a full example of the login page where the Spring MVC password tag is used.
1. Create a Model Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.kscodes.sampleproject.model; public class Login { private String userName; private String password; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } |
2. Create a Controller
In this example Controller is used to process the login form
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.kscodes.sampleproject.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.kscodes.sampleproject.model.Login; @Controller public class LoginController { @RequestMapping("/login") public ModelAndView getLoginPage() { return new ModelAndView("login", "command", new Login()); } @RequestMapping(value = "/processLogin", method = RequestMethod.POST) public ModelAndView processLogin(@ModelAttribute("login") Login login) { String userName = login.getUserName(); String password = login.getPassword(); if ("admin".equalsIgnoreCase(userName) && "admin123".equalsIgnoreCase(password)) { ModelAndView mv = new ModelAndView("success"); return mv; } else { ModelAndView mv = new ModelAndView("error"); return mv; } } } |
3. Login, Success and Error Pages
Create 3 jsp pages.
login.jsp has the login form. Note that the request method of the form should be same as the requestMethod of the Controller method that will be handling the form request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Spring MVC - Login</title> </head> <body> <h2>Login</h2> <form:form method="post" action="processLogin"> <table> <tr> <td><form:label path="userName">User Name</form:label></td> <td><form:input path="userName" /></td> </tr> <tr> <td><form:label path="password">Password</form:label></td> <td><form:password path="password" /></td> </tr> <tr> <td colspan="2"><input type="submit" value="Login" /></td> </tr> </table> </form:form> </body> </html> |
Output
Enter username = admin and password = admin123 for Success page to be displayed.
Any other values will display the error page.