通过jsp+javabean完成一个注册用户的验证功能;
在一般情况下,用户注册的功能是肯定是好不了的,而且这些功能本身也需要对输入
的数据完成验证;本程序暂时不使用数据库;
程序完成需要的界面:
myIndex.jsp: 注册信息填写页,同时会将输入错误的数据进行错误提示;
check.jsp: 将输入的表单数据自动赋值给javabean,同时验证如果失败返回到index.jsp
success.jsp: 注册成功页,可以显示出用户注册成功的信息
Register.java: 注册使用的javabean,可以接受参数,同时进行判断,并返回结果
myIndex.jsp:
<%@ page contentType="text/html" pageEncoding="gbk"%>
<html>
<head><title>这是测试</title></head>
<body>
<%
request.setCharacterEncoding("gbk");
%>
<jsp:useBean id="reg" scope="request" class="org.lid.demo.Register"/>
<form action="check.jsp" method="post">
用户名:<input type="text" name="name" value="<jsp:getProperty name="reg" property="name"/>" >
<%=reg.getErrorMsg("errName")%><br>
年龄:<input type="text" name="age" value="<jsp:getProperty name="reg" property="age"/>">
<%=reg.getErrorMsg("errAge")%><br>
Email:<input type="text" name="email" value="<jsp:getProperty name="reg" property="email"/>">
<%=reg.getErrorMsg("errEmail")%><br>
<input type="submit" value="注册">
<input type="reset" value="重置">
</form>
</body>
</html>
check.jsp:
<%@ page contentType="text/html" pageEncoding="gbk"%>
<html>
<head><title>这是测试</title></head>
<%
request.setCharacterEncoding("gbk");
%>
<jsp:useBean id="reg" scope="request" class="org.lid.demo.Register"/>
<jsp:setProperty name="reg" property="*"/>
<body>
<%
if(reg.isValidate())
{
%>
<jsp:forward page="success.jsp"/>
<%
}
else{
%>
<jsp:forward page="myIndex.jsp"/>
<%
}
%>
</body>
</html>
success.jsp:
<%@ page contentType="text/html" pageEncoding="gbk"%>
<html>
<head><title>这是测试</title></head>
<body>
<%
request.setCharacterEncoding("gbk");
%>
<jsp:useBean id="reg" scope="request" class="org.lid.demo.Register"/>
<h3>姓名:<jsp:getProperty name="reg" property="name"/></h3>
<h3>年龄:<jsp:getProperty name="reg" property="age"/></h3>
<h3>Email:<jsp:getProperty name="reg" property="email"/></h3>
</body>
</html>
Register.java:
package org.lid.demo;
import java.util.HashMap;
import java.util.Map;
import java.util.HashMap;
public class Register{
private String name;
private String age;
private String email;
private Map<String,String> errors=null;
public Register(){
this.name="";
this.age="";
this.email="";
this.errors=new HashMap<String,String>();
}
public boolean isValidate(){
boolean flag=true;
if(!this.name.matches("\\w{3,15}")){
flag=false;
this.name="";//清空内容
this.errors.put("errName","用户名为6-15个字母或数字");
}
if(!this.email.matches("\\w+@\\w+\\.\\w+\\.?\\w*")){
flag=false;
this.email="";
this.errors.put("errEmail","邮件地址错误");
}
if(!this.age.matches("\\d+")){
flag=false;
this.age="";
this.errors.put("errAge","年龄只能是数字");
}
return flag;
}
public String getErrorMsg(String key){
String value=this.errors.get(key);
return value==null?"":value;
}
public void setName(String name){
this.name=name;
}
public String getName(){
return this.name;
}
public void setAge(String age){
this.age=age;
}
public String getAge(){
return this.age;
}
public void setEmail(String email){
this.email=email;
}
public String getEmail(){
return this.email;
}
}