First Step: write the JavaBean source code.
package register.test; import java.util.Map; import java.util.HashMap; public class RegisterBean { private String name; private String age; private String email; private Map<String,String> errors; public RegisterBean() { this.name=""; this.age=""; this.email=""; this.errors=new HashMap<String,String>(); } public boolean isValid() { boolean flag = true ; if(!this.name.matches("\\w{6,15}")){ flag = false ; this.name = "" ; this.errors.put("errname","user name must between 6~15 words") ; } if(!this.email.matches("\\w+@\\w+\\.\\w+\\.?\\w*")){ flag = false ; this.email = "" ; this.errors.put("erremail","Email doesn't match.") ; } if(!this.age.matches("\\d+")){ flag = false ; this.age = "" ; this.errors.put("errage","Age must be a number") ; } return flag ; } public String getError(String key) { String value=this.errors.get(key); return value==null?"":value; } public void setName(String name) { this.name=name; } public void setAge(String age) { this.age=age; } public void setEmail(String email) { this.email=email; } public String getName() { return name; } public String getAge() { return age; } public String getEmail() { return email; } }
Then We should have a register page, here we go:
<html> <head> <title>Register Page</title> </head> <jsp:useBean id="user" scope="request" class="register.test.RegisterBean"/> <body> <form action="check.jsp" method="post"> Account ID: <input type="text" name="name" value="<jsp:getProperty name="user" property="name"/>"/><%=user.getError("errname")%><br> Age : <input type="text" name="age" value="<jsp:getProperty name="user" property="age"/>"/><%=user.getError("errage")%><br> Email: <input type="text" name="email" value="<jsp:getProperty name="user" property="email"/>"/><%=user.getError("erremail")%><br> <input type="submit" value="Submit"> </form> </body> </html>
When we submit this form, we use check.jsp to check the form content.
<html> <head> <title>Check Page</title> </head> <body> <jsp:useBean id="user" scope="request" class="register.test.RegisterBean"/> <jsp:setProperty name="user" property="*"/> <% if (user.isValid()) {%> <jsp:forward page="show.htm"/> <%} else {%> <jsp:forward page="index1.jsp"/> <%}%> </body> </html>
Here we omit the show page, it's not important.
*we should notice something here
->we should use the label to setProperty for the instance of a JavaBean, it will never be done automatically.
->when we need some data from the JavaBean, we use getProperty and if we need to modify the data, we must use setProperty label manually.