应用字符的ASCII码来判断用户名是否有效,英文字母的ASCII范围为65-90(大写字母)和97-122(小写字母),下划线的ASCII码为95,数字的ASCII码范围在47-58
创建StringUtil的JavaBean类,判断用户名是否有效
public class StringUtil6 {
private String str; //要判断的字符串
private boolean valid; //是否有效
private String cue; //提示信息
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public boolean isValid() { //boolean属性的get方法写法为isXXX()
char cArr[]=str.toCharArray(); //字符串转换为字符数组
int firstChar=(int)cArr[0]; //第一个字符的ASCII码
StringBuffer sb=new StringBuffer("");
if((firstChar>=65&&firstChar<=90)||(firstChar>=97&&firstChar<=122)){ //判断首字符是否为字母
for(int i=1;i<cArr.length;i++){
int ascii=cArr[i]; //获得字符的ASCII码
//判断字符是否为字母,数字和下划线,下划线的ASCII码为95
if((ascii>=48&&ascii<=57)||(ascii>=65&&ascii<=90)||(ascii==95)||(ascii>=97&&ascii<=122)){
sb.append(cArr[i]); //如果条件满足,将字符添加到StringBuffer字符串的末尾
}
}
int length=cArr.length-sb.toString().length();
if(length==1){ //如果被判断字符串的长度为StringBuffer字符串记录的长度差1
this.setCue("用户名格式正确");
valid=true;
return valid;
}else{
this.setCue("用户名格式错误,只能由字母,数字,下划线组成");
valid=false;
return valid;
}
}else{
this.setCue("用户名格式不对,首字母为字母");
valid=false;
return valid;
}
}
public void setValid(boolean valid) {
this.valid = valid;
}
public String getCue() {
return cue;
}
public void setCue(String cue) {
this.cue = cue;
}
}
创建index.jsp页面,输入表单信息
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="check6.jsp" method="post">
<table>
<tr>
<td align="right">请输入用户名:</td>
<td><input type="text" name="name">
<font>只能由字母,数字或下划线组成</font></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="验证"></td>
</tr>
</table>
</form>
</body>
</html>
创建check.jsp验证用户输入的字符串
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name=request.getParameter("name");
%>
<jsp:useBean id="strBean" class="com.cn.zj.bean.StringUtil6"></jsp:useBean>
<jsp:setProperty property="str" name="strBean" value="<%=name %>"/>
<table>
<tr>
<td align="right">输入的用户名为:</td>
<td>
<jsp:getProperty property="str" name="strBean"/>
</td>
</tr>
<tr>
<td align="right">是否有效:</td>
<td>
<jsp:getProperty property="valid" name="strBean"/>
</td>
</tr>
<tr>
<td align="right">提示信息:</td>
<td>
<jsp:getProperty property="cue" name="strBean"/>
</td>
</tr>
</table>
</body>
</html>