您的位置:首页 > 其它

网上图书商城项目学习笔记-004注册页面前后台的验证、注册功能实现、激活功能实现

2016-01-24 23:42 766 查看
一、功能分析

1.注册页面前后台的验证



2.注册功能实现



3.激活功能实现



二、代码实现

1.前端验证

$(function() {
/*
* 1. 得到所有的错误信息,循环遍历之。调用一个方法来确定是否显示错误信息!
*/
$(".labelError").each(function() {
showError($(this));//遍历每个元素,使用每个元素来调用showError方法
});

/*
* 2. 切换注册按钮的图片
*/
$("#submitBtn").hover(
function(){$(this).attr("src", "/goods/images/regist2.jpg")},
function(){$(this).attr("src", "/goods/images/regist1.jpg")}
);

/*
* 3. 输入框得到焦点隐藏错误信息
*/
$(".input").focus(function() {
var labelId = $(this).attr("id") + "Error";//通过输入框找到对应的label的id
var domEl = $("#" + labelId);
domEl.text("");//把label的内容清空!
showError(domEl);//隐藏没有信息的label
});

/*
* 4. 输入框失去焦点进行校验
*/
$(".input").blur(function() {
var id = $(this).attr("id");//获取当前输入框的id
var funName = "validate" + id.substring(0,1).toUpperCase() + id.substring(1) + "()";//得到对应的校验函数名
eval(funName);//执行函数调用
});

/*
* 5. 表单提交时进行校验
*/
$("#registForm").submit(function() {
var result = true;
if(!validateLoginname()) result = false;
if(!validateLoginpass()) result = false;
if(!validateReloginpass()) result = false;
if(!validateEmail()) result = false;
if(!validateVerifyCode()) result = false;
return result;
});
})

/*
* 登录名校验方法
*/
function validateLoginname() {
var $id = "#loginname";
var value = $($id).val();//获取输入框内容
var $errorId = $id + "Error";
/*
*  1. 非空校验
*/
if(!value) {
/*
* 获取对应的label
* 添加错误信息
* 显示label
*/
processError($errorId, "用户名不能为空!");
return false;
}
/*
* 2. 长度校验
*/
if(value.length < 3 || value.length > 20) {
/*
* 获取对应的label
* 添加错误信息
* 显示label
*/
processError($errorId, "用户名长度必须在3 ~ 20之间!");
return false;
}
/*
* 3. 是否注册校验
*/
$.ajax({
url:"/goods/UserServlet",
data:{method : "validateLoginname", loginname:value},
type:"POST",
dataType:"json",
asycn:false,//是否异步请求,如果是异步,那么不会等服务器返回,我们这个函数就向下运行了。
cache:false,
success:function(result) {
if(!result) {
processError($errorId, "用户名已被注册!");
return false;
}
}
});
return true;
}

/*
* 登录密码校验方法
*/
function validateLoginpass() {
var $id = "#loginpass";
var $errorId = $id + "Error";
var value = $($id).val();
if(!value) {
processError($errorId, "密码不能为空!");
return false;
}
if(value.length < 3 || value.length > 20) {
processError($errorId, "密码长度必须在3 ~ 20之间!");
return false;
}
return true;
}

/*
* 确认密码校验方法
*/
function validateReloginpass() {
var $id = "#reloginpass";
var $errorId = $id + "Error";
var value = $($id).val();
if(!value) {
processError($errorId, "确认密码不能为空!");
return false;
}
if(value != $("#loginpass").val()){
processError($errorId, "两次输入不一致!");
return false;
}
return true;
}

/*
* 判断当前元素是否存在内容,如果存在显示,不页面不显示!
*/
function showError(ele) {
var text = ele.text();//获取元素的内容
if(!text) {//如果没有内容
ele.css("display", "none");//隐藏元素
} else {//如果有内容
ele.css("display", "");//显示元素
}
}

/**
* Email校验方法
*/
function validateEmail() {
var $id = "#email";
var $errorId = $id + "Error";
var value = $($id).val();
if(!value){
processError($errorId, "Email不能为空!");
return false;
}
//Email格式校验
if(!/^([a-zA-Z0-9_-])+@([a-zA-Z-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(value)) {
processError($errorId, "错误的Email格式!");
return false;
}
$.ajax({
url     : "/goods/UserServlet",
data    : {method : "validateEmail", email : value},
type    : "post",
dataType: "json",
async   : false,
cache   : false,
success : function(result) {
if(!result) {
processError($errorId, "Email已被注册!");
return false;
}
}
});
return true;
}

/*
* 验证码校验方法
*/
function validateVerifyCode() {
var $id = "#verifyCode";
var $errorId = $id + "Error";
var value = $($id).val();
if(!value) {
processError($errorId, "验证码不能为空!");
return false;
}

//长度验证
if(value.length != 4) {
processError($errorId, "错误的验证码!");
return false;
}

//是否正确
$.ajax({
url : "/goods/UserServlet",
data : {method : "validateVerifyCode", verifyCode : value},
type : "POST",
dataType : "json",
asyc : false,
cache : false,
success : function(result) {
if(!result) {
processError($errorId, "验证码错误!");
return false;
}
}
});
return true;
}

/*
* 换一张验证码
*/
function _changeVerifyCode() {
/*
* 1. 获取<img>元素
* 2. 重新设置它的src
* 3. 使用毫秒来添加参数
*/
$("#vCode").attr("src", "/goods/VerifyCodeServlet?'/>" + new Date().getTime());
}

/*
* 校验完后调用此方法进行错误信息处理
*/
function processError($errorId, msg) {
var errorEl = $($errorId);
errorEl.text(msg);
showError(errorEl);
return;
}


2.后台验证

(1)servlet层

  a).UserServlet.java

package com.tony.goods.user.web.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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

import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet;

import com.tony.goods.user.domain.User;
import com.tony.goods.user.service.UserService;
import com.tony.goods.user.service.exception.UserException;

/**
* 用户模块WEB层
* @author T
*
*/
public class UserServlet extends BaseServlet {

private UserService userService = new UserService();

/**
* 用户名是否注册校验
* @param request
* @param response
* @return
* @throws IOException
*/
public String validateLoginname(HttpServletRequest request, HttpServletResponse response) throws IOException {
String loginname = request.getParameter("loginname");
boolean result = userService.validateLoginname(loginname);
response.getWriter().print(result);
return null;
}

/**
* Email是否注册校验
* @param request
* @param response
* @return
* @throws IOException
*/
public String validateEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
String email = request.getParameter("email");
boolean result = userService.validateEmail(email);
response.getWriter().print(result);
return null;
}

/**
* Email是否注册校验
* @param request
* @param response
* @return
* @throws IOException
*/
public String validateVerifyCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//1. 获取输入框中的验证码
String verifyCode = request.getParameter("verifyCode");
//2. 获取图片上真实的校验码
String vCode = (String) request.getSession().getAttribute("vCode");
//3. 进行忽略大小写比较,得到结果
boolean result = verifyCode.equalsIgnoreCase(vCode);
response.getWriter().print(result);
return null;
}

public String regist(HttpServletRequest request, HttpServletResponse response) {
//1. 封装表单数据到User对象
User formUser = CommonUtils.toBean(request.getParameterMap(), User.class);

//2. 校验之, 如果校验失败,保存错误信息,返回到regist.jsp显示
Map<String, String> errors = validateRegist(formUser, request.getSession());
if(errors.size() > 0) {
request.setAttribute("form", formUser);
request.setAttribute("errors", errors);
return "f:/jsps/user/regist.jsp";
}
//3. 使用service完成业务,会 发激活链接到邮箱
userService.regist(formUser);

//4. 保存成功信息,转发到msg.jsp显示!
request.setAttribute("code", "success");
request.setAttribute("msg", "注册成功,请马上到邮箱激活!");
return "f:/jsps/msg.jsp";
}

/**
* 注册校验
* 对表单的字段进行逐个校验,如果有错误,使用当前字段名称为key,错误信息为value,保存到map中
* 返回map
*/
private Map<String, String> validateRegist(User formUser, HttpSession session) {
Map<String, String> errors = new HashMap<String, String>();
// 1. 校验登录名
String loginname = formUser.getLoginname();
if(loginname == null || loginname.trim().isEmpty()) {
errors.put("loginname", "用户名不能为空!");
} else if(loginname.length() < 3 || loginname.length() > 20) {
errors.put("loginname", "用户名长度必须在3~20之间!");
} else if(!userService.validateLoginname(loginname)) {
errors.put("loginname", "用户名已被注册!");
}

// 2. 校验登录密码
String loginpass = formUser.getLoginpass();
if(loginpass == null || loginpass.trim().isEmpty())
errors.put("loginpass", "密码不能为空!");
else if(loginpass.length() < 3 || loginpass.length() > 20)
errors.put("loginpass", "密码长度必须在3~20之间!");

// 3. 确认密码校验
String reloginpass = formUser.getReloginpass();
if(reloginpass == null || reloginpass.trim().isEmpty()) {
errors.put("reloginpass", "确认密码不能为空!");
} else if(!reloginpass.equals(loginpass)) {
errors.put("reloginpass", "两次输入不一致!");
}

// 4. 校验email
String email = formUser.getEmail();
if(email == null || email.trim().isEmpty()) {
errors.put("email", "Email不能为空!");
} else if(!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")) {
errors.put("email", "Email格式错误!");
} else if(!userService.validateEmail(email)) {
errors.put("email", "Email已被注册!");
}

// 5. 验证码校验
String verifyCode = formUser.getVerifyCode();
String vCode = (String) session.getAttribute("vCode");
if(verifyCode == null || verifyCode.trim().isEmpty()) {
errors.put("verifyCode", "验证码不能为空!");
} else if(!verifyCode.equalsIgnoreCase(vCode)) {
errors.put("verifyCode", "验证码错误!");
}

return errors;
}

/**
* 激活功能
* @param request
* @param response
* @return
*/
public String activation(HttpServletRequest request, HttpServletResponse response) {
/*
* 1. 获取参数激活码
* 2. 用激活码调用service方法完成激活
*   > service方法有可能抛出异常, 把异常信息拿来,保存到request中,转发到msg.jsp显示
* 3. 保存成功信息到request,转发到msg.jsp显示。
*/
String code = request.getParameter("activationCode");
try {
userService.activate(code);
request.setAttribute("code", "success");//通知msg.jsp显示对号
request.setAttribute("msg", "恭喜,激活成功,请马上登录!");
} catch (UserException e) {
// 说明service抛出了异常
request.setAttribute("msg", e.getMessage());
request.setAttribute("code", "error");//通知msg.jsp显示X
}
return "f:/jsps/msg.jsp";
}
}


  b).BaseServlet.java

package cn.itcast.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

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

/**
* BaseServlet用来作为其它Servlet的父类
*
* @author qdmmy6
*
*         一个类多个请求处理方法,每个请求处理方法的原型与service相同! 原型 = 返回值类型 + 方法名称 + 参数列表
*/
@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");//处理响应编码

/**
* 1. 获取method参数,它是用户想调用的方法 2. 把方法名称变成Method类的实例对象 3. 通过invoke()来调用这个方法
*/
String methodName = request.getParameter("method");
Method method = null;
/**
* 2. 通过方法名称获取Method对象
*/
try {
method = this.getClass().getMethod(methodName,
HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("您要调用的方法:" + methodName + "它不存在!", e);
}

/**
* 3. 通过method对象来调用它
*/
try {
String result = (String)method.invoke(this, request, response);
if(result != null && !result.trim().isEmpty()) {//如果请求处理方法返回不为空
int index = result.indexOf(":");//获取第一个冒号的位置
if(index == -1) {//如果没有冒号,使用转发
request.getRequestDispatcher(result).forward(request, response);
} else {//如果存在冒号
String start = result.substring(0, index);//分割出前缀
String path = result.substring(index + 1);//分割出路径
if(start.equals("f")) {//前缀为f表示转发
request.getRequestDispatcher(path).forward(request, response);
} else if(start.equals("r")) {//前缀为r表示重定向
response.sendRedirect(request.getContextPath() + path);
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}


(2)service层

  a).UserService.java

package com.tony.goods.user.service;

import java.io.IOException;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;

import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils;

import com.tony.goods.user.dao.UserDao;
import com.tony.goods.user.domain.User;
import com.tony.goods.user.service.exception.UserException;

/**
* 用户模块业务层
* @author T
*
*/
public class UserService {
private UserDao userDao = new UserDao();

/**
* 用户名注册校验
* @param loginname
* @return
*/
public boolean validateLoginname(String loginname) {
try {
return userDao.validateLoginname(loginname);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

/**
* Email校验
* @param email
* @return
*/
public boolean validateEmail(String email) {
try {
return userDao.validateEmail(email);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}

public void regist(User user) {
//1. 数据的补齐
user.setUid(CommonUtils.uuid());
user.setStatus(false);
user.setActivationCode(CommonUtils.uuid() + CommonUtils.uuid());

//2. 向数据库插入
try {
userDao.add(user);
} catch (SQLException e) {
throw new RuntimeException(e);
}

//3. 发邮件
//3.1 把配置文件内容加载到prop中
Properties prop = new Properties();
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
} catch (IOException e) {
throw new RuntimeException(e);
}
//3.2  登录邮件服务器,得到session
String host = prop.getProperty("host");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
Session session = MailUtils.createSession(host, username, password);

//3.3 创建Mail对象
String from = prop.getProperty("from");
String to = user.getEmail();
String subject = prop.getProperty("subject");
// MessageForm.format方法会把第一个参数中的{0},使用第二个参数来替换。
// 例如MessageFormat.format("你好{0}, 你{1}!", "张三", "去死吧"); 返回“你好张三,你去死吧!”
String content = MessageFormat.format(prop.getProperty("content"), user.getActivationCode());
Mail mail = new Mail(from, to ,subject, content);

//3.4 发送邮件
try {
MailUtils.send(session, mail);
} catch (MessagingException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

/**
* 激活功能
* @param code
* @throws UserException
*/
public void activate(String code) throws UserException {
/*
* 1. 通过激活码查询用户
* 2. 如果User为null,说明是无效激活码,抛出异常,给出异常信息(无效激活码)
* 3. 查看用户状态是否为true,如果为true,抛出异常,给出异常信息(请不要二次激活)
* 4. 修改用户状态为true
*/
try {
User user = userDao.findByCode(code);
if(user == null) throw new UserException("无效的激活码!");
if(user.isStatus()) throw new UserException("您已经激活过了,不要二次激活!");
userDao.updateStatus(user.getUid(), true);//修改状态
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}


(3)dao层

  a).UserDao.java

package com.tony.goods.user.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;

import com.tony.goods.user.domain.User;

/**
* 用户模块持久层
* @author T
*
*/
public class UserDao {
private QueryRunner qr = new TxQueryRunner();

/**
* 通过激活码查询用户
* @param code
* @return
* @throws SQLException
*/
public User findByCode(String code) throws SQLException {
String sql = "select * from t_user where activationCode=?";
return qr.query(sql, new BeanHandler<User>(User.class), code);
}

/**
* 修改用户状态
* @param uid
* @param b
* @throws SQLException
*/
public void updateStatus(String uid, boolean status) throws SQLException {
String sql = "update t_user set status=? where uid=?";
qr.update(sql, status, uid);
}

/**
* 校验用户名是否注册
* @param loginname
* @return
* @throws SQLException
*/
public boolean validateLoginname(String loginname) throws SQLException {
String sql = "select count(1) from t_user where loginname=?";
Number number = (Number) qr.query(sql, new ScalarHandler(), loginname);
return number.intValue() == 0;
}

/**
* 校验Email是否注册
* @param email
* @return
* @throws SQLException
*/
public boolean validateEmail(String email) throws SQLException {
String sql = "select count(1) from t_user where email=?";
Number number = (Number) qr.query(sql, new ScalarHandler(), email);
return number.intValue() == 0;
}

/**
* 添加用户
* @param user
* @throws SQLException
*/
public void add(User user) throws SQLException {
String sql = "insert into t_user values(?,?,?,?,?,?)";
Object[] params = {user.getUid(), user.getLoginname(), user.getLoginpass(), user.getEmail(), user.isStatus(), user.getActivationCode()};
qr.update(sql, params);
}

}


(4)view层

  a)regist.jsp

3.配置文件

(1)web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">

<!-- 统一编码处理 -->
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>cn.itcast.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 生成验证码 -->
<servlet>
<servlet-name>VerifyCodeServlet</servlet-name>
<servlet-class>cn.itcast.vcode.servlet.VerifyCodeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>VerifyCodeServlet</servlet-name>
<url-pattern>/VerifyCodeServlet</url-pattern>
</servlet-mapping>

<!-- 用户模块的注册校验(eg:用户名是 否已注册) -->
<servlet>
<servlet-name>UserServlet</servlet-name>
<servlet-class>com.tony.goods.user.web.servlet.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<url-pattern>/UserServlet</url-pattern>
</servlet-mapping>
</web-app>


(2)email.properties

subject=\u6765\u81EAI\u65B0\u6708\u4E66\u5E97\u7684\u6FC0\u6D3B\u90AE\u4EF6
content=\u606D\u559C\uFF0C\u60A8\u5DF2\u6CE8\u518C\u6210\u529F\uFF0C\u8BF7\u70B9\u51FB<a href\="http\://localhost\:8080/goods/UserServlet?method\=activation&activationCode\={0}">\u8FD9\u91CC</a>\u5B8C\u6210\u6FC0\u6D3B\u3002
from=aaa@163.com
host=smtp.163.com
username=bbb
password=xxx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: