Javaweb常用登录和注册功能实现(详细步骤)

今天是总结一下自己学习,这个常用的功能登录和注册。

使用工具:myeclipse10、navicat Premimu12(MySQL)、Win10、tomcat7x。

1、打开mysql服务(管理员打开),确保数据库已经连接好,能使用。

Javaweb常用登录和注册功能实现(详细步骤)_第1张图片

下图右侧所示:连接成功,使用的数据库(名称:mytest)
Javaweb常用登录和注册功能实现(详细步骤)_第2张图片

创建表user,设计表如下:
Javaweb常用登录和注册功能实现(详细步骤)_第3张图片

插入数据,用于登录验证(适当插入几条数据即可):
Javaweb常用登录和注册功能实现(详细步骤)_第4张图片

2、打开myeclipse10,创建一个新项目,实现登录功能。

(1)在WebRoot下创建user_login.jsp(注意大小写)

<%@page import="com.qianfeng.orderfood.util.ValidateUtil"%>
<%@page import="com.qianfeng.orderfood.eums.UserLoginEnum"%>
<%@ 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">

	<%String msg = request.getParameter("msg") == null ? "" : request
					.getParameter("msg");%>
					
	<%if (msg.equals(UserLoginEnum.USER_NAME_IS_NUll.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_NAME_IS_NUll.getDesc()%>");
	<%}%>			
			
	<%if (msg.equals(UserLoginEnum.USER_PASSWORD_IS_NULL.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_PASSWORD_IS_NULL.getDesc()%>");
	<%}%>
		
	<%if (msg.equals(UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getDesc()%>");
	<%}%>
					
	<%if (msg.equals(UserLoginEnum.USER_NAME_OR_PASSWORD_IS_FAIL.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_NAME_OR_PASSWORD_IS_FAIL.getDesc()%>");
	<%}%>

	<%if (msg.equals(UserLoginEnum.USER_LOGIN_SUCCESS.getValue())) {%>
	 alert("<%=UserLoginEnum.USER_LOGIN_SUCCESS.getDesc()%>");
<%}%>
	
</script>

  </head>
  
  <body >
  	<div style="position: absolute;top:0;bottom: 0;left: 0;right: 0;height: 300px;width: 500px;margin:auto;">
  	<form action="UserLoginServlet" method="post">
  		<center><h1 style="color:red">网上订餐系统</h1>
  		<table style="text-align:justify;text-align-last: justify;">
  			<tr>
  				<td>用 户 名:</td>
  				<td><input name="username"></td>
  			</tr>
  			<tr>
  				<td>密  码:</td>
  				<td><input name="password"></td>
  			</tr>
  			<tr>
 				<%
					String validateCode = ValidateUtil.createValidateCode();
					session.setAttribute("syscode", validateCode);
				%>
  				<td>验 证 码:</td>
  				<td><input name="validatecode"></td>
  				<td><b><i style="color: red"><%=validateCode%></i> </b></td>
  			</tr>
  			
  			<tr>	
	  			<td><button type="submit">登录</button></td>
	  			<td><input type="button" value="注册" onclick="location='user_register.jsp'"/></td>
  			</tr>
  		</table></center>
  	</form>
  	</div>
  </body>
</html>

效果如下所示:
Javaweb常用登录和注册功能实现(详细步骤)_第5张图片

(2)在src目录下创建包(注意命名,可以不一致,创建相应的类类在相应包即可,下文会详细说明)
业务接口(包名:com.qianfeng.orderfood.biz)
业务实现(包名:com.qianfeng.orderfood.bizimpl)
dao层接口(包名:com.qianfeng.orderfood.dao)
dao层实现(包名:com.qianfeng.orderfood.daoimpl)
实体(包名: com.qianfeng.orderfood.entity)
场景(包名:com.qianfeng.orderfood.eums)
servlet服务(包名:com.qianfeng.orderfood.servlet)
工具包(包名:com.qianfeng.orderfood.util)

(3)导入相应的包到WebRoot—》WebINF—》lib
只需导入下图所示第四个包即可,再点击包,Bulid Path——》Add to Bulid Path
Javaweb常用登录和注册功能实现(详细步骤)_第6张图片
可以下载使用到的包(不需要积分,已上传)
Javaweb常用登录和注册功能实现涉及的包

(4)首先,在包com.qianfeng.orderfood.entity下创建实体类User(该类属性和表中字段一致);

package com.qianfeng.orderfood.entity;

import java.io.Serializable;
import java.sql.Timestamp;
// 什么样的文件才有资格叫实体类?
// 1:要符合ORM规范 
// (保持3个一直  表名和文件名一致)
// JAVA文件的属性名和数据库中的字段名要保持一致
// 数据库中的类型和JAVA中的类型要可以转换
// 2:要符合JAVABEAN规范
// 符合最基础的JAVABEAN 规范要满足以下几点
// (1)私有的属性
// (2)为私有的属性提供 GETER STEER
// (3)提供无参构造函数
// (4)实现序列化接口 (可以把文件存储内存中)

public class User implements Serializable {
	private int userid;
	private String username;
	private String password;
	private Timestamp createtime;
	private Timestamp updatetime;
	
	//快捷键ALT+SHIFT+S生成get和set函数
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	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 Timestamp getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Timestamp createtime) {
		this.createtime = createtime;
	}
	public Timestamp getUpdatetime() {
		return updatetime;
	}
	public void setUpdatetime(Timestamp updatetime) {
		this.updatetime = updatetime;
	}
	
	
}

(5)在包com.qianfeng.orderfood.eums下创建登录场景类UserLoginEnum;

package com.qianfeng.orderfood.eums;

public enum UserLoginEnum {

	// 枚举的格式   是全部要大写 多个单词 用下划线隔开
		// ctrl + shift + y + x  (大小写转换)
		// 一个功能如果 有涉及到业务场景 那么这个时候 我们就要考虑到封装一个枚举文件 用来记录这些业务场景,而不是
		// 让开发开发人员去死记硬背 这些 单词
		USER_NAME_IS_NUll("user_name_is_null","用户名不能为空"),
		USER_PASSWORD_IS_NULL("user_password_is_null","密码不能为空"),
		USER_NAME_OR_PASSWORD_IS_FAIL("user_name_or_password_is_fail","用户名或密码错误"),
		USER_VALIDATE_CODE_IS_FAIL("user_validate_code_is_fail","验证码错误"),
		USER_LOGIN_SUCCESS("user_login_success","登录成功");
		
		private String value;
		private String desc;
		// 添加构造函数的 快捷键 是 alt + shift + s
		private UserLoginEnum(String value, String desc) {
			this.value = value;
			this.desc = desc;
		}
		public String getValue() {
			return value;
		}
		public void setValue(String value) {
			this.value = value;
		}
		public String getDesc() {
			return desc;
		}
		public void setDesc(String desc) {
			this.desc = desc;
		}
}

(6)在包com.qianfeng.orderfood.util下创建三个工具类
数据库连接类JDBCUtil:

package com.qianfeng.orderfood.util;

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

public class JDBCUtil {

	//useSSL=false 是Mysql数据库的SSL连接问题,提示警告不建议使用没有带服务器身份验证的SSL连接
	private static final String driver="com.mysql.jdbc.Driver";
	//数据库名称填写自己的:这里是mytest,上文有提到
	private static final String url="jdbc:mysql://localhost:3306/mytest?useSSL=false";
	private static final String user="root";
	private static final String password="123456";
	static{
		try {
			Class.forName(driver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	public static Connection getConnection(){
		
		try {
			return DriverManager.getConnection(url,user,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	// 查询使用的关闭
	public static void close(ResultSet resultSet,
			PreparedStatement preparedStatement, Connection connection) {
		try {
				resultSet.close();
				preparedStatement.close();
				connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 增删查改的关闭
	public static void close(PreparedStatement preparedStatement,
			Connection connection) {
		try {
			preparedStatement.close();
			connection.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}

验证码工具类ValidateUtil;

package com.qianfeng.orderfood.util;

import java.util.Random;

public class ValidateUtil {

	public static String createValidateCode() {
		String temp = "1234567890qwertyuioplkjhgfdsazxcvbnm";
		StringBuilder validateCode = new StringBuilder();
		for (int i = 0; i < 4; i++) {
			validateCode.append(temp.charAt(new Random().nextInt(temp
					.length())));
		}
		return validateCode.toString();
	}

	public static void main(String[] args) {
		System.out.println(createValidateCode());
	}
}

判断字符工具类StringUtil;

package com.qianfeng.orderfood.util;

public class StringUtil {
	
	// 为何要判断NULL 和 空字符串呢?
	
	// NULL 在用户没有在请求报文中传输该KEY的时候发生
	// "" 是用户在表单没有输入数据的情况下发生
	public static boolean isEmpty(String arg){
		return arg == null || arg.equals("");
	}

	public static boolean isNotEmpty(String arg){
		return arg != null && !arg.equals("");
	}
}

(7)在包 com.qianfeng.orderfood.servlet下创建登录响应类UserLoginServlet;

package com.qianfeng.orderfood.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qianfeng.orderfood.biz.UserBIZ;
import com.qianfeng.orderfood.bizimpl.UserBIZImpl;
import com.qianfeng.orderfood.eums.UserLoginEnum;

public class UserLoginServlet extends HttpServlet {
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp){
		String result = null;
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String validatecode = req.getParameter("validatecode");
		String syscode = (String) req.getSession().getAttribute("syscode");
		try {
			UserBIZ userBIZ = new UserBIZImpl();
			result = userBIZ.userLogin(username, password, validatecode, syscode, req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (result.equals(UserLoginEnum.USER_LOGIN_SUCCESS.getValue())) {
				req.getRequestDispatcher("index.jsp").forward(
						req, resp);
			} else {
				req.getRequestDispatcher("user_login.jsp?msg=" + result + "")
						.forward(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

注意:web.xml配置,将下列代码加入web.xml

<servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>UserLoginServletservlet-name>
    <servlet-class>com.qianfeng.orderfood.servlet.UserLoginServletservlet-class>
  servlet>




 <servlet-mapping>
    <servlet-name>UserLoginServletservlet-name>
    <url-pattern>/UserLoginServleturl-pattern>
  servlet-mapping>

(8)在包com.qianfeng.orderfood.biz下创建业务接口类UserBIZ;

package com.qianfeng.orderfood.biz;

import javax.servlet.http.HttpServletRequest;

public interface UserBIZ {

	//用户登录
	String userLogin(String username, String password, String validatecode,
			String syscode, HttpServletRequest req);

	//用户注册
	String userRegister(String username, String password, String againpassword, String validatecode,
			String syscode, HttpServletRequest req);

}

(9)在包com.qianfeng.orderfood.bizimpl下创建业务接口类UserBIZImpl(实现接口UserBIZ );

package com.qianfeng.orderfood.bizimpl;

import javax.servlet.http.HttpServletRequest;

import com.qianfeng.orderfood.biz.UserBIZ;
import com.qianfeng.orderfood.dao.UserDAO;
import com.qianfeng.orderfood.daoimpl.UserDAOImpl;
import com.qianfeng.orderfood.entity.User;
import com.qianfeng.orderfood.eums.UserLoginEnum;
import com.qianfeng.orderfood.eums.UserRegisterEnum;
import com.qianfeng.orderfood.util.StringUtil;

public class UserBIZImpl implements UserBIZ {
	
	UserDAO userDAO = new UserDAOImpl();
	
	//用户登录
	public String userLogin(String username, String password,
			String validatecode, String syscode, HttpServletRequest request) {
		if (StringUtil.isEmpty(username)) {
			return UserLoginEnum.USER_NAME_IS_NUll.getValue();
		}
		if (StringUtil.isEmpty(password)) {
			return UserLoginEnum.USER_PASSWORD_IS_NULL.getValue();
		}
		if (StringUtil.isEmpty(validatecode) || StringUtil.isEmpty(syscode)) {
			return UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getValue();
		}
		if (!validatecode.equals(syscode)) {
			return UserLoginEnum.USER_VALIDATE_CODE_IS_FAIL.getValue();
		}
		User user = null;
		user = userDAO.userLogin(username,password);
		if (user == null) {
			return UserLoginEnum.USER_NAME_OR_PASSWORD_IS_FAIL.getValue();
		}
		// 登录成功后 把当前登录成功后的用户 存入到SESSION中 基本是 所有后台的必备功能
		request.getSession().setAttribute("user", user);
		
	
		return UserLoginEnum.USER_LOGIN_SUCCESS.getValue();
	}
	
	
	//用户注册
	public String userRegister(String username, String password, String againpassword,
			String validatecode, String syscode, HttpServletRequest req) {
		
		if (StringUtil.isEmpty(username)) {
			return UserRegisterEnum.USER_REGISTER_NAME_IS_NULL.getValue();
		}
		if (StringUtil.isEmpty(password)) {
			return UserRegisterEnum.USER_REGISTER_PASSWORD_IS_NULL.getValue();
		}
		if (StringUtil.isEmpty(validatecode)) {
			return UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_NULL.getValue();
		}
		if(!password.equals(againpassword)){
			return UserRegisterEnum.USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT.getValue();
		}
		if (!validatecode.equals(syscode) || StringUtil.isEmpty(syscode)) {
			return UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_FAIL.getValue();
		}
		
		User user = null;
		user = userDAO.userToRegister(username);
		if (user != null) {
			return UserRegisterEnum.USER_REGISTER_NAME_IS_EXIST.getValue();
		}
		
		Integer executeCount =  null;
		executeCount = userDAO.userRegister(username, password);
		if(executeCount != null){
			return UserRegisterEnum.USER_REGISTER_SUCCESS.getValue();
		}
		
		return null;
	}

}

(10)在包com.qianfeng.orderfood.dao下创建dao层接口UserDAO;

package com.qianfeng.orderfood.dao;
import com.qianfeng.orderfood.entity.User;

public interface UserDAO {
	// 阿里规范 公开 的 抽象的 这两个 描述 不需要手动的写出来
		//用户登录
		User userLogin(String username, String password);
		
		//用户注册
		int userRegister(String username, String password);
		
		//判断注册用户名存在否
		User userToRegister(String username);
}

(11)在包com.qianfeng.orderfood.daoimpl下创建类实现dao层接口UserDAOImpl;

package com.qianfeng.orderfood.daoimpl;

import java.sql.SQLException;

import com.qianfeng.orderfood.dao.UserDAO;
import com.qianfeng.orderfood.entity.User;
import com.qianfeng.orderfood.util.JDBCUtil;

public class UserDAOImpl implements UserDAO {

	
	//用户登录,查询用户是否存在
	public User userLogin(String username, String password) {
		User user = null;
		java.sql.Connection connection = null;
		java.sql.PreparedStatement preparedStatement = null;
		java.sql.ResultSet resultSet = null;
		
		try {
			connection = JDBCUtil.getConnection();
			preparedStatement = connection.prepareStatement("select userid,username,password from user where username=? and password=?");
			preparedStatement.setObject(1, username);
			preparedStatement.setObject(2, password);
			resultSet = preparedStatement.executeQuery();
			
			while (resultSet.next()) {
				user = new User();
				user.setUserid(resultSet.getInt("USERID"));
				user.setUsername(resultSet.getString("USERNAME"));
				user.setPassword(resultSet.getString("PASSWORD"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(resultSet, preparedStatement, connection);
		}
		return user;
	}
	
	
	//用户注册过程,判断用户名存在否
	public User userToRegister(String username) {
		User user = null;
		java.sql.Connection connection = null;
		java.sql.PreparedStatement preparedStatement = null;
		java.sql.ResultSet resultSet = null;
		
		try {
			connection = JDBCUtil.getConnection();
			preparedStatement = connection.prepareStatement("select username from user where username=?");
			preparedStatement.setObject(1, username);
			resultSet = preparedStatement.executeQuery();
			
			while (resultSet.next()) {
				user = new User();
				user.setUsername(resultSet.getString("USERNAME"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(resultSet, preparedStatement, connection);
		}
		return user;
	}

	
	//用户注册过程,创建新用户
	public int userRegister(String username, String password) {
		User user = null;
		java.sql.Connection connection = null;
		java.sql.PreparedStatement preparedStatement = null;
		int executeCount = 0;
		
		try {
			connection = JDBCUtil.getConnection();
			preparedStatement = connection.prepareStatement("insert into user (username,password) values(?,?)");
			preparedStatement.setObject(1, username);
			preparedStatement.setObject(2, password);
			executeCount = preparedStatement.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.close(preparedStatement, connection);
		}
		return executeCount;
	}

}

部署到tomcat容器上,运行。

3.测试效果

登录页面展示:
Javaweb常用登录和注册功能实现(详细步骤)_第7张图片

场景测试:
(1)登录成功测试Javaweb常用登录和注册功能实现(详细步骤)_第8张图片
登录成功:跳转至index.jsp页面(可自行修改,在UserLoginServlet类中)
Javaweb常用登录和注册功能实现(详细步骤)_第9张图片

(2)密码(用户名同理)错误(原密码:123456
错误密码:1234567):
Javaweb常用登录和注册功能实现(详细步骤)_第10张图片
Javaweb常用登录和注册功能实现(详细步骤)_第11张图片

(3)测试验证码错误:
正确验证码:uk28
错误验证码:uk
Javaweb常用登录和注册功能实现(详细步骤)_第12张图片
Javaweb常用登录和注册功能实现(详细步骤)_第13张图片

登录测试大致到此为止;详细测试可自行运行查看(代码完整可运行),亲测有效。

4.注册功能实现,紧接上文,继续码

有很多其实已经完成,和登录功能可共用,注册功能实现具体详细步骤如下;
(1)在WebRoot下创建user_register.jsp(注意大小写)

<%@page import="com.qianfeng.orderfood.util.ValidateUtil"%>
<%@page import="com.qianfeng.orderfood.eums.UserRegisterEnum"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<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">
	
	
	<script type="text/javascript">

	<%String msg = request.getParameter("msg") == null ? "" : request
					.getParameter("msg");%>
					
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_NAME_IS_EXIST.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_NAME_IS_EXIST.getDesc()%>");
	<%}%>			
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_NAME_IS_NULL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_NAME_IS_NULL.getDesc()%>");
	<%}%>
					
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_PASSWORD_IS_NULL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_PASSWORD_IS_NULL.getDesc()%>");
	<%}%>
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT.getDesc()%>");
	<%}%>
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_NULL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_NULL.getDesc()%>");
	<%}%>
	
	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_FAIL.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_VALIDATE_CODE_IS_FAIL.getDesc()%>");
	<%}%>

	<%if (msg.equals(UserRegisterEnum.USER_REGISTER_SUCCESS.getValue())) {%>
	 alert("<%=UserRegisterEnum.USER_REGISTER_SUCCESS.getDesc()%>");
<%}%>
	
script>

  head>
  
   <body >
  	<div style="position: absolute;top:0;bottom: 0;left: 0;right: 0;height: 300px;width: 500px;margin:auto;">
  	<form action="UserRegisterServlet" method="post">
  		<center><h1 style="color:red">用户注册h1>
  		<table style="text-align:justify;text-align-last: justify;">
  			<tr>
  				<td>用户名:td>
  				<td><input name="username">td>
  			tr>
  			<tr>
  				<td>密  码:td>
  				<td><input name="password">td>
  			tr>
  			<tr>
  				<td>确认密码:td>
  				<td><input name="againpassword">td>
  			tr>
  			<tr>
 				<%
					String validateCode = ValidateUtil.createValidateCode();
					session.setAttribute("syscode", validateCode);
				%>
  				<td>验证码:td>
  				<td><input name="validatecode">td>
  				<td><b><i style="color: red"><%=validateCode%>i> b>td>
  			tr>
  			
  			<tr>
  					
	  			<td><button type="submit">注册button>td>
	  			<td><input type="button" value="返回" onclick="location='user_login.jsp'"/>td>
  			tr>
  		table>center>
  	form>
  	div>
  body>
html>

效果如下图所示:
Javaweb常用登录和注册功能实现(详细步骤)_第14张图片

(2)在包com.qianfeng.orderfood.eums下创建注册场景类UserRegisterEnum;

package com.qianfeng.orderfood.eums;

public enum UserRegisterEnum {
	
	// 枚举的格式   是全部要大写 多个单词 用下划线隔开
	// ctrl + shift + y + x  (大小写转换)
	// 一个功能如果 有涉及到业务场景 那么这个时候 我们就要考虑到封装一个枚举文件 用来记录这些业务场景,而不是
	// 让开发开发人员去死记硬背 这些 单词
	
	USER_REGISTER_NAME_IS_EXIST("user_register_name_is_exist","该用户名已存在"),
	USER_REGISTER_NAME_IS_NULL("user_register_name_is_null","注册的用户名不能为空"),
	USER_REGISTER_PASSWORD_IS_NULL("user_register_password_is_null","注册的密码不能为空"),
	USER_REGISTER_AGAINPASSWORD_IS_DIFFERENT("user_register_againpassword_is_different","两次密码不一致"),
	USER_REGISTER_VALIDATE_CODE_IS_NULL("user_register_validate_code_is_null","验证码不能为空"),
	USER_REGISTER_VALIDATE_CODE_IS_FAIL("user_register_validate_code_is_fail","验证码错误"),
	USER_REGISTER_SUCCESS("user_register_success","注册成功");
	
	private String value;
	private String desc;
	
	private UserRegisterEnum(String value, String desc) {
		this.value = value;
		this.desc = desc;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}
}

(3)在包 com.qianfeng.orderfood.servlet下创建注册响应类UserRegisterServlet;

package com.qianfeng.orderfood.servlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qianfeng.orderfood.biz.UserBIZ;
import com.qianfeng.orderfood.bizimpl.UserBIZImpl;
import com.qianfeng.orderfood.eums.UserLoginEnum;
import com.qianfeng.orderfood.eums.UserRegisterEnum;

public class UserRegisterServlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp){
		String result = null;
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String againpassword = req.getParameter("againpassword");
		String validatecode = req.getParameter("validatecode");
		String syscode = (String) req.getSession().getAttribute("syscode");
		try {
			UserBIZ userBIZ = new UserBIZImpl();
			result = userBIZ.userRegister(username, password, againpassword, validatecode, syscode, req);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			if (result.equals(UserRegisterEnum.USER_REGISTER_SUCCESS.getValue())) {
				req.getRequestDispatcher("user_login.jsp?msg=" + result + "").forward(
						req, resp);
			} else {
				req.getRequestDispatcher("user_register.jsp?msg=" + result + "")
						.forward(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

注意:web.xml配置,将下列代码加入web.xml

 <servlet>
    <description>This is the description of my J2EE componentdescription>
    <display-name>This is the display name of my J2EE componentdisplay-name>
    <servlet-name>UserRegisterServletservlet-name>
    <servlet-class>com.qianfeng.orderfood.servlet.UserRegisterServletservlet-class>
  servlet>
  <servlet>

 <servlet-mapping>
    <servlet-name>UserRegisterServletservlet-name>
    <url-pattern>/UserRegisterServleturl-pattern>
  servlet-mapping>

具体接口及实现在上文代码中都有(没有删除),如果之前是按步骤全部复制代码的话,到这里就可以部署运行了。如果不需要注册,只要将接口和实现删掉就可以(有注释说明,不删也可以)

5、测试注册功能:

(1)注册用户存在测试:
admin是在最初已经插入的数据(第一个大步骤中的数据库图片有显示)
Javaweb常用登录和注册功能实现(详细步骤)_第15张图片
Javaweb常用登录和注册功能实现(详细步骤)_第16张图片

(2)测试两次密码不一致:
密码:123456
确认密码:1234567
Javaweb常用登录和注册功能实现(详细步骤)_第17张图片
Javaweb常用登录和注册功能实现(详细步骤)_第18张图片

(3)测试注册成功:
当前数据库存在用户:
Javaweb常用登录和注册功能实现(详细步骤)_第19张图片

注册新用户CDSN
Javaweb常用登录和注册功能实现(详细步骤)_第20张图片
注册成功返回登录界面:
Javaweb常用登录和注册功能实现(详细步骤)_第21张图片

查看数据库,CSDN用户存在(可和之前对比);
Javaweb常用登录和注册功能实现(详细步骤)_第22张图片

到了这里,登录注册功能也就粗略完成了,当然还可以对密码进行加密,这里就不细说,感兴趣的可以自己参试一下。

登录注册功能总结到此为止,有需要的可以参考,无需求请轻喷,共同学习共同进步。

你可能感兴趣的:(java,mysql,web)