javaBean验证用户姓名是否有效

首先是java的代码:用来验证用户名等

package com.zhong;

public class Username {
    
    String reg = "[a-zA-Z]";
    String regx = "[a-zA-Z0-9_]";
    String username;
    Boolean isval;
    String tip;
    
    public String getTip() {
        return tip;
    }

    public void setTip(String tip) {
        this.tip = tip;
    }

    public String getUsername() {
        return username;
    }

    public Boolean getIsval() {
        return isValid();
    }

    public void setIsval(Boolean isval) {
        this.isval = isval;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public boolean isValid(){
        String name = getUsername();
        String firstname = String.valueOf(name.charAt(0));
        //首字母为字母
        if(firstname.matches(reg)){
            for(int i=1;i<name.length();i++){
                if(!String.valueOf(name.charAt(i)).matches(regx)){
                    setTip("用户姓名错误,只能由字母、数字和下划线组成!");
                    return false;
                }
            }
            setTip("用户格式正确!");
            return true;
        }else{
            setTip("用户姓名错误,首字符必须为字母!");
            return false;
        }
    }
}

然后是用户输入用户名界面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 = "judge.jsp" method = "post">
        <li>请输入用户名:<input type = "text" name= "username"/>只能由字母、数字或者下划线组成</li>
        <li><input type = "submit" name = "submit" value = "验证"/></li>
    </form>
</body>
</html>

最后是验证反馈给用户的界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <% response.setCharacterEncoding("UTF-8"); %>
    
<jsp:useBean id = "username" class = "com.zhong.Username" scope = "page">
    <jsp:setProperty name = "username" property = "*"/>
</jsp:useBean>
<!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>
    <ul>
        <li>输入的用户名为:<jsp:getProperty property = "username" name = "username"/></li>
        <li>&nbsp;&nbsp;&nbsp;是否有效:<jsp:getProperty property = "isval" name = "username"/></li>
        <li>&nbsp;&nbsp;&nbsp;提示信息:<jsp:getProperty property = "tip" name = "username"/></li>
    </ul>
</body>
</html>

南京  大三   想在南京附近找个能实习的机会。

你可能感兴趣的:(javabean)