【JavaWeb】JDBC+Servlet+MySQL实现简单的注册功能(含部分源码)


思路

用户注册的一般流程为:
1、用户在前台填写用户名、密码等注册信息
2、servlet在后台获取从前台页面传来的注册信息,判断用户密码和确认密码是否一致,如果一致执行,否则给出提示。
3、将通过表单验证的用户信息加入到数据库中。

一、建立数据库

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (
  `username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `gender` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `habits` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `province` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `city` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

二、MVC

注册功能实现架构图

在这里插入图片描述


实体类

User.java

import java.io.Serializable;

public class User implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private String username; // 用户姓名
	private String password; // 用户密码
	private String email; // 用户邮箱
	private String gender; // 用户性别
	private String habits; // 用户兴趣爱好
	private String province; // 用户省份
	private String city; // 用户城市
	public User(String username, String password, String email, String gender, String habits, String province,
			String city) {
		super();
		this.username = username;
		this.password = password;
		this.email = email;
		this.gender = gender;
		this.habits = habits;
		this.province = province;
		this.city = city;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getHabits() {
		return habits;
	}
	public void setHabits(String habits) {
		this.habits = habits;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", email=" + email + ", gender=" + gender
				+ ", habits=" + habits + ", province=" + province + ", city=" + city + "]";
	}
    
}

数据库连接类

dataConTest.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class dataConTest {
	public static Connection getConnection(){
		Connection connection=null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("加载驱动程序有错误!请查看MySql的jar包导入是否正确");
			e.printStackTrace();
		}
		String url = "jdbc:mysql://localhost:3306/数据库名?user=用户名&password=密码&useUnicode=true&characterEncoding=utf8";
		try {
			connection=DriverManager.getConnection(url);
			System.out.println("MySQL数据库连接成功!");
		} catch (SQLException e) {
			System.out.println("数据库连接失败,请检查用户名、密码端口号等是否正确!");
			e.printStackTrace();
		}
		return connection;
		
	}
	public static void main(String[] args) {
		getConnection();
	}
}


实现注册的Servlet类

RegisterServlet.java

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zrz.servler.Service.UserService;
import com.zrz.servlet.domain.User;

@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	
    public RegisterServlet() {
        super();
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	     request.setCharacterEncoding("utf-8");
	     response.setContentType("text/html;charset=utf-8");
	     String username=request.getParameter("username"); // 用户姓名
	 	 String password=request.getParameter("password"); // 用户密码
	 	 String email=request.getParameter("email"); // 用户邮箱
	 	 String gender=request.getParameter("gender"); // 用户性别
	 	 String[] habits=request.getParameterValues("habits"); // 用户兴趣爱好
	 	 String province=request.getParameter("province"); // 用户省份
	 	 String city=request.getParameter("city"); // 用户城市
	 	 String habit = Arrays.toString(habits);
	 	 habit=habit.substring(1,habit.length()-1);
	 	 User user = new User(username,password,email,gender,habit,province,city);
	 	 UserService uservice= new UserService();
	 	 try {
			uservice.register(user);
			response.getWriter().println("<h1>注册成功</h1>");
		 	response.setHeader("refresh", "2;url=register.html");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}


前端页面代码

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="text/javascript" src="form.js"></script>
    <meta charset="UTF-8">
    <title>用户注册</title>

</head>
<body>
    <form action="RegisterServlet" method="post" >
        <table frame="above" width="1000px" border="1" cellspacing="0" align="center">
            <tr>
                <td colspan="3" style="text-align:center;border-color: orange;background-color: #fefdfb;">
                    <font style="font-size: 20px">Servlet实现简单的注册功能</font>
                </td>
            </tr>
            <tr>
                <td colspan="3" style="text-align:center;border-color: orange;background-color: #fefdfb;">
                    <font color="red">欢迎申请账户</font>
                </td>
            </tr>

            <tr>
                <td style="text-align: right ">
                    <font style="color: red;">* </font>用户名:
                </td>
                <td style="width: 50% ;text-align:center;"><input type="text" class="textinput " id="username" name="username" onkeyup="checkUsername();">
                </td>
                <td><span id="usernameMsg"> <font color="#999999" style="font-size: 13px; ">字母数字下划线1到10位, 不能是数字开头</font></span>
                </td>
            </tr>
            <tr>
                <td style="text-align: right ">
                    <font style="color: red;">* </font>密码:</td>
                <td style="width: 50% ;text-align:center; ">
                    <input type="password" class="textinput " id="password" name="password" onkeyup="checkPassword();" /></td>
                <td><span id="passwordMsg"> <font color="#999999" style="font-size: 13px; ">密码请设置6-16位字符</font></span>

                </td>
            </tr>
            <tr>
                <td style="text-align: right">
                    <font style="color: red; ">* </font>密码确认:</td>
                <td style="width: 50% ;text-align:center; ">
                    <input type="password" class="textinput" id="repassword" name="repassword" onkeyup="checkConfirm(); " />
                </td>
                <td><span id="confirmMsg"></span></td>
            </tr>
            <tr>
                <td style="text-align: right; width: 20% ">
                    <font style="color: red; ">* </font>电子邮箱地址:</td>
                <td style="width: 50%;text-align:center;">
                    <input type="text" class="textinput" id="email" name="email" onkeyup="checkEmail(); " />
                </td>
                <td><span id="emailMsg"> <font color="#999999" style="font-size: 13px;">请输入有效的邮箱地址</font></span>
                </td>
            </tr>
            <tr>
                <td style="text-align: right ">
                    <font style="color: red; ">* </font>性别:</td>
                <td style="width:50%;text-align:center;">
                    
                    <input type="radio" name="gender" value="" checked="checked" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input type="radio" name="gender" value="" /></td>
                <td></td>
            </tr>
            <tr>
                <td style="text-align: right ">
                    <font style="color: red;">* </font>您的兴趣爱好:</td>
                <td style="width: 50%;text-align:center; ">
                    <input type="checkbox" value="全选" name="habits" onclick="checkAll();" />全 选
                    <input type="checkbox" value="全不选 " name="habits" onclick="checkNotAll();">全不选
                    <input type="checkbox" value="购物 " name="habits" onclick="checkHabits();">购 物
                    <input type="checkbox" value="唱歌 " name="habits" onclick="checkHabits();">唱 歌
                    <input type="checkbox" value="玩游戏 " name="habits" onclick="checkHabits();">玩游戏
                    <input type="checkbox" value="看书 " name="habits" onclick="checkHabits();">看书
                </td>
                <td><span id="HabitMsg"> <font color="#999999" style="font-size: 13px;">请选择您的兴趣爱好</font></td>
            </tr>
            <tr>
                <td style="text-align: right ">
                    <font style="color: red; ">* </font>您的籍贯:</td>
                <td style="width: 50%;text-align:center; ">
                    省份:<select name="province">
                        <option  >请选择</option>
                        <option  value="河南" >河南</option>
                        <option  value="河北" >河北</option>
                        <option  value="山东" >山东</option>
                        <option  value="湖南" >湖南</option>
                        <option  value="台湾" >台湾</option>
                      </select> 城市:
                    <select name="city">
                         <option>请选择</option>
                        <option  value="平顶山" >平顶山</option>
                        <option  value="安阳" >安阳</option>
                        <option  value="南阳" >南阳</option>
                        <option  value="长沙" >长沙</option>
                        <option  value="台北" >台北</option>
                      </select>
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td colspan="3 " style=" text-align: center ">
                    <input type="submit"  value="提交 " style="width: 200px; ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input type="reset" style="width: 200px; ">
                </td>
            </tr>
        </table>
    </form>

</body>


</html>

form.js

var usernameObj;
var passwordObj;
var confirmObj;
var emailMsg;
var usernameMsg;
var passwordMsg;
var confirmMsg;
var habitMsg;
window.onload = function() { // 页面加载之后, 获取页面中的对象
    emailObj = document.getElementById("email");
    usernameObj = document.getElementById("username");
    passwordObj = document.getElementById("password");
    confirmObj = document.getElementById("repassword");
    emailMsg = document.getElementById("emailMsg");
    usernameMsg = document.getElementById("usernameMsg");
    passwordMsg = document.getElementById("passwordMsg");
    confirmMsg = document.getElementById("confirmMsg");
    habitMsg = document.getElementById("HabitMsg");

};

function checkForm() { // 验证整个表单
    var bEmail = checkEmail();
    var bUsername = checkUsername();
    var bPassword = checkPassword();
    var bConfirm = checkConfirm();
    return bUsername && bPassword && bConfirm && bEmail; // return false后, 事件将被取消
}

function checkEmail() { // 验证邮箱
    var regex = /^[\w-]+@([\w-]+\.)+[a-zA-Z]{2,4}$/;
    var value = emailObj.value;
    var msg = "";
    if (!value) { msg = "<span style=\"color:red;\">邮箱不能为空</span>"; } else if (!regex.test(value)) {
        msg = "<span style=\"color:red;\">邮箱格式不合法</span>";
    } else {
        msg = "<span style=\"color:green;\">格式合法</span>";
    }

    emailMsg.innerHTML = msg;
    return msg == "";
}

function checkUsername() { // 验证用户名
    var regex = /^[a-zA-Z_]\w{0,20}$/; // 字母数字下划线1到10位, 不能是数字开头
    var value = usernameObj.value; // 获取usernameObj中的文本
    var msg = ""; // 最后的提示消息, 默认为空
    if (!value) { msg = "<span style=\"color:red;\">用户名不能为空</span>"; } // 改变提示消息// 如果用户名没填, 填了就是一个字符串可以当作true, 没填的话不论null或者""都是false
    else if (!regex.test(value))
    // 如果用户名不能匹配正则表达式规则
    { msg = "<span style=\"color:red;\">用户名格式不正确</span>"; } else {
        msg = "<span style=\"color:green;\">该用户名可以使用</span>";
    }
    // 改变提示消息
    usernameMsg.innerHTML = msg; // 将提示消息放入SPAN
    return msg == ""; // 如果提示消息为空则代表没出错, 返回true
}

function checkPassword() { // 验证密码
    var regex = /^.{6,16}$/; // 任意字符, 6到16位
    var value = passwordObj.value;
    var msg = "";
    if (!value)
        msg = "<span style=\"color:red;\">密码不能为空</span>";
    else if (!regex.test(value)){ msg = "<span style=\"color:red;\">密码不合法</span>";}
      else { msg="<span style=\"color:green;\">验证密码通过</span>";}
       
    passwordMsg.innerHTML = msg;
    return msg == "<span style=\"color:green;\">密码合法</span>";
}

function checkConfirm() { // 验证确认密码
    var passwordValue = passwordObj.value;
    var confirmValue = confirmObj.value;
    var msg = "";

    if (!confirmValue) {
        msg = "<span style=\"color:red;\">确认密码不能为空</span>";
    } else if (passwordValue != confirmValue) {
        msg = "<span style=\"color:red;\">请保持和上面的密码一致</span>";
    } else {
        msg = "<span style=\"color:green;\">格式合法</span>";
    }
    confirmMsg.innerHTML = msg;
    return msg == "<span style=\"color:green;\">√</span>";
}

function checkAll() {
    var habits = document.getElementsByName("habits");
    for (var i = 0; i < habits.length; i++) {
        habits[i].checked = true;
    }
}

function checkNotAll() {
    var habits = document.getElementsByName("habits");
    for (var i = 0; i < habits.length; i++) {
        habits[i].checked = false;
    }
}

function checkHabits() {
    var habits = document.getElementsByName("habits");
    var count = 0;
    var msg = "";
    for (var i = 0; i < habits.length; i++) {
        if (habits[2].checked == true || habits[3].checked == true || habits[4].checked == true || habits[5].checked == true) {
            count++;
        }
    }
    if (count == 0) {
        msg = "<span style=\"color:red;\">请选择兴趣爱好</span>";
    } else {
        msg = "<span style=\"color:green;\">√ 通过</span>";
    }
    habitMsg.innerHTML = msg;
    return msg = "";
}

效果图

1、页面展示

在这里插入图片描述

2、表单验证

在这里插入图片描述

3、提交通过验证后的信息

在这里插入图片描述
数据库中已经插入在页面上提交的信息
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慢热型网友.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值