StringUtil.java
package com.lh.bean;
public class StringUtil {
// 要判断的字符串
private String numStr;
// 判断结果
private boolean number;
// 提示信息
private String cue;
public void setNumStr(String numStr) {
// 去掉字符串中的空格
numStr = numStr.replaceAll(" ", "");
this.numStr = numStr;
}
public boolean isNumber(){
//将字符串转换为字符数组
char cArr[]=numStr.toCharArray();
//创建动态字符串对象
StringBuffer sb=new StringBuffer("");
for (int i = 0; i < cArr.length; i++) {
//将字符强制转换为int值,该值为字符的ASCII码
int ascii=(int)cArr[i];
//数字0~9的ASCII码范围在48~57之间
if(ascii>=48&&ascii<=57){
//条件满足,将字符添加到StringBuffer字符串末尾
sb.append(cArr[i]);
}
}
if(sb.length()==cArr.length){
//如果SringBuffer字符串的长度等于字符数组的长度
number=true;
this.setCue("您输入的是数字!");
}else{
number=false;
this.setCue("您输入的不是数字!");
}
return number;
}
public String getCue() {
return cue;
}
public void setCue(String cue) {
this.cue = cue;
}
public String getNumStr() {
return numStr;
}
public void setNumber(boolean number) {
this.number = number;
}
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>index.jsp</title>
</head>
<body>
<form action="check.jsp" method="post">
<table>
<tr>
<td align="right">月工资收入:</td>
<td><input type="text" name="numstr" />元
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="检查" />
</td>
</tr>
</table>
</form>
</body>
</html>
check.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>check.jsp</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String numStr = request.getParameter("numstr");
%>
<!-- 使用useBean动作标签导入JavaBean对象 -->
<jsp:useBean id="strBean" class="com.lh.bean.StringUtil"></jsp:useBean>
<!-- 对StringUtil类的dateStr属性赋值 -->
<jsp:setProperty property="numStr" name="strBean" value="<%=numStr %>" />
<table>
<tr>
<td align="right">输入的字符串为:</td>
<td>
<!-- 从StringUtil对象中获得numStr的属性值 --> <jsp:getProperty
property="numStr" name="strBean" /></td>
</tr>
<tr>
<td align="right">是否为数字:</td>
<td>
<!-- 从StringUtil对象中获得today的属性值 --> <jsp:getProperty
property="number" name="strBean" /></td>
</tr>
<tr>
<td align="right">提示信息:</td>
<td>
<!-- 从StringUtil对象中获得cue的属性值 --> <jsp:getProperty property="cue"
name="strBean" /></td>
</tr>
</table>
</body>
</html>