JavaBean专题

验证用户名是否正确

2018-08-19  本文已影响0人  神坛下的我

StringUtil.java

public class StringUtil {
    public StringUtil(){}
    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() {
        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];
                /*判断字符是否为字母,数字或下划线*/
                if ((ascii>=48&&ascii<=57)||(ascii>=65&&ascii<=90)||(ascii>=97&&ascii<=122)||(ascii==95)) {
                    sb.append(cArr[i]);
                }
            }
            int length=cArr.length-sb.toString().length();
            if(length==1){
                /*如果被判断字符串的长度与sb字符串的长度差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

<body>
    <form action="result.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>

result.jsp

<body>
    <%
        request.setCharacterEncoding("utf-8");
        String name= request.getParameter("name");
    %>
    <jsp:useBean id="strBean" class="com.count.StringUtil"></jsp:useBean>
    <jsp:setProperty property="str" name="strBean" value="<%=name %>"/>
    
    <table>
        <tr>
            <td>输入的用户名是:</td>
            <td align="left">
                <jsp:getProperty property="str" name="strBean"/>
            </td>
        </tr>
        <tr>
            <td>是否有效:</td>
            <td align="center">
                <jsp:getProperty property="valid" name="strBean"/>
            </td>
        </tr>
        <tr>
            <td>提示信息:</td>
            <td align="right">
                <jsp:getProperty property="cue" name="strBean"/>
            </td>
        </tr>
    </table>
</body>
10.PNG
上一篇下一篇

猜你喜欢

热点阅读