index.jsp用来接收用户输入的表单,其代码如下:
<html>
<body>
<form action="result.jsp" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
年龄:<input type="text" name="age"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
result.jsp负责检查输入信息的正确性和完整性,并显示注册结果,其代码如下:
<%!
public boolean isNumeric(String str){
Pattern pattern=Pattern.compile("[0-9]*");
return pattern.matcher(str).matches();}
%>
<%
String username=request.getParameter("username");
String password=request.getParameter("password");
String age=request.getParameter("age");
//如果任意一个输入框中信息为空
if("".equals(username)||"".equals(password)||"".equals(age))
{
out.print("信息不能为空!<br>");
out.print("<a href=\"javascript:history.go(-1)\">返回</a>");
}
else{
//如果年龄不是数字
if(!isNumeric(age)){
out.print("年龄必须是数字<br>");
out.print("<a href=\"javascript:history.go(-1)\">返回</a>");
}
else{
out.print("注册成功<br>");
out.print("用户名:"+username);
out.print("密码:"+password);
out.print("年龄:"+age);
}
}
%>
index.jsp运行结果:
此时往输入框中输入信息,会出现以下三种情况:
1.完整并正确输入用户信息后点击”注册“按钮,页面跳转到result.jsp,显示用户信息:
2.输入信息不完整时(至少有一个输入框信息为空)点击“注册”按钮,页面跳转到result.jsp,显示错误信息:
例如输入情况如下:
点击“注册”按钮后出现以下信息:
3.输入年龄不为数字时点击“注册按钮,页面跳转到result.jsp,显示错误信息:
例如输入情况如下:
点击“注册”按钮后出现以下信息: