JavaBean实例10:判断字符串是否以指定字符开头

在网站注册的时候,用户名信息往往不允许以数字或者其他字符开头。它是怎么实现的呢?

实际上其核心是用了String类中的方法实现的:
1.startsWith(String prefix);
public boolean startsWith(String prefix)
该方法用于判断字符串是否以指定的前缀(prefix)开始。

2.public boolean startsWith(String prefix,int toffset);
toffset为字符串指定索引开始位置。
例如:

String str="abcdefg";
str.startsWith("c",2);//返回true

实例代码:

1.javaBean文件:

package exa138;

public class StringUtil {

	private String startStr ;	//指定开头的字符串
	private String str;			//被判断的字符串
	private boolean check;		//判断结果
	
	public String getStartStr() {
		return startStr;
	}
	public void setStartStr(String startStr) {
		this.startStr = startStr;
	}
	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
	public boolean isCheck() {
		//使用startsWith方法判断字符串是否以制定字符开头,如果是则返回ture,否则返回false
		return str.startsWith(startStr);
	}
}

2.JSP文件
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="check.jsp" method="post">
     <table>
     	<tr>
     		<td align="right">请输入字符串:</td>
     		<td><input type="text" name="str"  /></td>
     	</tr>
     	<tr>
     		<td align="right">请输入开头的字符串:</td>
     		<td><input type="text" name="startStr"  /></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 str = request.getParameter("str");
   		String startStr = request.getParameter("startStr");
  	 %>
  	 <!-- 使用useBean动作标签导入JavaBean对象 -->
  	<jsp:useBean id="strBean" class="exa138.StringUtil"></jsp:useBean>
  	 <!-- 对StringUtil类的str属性赋值 -->
  	<jsp:setProperty property="str" name="strBean" value="<%=str %>"/>
    <!-- 对StringUtil类的startStr属性赋值 -->
    <jsp:setProperty property="startStr" name="strBean" value ="<%=startStr %>"/>
    <table>
    	<tr>
			<td align="right">输入的字符串:</td>
			<td>	
				<jsp:getProperty property="str" name="strBean"/>
			</td>
		</tr>
		<tr >
			<td align="right">开头的字符串:</td>
			<td>	
				<jsp:getProperty property="startStr" name="strBean"/>
			</td>		
		</tr>
		<tr>
			<td align="right">验证结果:</td>
			<td>	
				<jsp:getProperty property="check" name="strBean"/>
			</td>		
		</tr>
 	</table>	
</body>
</html>

结果:
JavaBean实例10:判断字符串是否以指定字符开头_第1张图片

你可能感兴趣的:(Javaweb实例学习)