当前位置: 代码迷 >> Web前端 >> javaBean范例之注册验证
  详细解决方案

javaBean范例之注册验证

热度:140   发布时间:2012-10-29 10:03:53.0
javaBean实例之注册验证

首先定义Bean:

package com.keith.bean;

import java.util.HashMap;
import java.util.Map;

public class Register {
	private String name;
	private String age;
	private String email;
	private Map<String, String> errors = null;

	public Register() {
		this.name = "";
		this.email = "";
		this.age = "";
		this.errors = new HashMap<String, String>();
	}

	public boolean isValidate() {
		boolean flag = true;
		if (!this.name.matches("\\w{6,15}")) {
			flag = false;
			this.name = "";
			errors.put("errname", "用户名必须是6~15位的字母或者数字!");
		}
		if (!this.email.matches("\\w+@\\w+\\.\\w+\\.?\\w")) {
			flag = false;
			this.email = "";
			errors.put("erremail", "输入的email地址不合法!");
		}
		if (!this.age.matches("\\d+")) {
			flag = false;
			this.age = "";
			errors.put("errage", "输入的年龄不合法!!!");
		}
		return flag;
	}

	public String getErrorMsg(String key) {
		String value = this.errors.get(key);
		return value == null ? "" : value;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Map<String, String> getErrors() {
		return errors;
	}

	public void setErrors(Map<String, String> errors) {
		this.errors = errors;
	}
}

?注册页面:

<jsp:useBean id="reg" scope="request" class="com.keith.bean.Register"></jsp:useBean>

	<form action="check.jsp" method="post">
		userName:<input type="text" name="name" value="<jsp:getProperty name="reg" property="name" />">
		<%=reg.getErrorMsg("errname") %>
		<br />
		email:<input type="text" name="email" value="<jsp:getProperty name="reg" property="email" />">
		<%=reg.getErrorMsg("erremail") %>
		<br />
		age:<input type="text" name="age" value="<jsp:getProperty name="reg" property="age" />">
		<%=reg.getErrorMsg("errage") %>
		<br />
		<input type="submit" value="Login">
		<input type="reset" value="Reset">
	</form>
	

?信息验证页:

<jsp:useBean id="reg" scope="request" class="com.keith.bean.Register"></jsp:useBean>

<body>
<jsp:setProperty property="*" name="reg"/>
	<%
		if(reg.isValidate()){
	 %>
	 	<jsp:forward page="success.jsp" />
	 <%
	 	}else{
	  %>
	  <jsp:forward page="index.jsp"></jsp:forward>
	  <%
	  	}
	   %>
</body>

?显示成功页:

<jsp:useBean id="reg" scope="request" class="com.keith.bean.Register"></jsp:useBean>
<body>
	用户名:<jsp:getProperty property="name" name="reg"/><br />
	年龄:<jsp:getProperty property="age" name="reg"/><br />
	EMail:<jsp:getProperty property="email" name="reg"/>
</body>
?
  相关解决方案