用户注册的一般流程为:
1、用户在前台填写用户名、密码等注册信息
2、servlet在后台获取从前台页面传来的注册信息,判断用户密码和确认密码是否一致,如果一致执行,否则给出提示。
3、后台遍历用户表里的userName字段,检查是否存在和前台用户名相等的值,如果没有则执行注册功能,否则给出用户名已存在的提示。
用户表的信息如下:
CREATE TABLE `db_user` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`userName` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`sex` varchar(6) DEFAULT NULL,
`birthday` varchar(20) DEFAULT NULL,
`email` varchar(50) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8
接着新建一个Java web工程并新建一个注册页面
实体类的代码如下:
package cn.dry.entity;
public class User {
private int id;//用户编号
private String userName;//用户名
private String password;//密码
private String sex;//性别
private String birthday;//出生日期
private String email;//邮箱
private String phone;//电话
private String address;//地址
public User(){
super();
}
public User (String userName,String password){
super();
this.userName = userName;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
数据库连接工具类代码如下:
package cn.dry.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class DbUtil {
private String dbUrl="jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8";
private String dbUserName="root";
private String dbPassword="数据库连接密码";
private String jdbcName="com.mysql.jdbc.Driver";
/**
* 获取数据库连接
* @return
* @throws Exception
*/
public Connection getCon() throws Exception{
Class.forName(jdbcName);
Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
return con;
}
/**
* 关闭数据库连接
* @param con
* @throws Exception
*/
public void closeCon(Connection con) throws Exception{
if(con!=null){
con.close();
}
}
public static void main(String[] args) {
DbUtil dbUtil=new DbUtil();
try {
dbUtil.getCon();
System.out.println("数据库连接成功");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
判断字符串是否为空的工具类代码
package cn.dry.util;
public class StringUtil {
public static boolean isEmpty(String str){
if("".equals(str)|| str==null){
return true;
}else{
return false;
}
}
public static boolean isNotEmpty(String str){
if(!"".equals(str)&&str!=null){
return true;
}else{
return false;
}
}
}
实现登录的servlet类代码如下:
package cn.dry.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.PreparedStatement;
import cn.dry.model.UserDao;
import cn.dry.util.DbUtil;
import cn.dry.util.StringUtil;
/**
* Servlet implementation class AddMessageServlet
*/
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DbUtil dbUtil=new DbUtil();
UserDao userDao=new UserDao();
/**
* @see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码、响应方式和编码方式
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Statement stmt = null;
ResultSet rs = null;
PreparedStatement pstmt = null;
//创建用户名集合
ArrayList<String> userNameList = new ArrayList<String>();
String userName = request.getParameter("userName");//获取用户名
String password = request.getParameter("password");//获取密码
String password1 = request.getParameter("password1");//获取确认密码
String sex = request.getParameter("sex");//获取性别
String birthday = request.getParameter("birthday");//获取出生日期
String email = request.getParameter("email");//获取邮箱
String phone = request.getParameter("phone");//获取电话
String address = request.getParameter("address");//获取地址
//获取与数据库连接的connection对象
Connection con = null;
try {
con = dbUtil.getCon();
//判断用户名和密码是否为空
if(StringUtil.isEmpty(userName)||StringUtil.isEmpty(password)||StringUtil.isEmpty(password1)){
request.setAttribute("error", "用户名或密码不能为空!");
//如果用户名和密码为空则重定向到登录页面
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
//判断两次密码是否一致
if(password.equals(password1)){
try {
//判断用户表中是否已经存在用户,遍历用户表中的userName字段,将userName字段的数据存入集合中
//判断集合中是否包含注册的用户名,如果有则提示用户已经存在,否则提交注册信息
//遍历用户表中的userName字段
String sql = "select userName from db_user";
stmt = con.createStatement();//创建sql语句
rs = stmt.executeQuery(sql);//执行sql语句
//将userName字段的数据存入集合中
while (rs.next()) {
userNameList.add(rs.getString(1));
}
//关闭ResultSet和Statement
rs.close();
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
if(userNameList.contains(userName)){
//out.println("<script type='text/javascript'>alert('用户名已存在,请重新注册!')</script>");
//response.sendRedirect("register.jsp");
request.setAttribute("error", "用户名已存在,请重新注册!");
//服务器端跳转
request.getRequestDispatcher("register.jsp").forward(request, response);
}else{
String insert = "insert into db_user(userName,password,sex,birthday,email,phone,address) values(?,?,?,?,?,?,?)";
try {
pstmt = (PreparedStatement) con.prepareStatement(insert);
//设置pstmt参数
pstmt.setString(1,userName);
pstmt.setString(2,password);
pstmt.setString(3,sex);
pstmt.setString(4,birthday);
pstmt.setString(5,email);
pstmt.setString(6,phone);
pstmt.setString(7,address);
//执行sql 语句
pstmt.execute();
//out.println("欢迎注册");
request.setAttribute("error", "注册成功!");
//客户端跳转
response.sendRedirect("index.jsp");
} catch (Exception e) {
e.printStackTrace();
}
}
}else{
//out.println("确认密码和密码不一致,请重新输入!");
out.println("<script type='text/javascript'>alert('确认密码和密码不一致,请重新输入!')</script>");
//服务器端跳转
//response.sendRedirect("register.jsp");
//request.setAttribute("error", "确认密码和密码不一致,请重新输入!");
request.setAttribute("error", "确认密码和密码不一致,请重新输入!");
//服务器端跳转
request.getRequestDispatcher("register.jsp").forward(request, response);
}
} catch (Exception e1) {
e1.printStackTrace();
}finally {
try {
//关闭connection连接
if(con!=null){
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
out.flush();
out.close();
}
}
配置相关的web.xml如下:
用户注册前台页面代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>用户注册</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript" src="<%=request.getContextPath() %>/js/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript">
/* function checkForm(){
var userNaem = $("#userNaem").val();
var password = $("#password").val();
var password1 = $("#password1").val();
var email = $("#email").val();
var phone = $("#phone").val();
var address = $("#address").val();
if(userNmae==""){
$("#error").html("用户名不能为空!");
return false;
}
if(password==""){
$("#error").html("密码不能为空!");
return false;
}
if(password1==""){
$("#error").html("密码不能为空!");
return false;
}
if(password!=password1){
$("#error").html("确认密码和密码不一致,请重新输入!");
return false;
}
if(email==""){
$("#error").html("电子邮箱不能为空!");
return false;
}
if(phone==""){
$("#error").html("电话不能为空!");
return false;
}
if(address==""){
$("#error").html("地址不能为空!");
return false;
}
return true;
} */
</script>
<style type="text/css">
#right{
text-align: right;
}
</style>
</head>
<body>
<div align="center">
<img alt="" src="images/bg.jpg" height="200px" width="80%">
</div>
<marquee scrollamount="10">欢迎注册旅游网</marquee>
<br/>
<hr color="blue" width="80%" size="3">
<form action="RegisterServlet" method="post" onsubmit="return checkForm()">
<table align="center" background="images/userlogin.jpg" border="1" width="350">
<tr>
<td id="right">
用 户 名(*):
</td>
<td width="60%"><input type="text" name="userName" id="userName" value="${userName }" onblur="checkUserName(this.value)" > <font id="userErrorInfo" color="red"></font></td>
</tr>
<tr>
<td id="right">
密 码(*):
</td>
<td>
<input type="password" name="password" id="password" value="${password }">
</td>
</tr>
<tr>
<td id="right">
确认密码(*):
</td>
<td><input type="password" name="password1" id="password" value="${password1 }"></td>
</tr>
<tr>
<td id="right">
性 别:
</td>
<td>
<input value="男" type="radio" checked="checked" name="sex" id="sex">男
<input value="女" type="radio" name="sex" id="sex">女
</td>
</tr>
<!-- <tr>
<td>
兴趣爱好:打篮球<input type="checkbox" name="c1" id="c1">
看书<input type="checkbox" name="c2" id="c2">
跑步<input type="checkbox" name="c3" id="c3">
</td>
</tr> -->
<tr>
<td id="right">
出生年月(*):
</td>
<td><input type="text" name="birthday" id="birthday" class="Wdate" value="${birthday }" onfocus="WdatePicker({isShowWeek:true})"></td>
</tr>
<%--<tr>
<td>年龄(*)</td>
<td>
<select name="age">
<option>请选择年龄</option>
<option value="00后">00后</option>
<option value="90后">90后</option>
<option value="80后">80后</option>
<option value="70后">70后</option>
</select>
</td>
</tr>
--%><tr>
<td id="right">
电子邮箱(*):
</td>
<td><input type="text" name="email" id="email" value="${email }"></td>
</tr>
<tr>
<td id="right">
电 话(*):
</td>
<td><input type="text" name="phone" id="phone" value="${phone }"> </td>
</tr>
<tr>
<td id="right">
家庭地址(*):
</td>
<td><input type="text" name="address" id="address" value="${address }"> </td>
</tr>
<tr>
<td>
</td>
<td>
<input type="reset" value="重置" name="reset" >
<input type="submit" value="注册" >
</td>
</tr>
<tr height="20">
<td colspan="2" align="center">
<font color="red">${error }</font>
</td>
</tr>
<tr >
<td></td>
</tr>
</table>
</form>
<hr color="blue" width="80%" size="3">
<div align="center">
网站版权所有:dry
</div>
</body>
</html>
最后是注册效果,用户名已存在的验证:
密码和确认密码不一致的验证:
写了一个晚上终于实现了基本的用户注册和登录功能,只是用了一些基本的验证方式,后台写的不是很好,希望能帮到大家,有问题欢迎留言。