1、我们来看程序的代码

数据库层:

1、通过激活码查找到对应的用户

2、设置用户的激活状态

2、业务层

1、通过数据库接口通过验证码得到对应的用户

2、判断当用户是否为空,如果没有通过激活码查找到对应的用户,说明用户点击邮箱上传的激活码是无效的,这个时候说明激活失败,抛出一个业务失败异常,说明激活码无效

3、如果用户不为空,并且用户的激活状态是没有激活的,将用户的激活状态设置成true

4、如果用户不为空,但是用户的激活状态是已经激活的,抛出一个业务失败异常,提示用户无需重复激活

3、servlet就是调用业务层的方法进行激活,对业务层返回的异常进行处理,在界面上提示激活成功还是激活失败。我们来看程序的代码

package com.weiyuan.goods.user.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler; import com.weiyuan.goods.user.domian.User; import cn.itcast.jdbc.TxQueryRunner; public class UserDao { //操作数据库
private TxQueryRunner qr = new TxQueryRunner(); /***
* 查询用户名是否存在
* @throws SQLException
*/
public boolean ajaxValidateLoginName(String loginName) throws SQLException{
//获得满足记录的数目是对象,返回一个整数,整数是单行单列使用ScalarHandler
String sql ="select count(*) from t_user where loginname=?";
Number num = (Number) qr.query(sql, new ScalarHandler(),loginName);
int count = num.intValue(); if(count>){
return true;
}
return false;
} /***
* 查询邮箱是否存在
* @throws SQLException
*/
public boolean ajaxValidateEmail(String email) throws SQLException{
//获得满足记录的数目是对象,返回一个整数,整数是单行单列使用ScalarHandler
String sql ="select count(*) from t_user where email=?";
Number num = (Number) qr.query(sql, new ScalarHandler(),email);
int count = num.intValue();
System.out.println("count="+count);
if(count>){
return true;
}
return false;
} /***
* 添加注册的用户
* @throws SQLException
*/
public void addUser(User user) throws SQLException{
//获得满足记录的数目是对象,返回一个整数,整数是单行单列使用ScalarHandler
String sql ="insert into t_user values(?,?,?,?,?,?)";
System.out.println("user="+user.toString());
Object[] params = {user.getUid(),user.getLoginname(),user.getLoginpass(),
user.getEmail(),user.getStatus(),user.getActivationCode()};
qr.update(sql, params);
} /*
* 通过激活码获得用户
* */
public User findUserByActivationCode(String activationCode) throws SQLException{ String sql = "select * from t_user where activationCode = ?";
return qr.query(sql, new BeanHandler<User>(User.class),activationCode);
} /*
* 设置用户的激活状态
* */ public void setUserActivationCode(String uuid,int status) throws SQLException{
String sql = "update t_user set status = ? where uid = ? ";
qr.update(sql,status,uuid);
} }

我们来看业务层的代码:

package com.weiyuan.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 javax.management.RuntimeErrorException; import cn.itcast.commons.CommonUtils;
import cn.itcast.mail.Mail;
import cn.itcast.mail.MailUtils; import com.weiyuan.goods.user.dao.UserDao;
import com.weiyuan.goods.user.domian.User; public class UserService { private UserDao dao = new UserDao(); public boolean ajaxValidateLoginName(String loginName) { try {
return dao.ajaxValidateLoginName(loginName);
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
} } public boolean ajaxValidateEmail(String email) { try {
return dao.ajaxValidateEmail(email);
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
} } //添加注册的用户
public void addUser(User user){
//添加用户的uuid
user.setUid(CommonUtils.uuid());
//添加用户的激活码
String activationCode = CommonUtils.uuid()+CommonUtils.uuid();
user.setActivationCode(activationCode);
//当前处于未激活的状态
user.setStatus();//0表示未激活 try {
dao.addUser(user);
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage());
} //向注册的用户发送邮件
//1读取配置文件
Properties properties = new Properties();
try {
properties.load(this.getClass().getClassLoader().getResourceAsStream("email_template.properties"));
} catch (IOException e1) {
throw new RuntimeException(e1.getMessage());
} String host = properties.getProperty("host"); //qq邮箱发送邮件的地址,端口465或者587
//qq接受邮件服务器的地址是pop.qq.com,端口995
String username=properties.getProperty("username"); //登陆服务器的账号
String password=properties.getProperty("password");//这里不是客户端登陆的密码,而是授权密码一定要注意
Session session = MailUtils.createSession(host, username, password);
//发送邮件
String from = properties.getProperty("from");//发件人
String to = user.getEmail();//收件人
String title = properties.getProperty("subject");
String content = properties.getProperty("content");
Object [] array = new Object[]{user.getActivationCode()};
//替换占位符
String formatContent = MessageFormat.format(content, user.getActivationCode());//替换占位符
System.out.println("email content is:"+content);
Mail mail = new Mail(from,to,title,formatContent);
try {
MailUtils.send(session, mail);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} } /*设置用户的激活状态*/ public void activation(String activationCode) throws Exception{
//1 、通过激活码查找对应的用户信息
try {
User user = dao.findUserByActivationCode(activationCode);
if(user == null){
throw new Exception("无效的激活码");//业务异常,业务失败
}
if(user.getStatus()== ){
throw new Exception("用户已经既激活,不要二次激活");//业务异常,业务失败
}
dao.setUserActivationCode(user.getUid(), ); //1表示激活
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage()); // 不是业务的异常吗,而是电脑环境系统数据库的异常,直接退出线程,无法进行业务的操作了
} } }

我们来看servlet的代码

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

import java.io.IOException;
import java.util.Map; 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 org.apache.commons.collections.map.HashedMap; import com.weiyuan.goods.user.domian.User;
import com.weiyuan.goods.user.service.UserService; import cn.itcast.commons.CommonUtils;
import cn.itcast.servlet.BaseServlet; /**
* Servlet implementation class UserServlet
*/
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet{
private static final long serialVersionUID = 1L;
private UserService service = new UserService();
/*
* 用户注册页面使用ajax校验/*
* 用户注册页面使用ajax校验用户名会调用该方法
* *会调用该方法
* */
public String validateLoginname(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//首先获得用户上传的用户名
String loginName = request.getParameter("loginname");
boolean flag = service.ajaxValidateLoginName(loginName);
response.getWriter().print(flag);
return null;
}
/*
* 用户注册页面使用ajax校验邮箱会调用该方法
* */
public String validateEmail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//获得用户上传的emai String email = request.getParameter("email");
System.out.println("validateEmail is called"+email);
boolean flag = service.ajaxValidateEmail(email);
response.getWriter().print(flag);
return null;
} /*
* 用户注册页面使用ajax校验验证码会调用该方法
* */
public String validateVerifyCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//获得用户上传的verfycode
String verifyCode = request.getParameter("verifyCode");
//获得session中保存的验证码
String sessionCode = (String) request.getSession().getAttribute("vCode");
//二者进行比较看是否相等
System.out.println("validateVerifyCode is called"+verifyCode+":"+sessionCode);
boolean flag = sessionCode.equalsIgnoreCase(verifyCode);
response.getWriter().print(flag);
return null;
} /*
* 当用户从邮箱点击的激活的时候会调用该方法,并且把激活码传递过来
*
* */
public String activation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub String activationCode = request.getParameter("activationCode");
System.out.println("email activationCode is :"+activationCode);
try {
service.activation(activationCode);
//激活成功
request.setAttribute("code", "success"); //msg.jsp已经code的值来显示错误信息还是正确的信息
request.setAttribute("msg", "激活成功");
return "f:/jsps/msg.jsp";
} catch (Exception e) {
//将业务操作的异常信息在msg.jsp中显示出来
String msg = e.getMessage();
request.setAttribute("code", "error"); //msg.jsp已经code的值来显示错误信息还是正确的信息
request.setAttribute("msg", msg);
return "f:/jsps/msg.jsp"; } } /*
* 当用户注册的时候会调用该方法
*
* */
public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("activation is called"); //1、将请求的参数封装成User对象
User user = CommonUtils.toBean(request.getParameterMap(), User.class);
//2 、对传递过来的参数进行校验,把错误的信息封装到一个hashMap中
Map errors = validateParams(user, request);
if(errors.size() > ){//说明参数错误,跳转到注册界面提示用户输入的参数有误
request.setAttribute("errors", errors);
request.setAttribute("user", user);
return "f:/jsps/user/regist.jsp";
}
service.addUser(user);
request.setAttribute("code", "success");
request.setAttribute("msg", "用户注册成功,请马上到邮箱进行激活");
return "f:/jsps/msg.jsp"; } public Map validateParams(User user,HttpServletRequest request){
Map<String, String> map = new HashedMap();
//校验用户名
String loginName = user.getLoginname();
if(loginName == null || loginName.isEmpty()){
map.put("loginname", "用户名不能为空");
}
if(loginName.length() < || loginName.length() > ){
map.put("loginname", "用户名长度应该在3到20之间");
}
//校验用户名是否注册
if(service.ajaxValidateLoginName(loginName)){
map.put("loginname", "用户名已经被注册");
} //检查登陆密码
String loginpass = user.getLoginpass();
if(loginpass == null || loginpass.isEmpty()){
map.put("loginpass", "登陆密码不能为空");
}
if(loginpass.length() < || loginpass.length() > ){
map.put("loginname", "登陆密码的长度应该在3到20之间");
} //检查确认密码的信息
//检查登陆密码
String reloginpass = user.getReloginpass();
if(reloginpass == null || reloginpass.isEmpty()){
map.put("reloginpass", "登陆密码不能为空");
}
if(reloginpass.length() < || reloginpass.length() > ){
map.put("reloginpass", "登陆密码的长度应该在3到20之间");
}
if(!reloginpass.equalsIgnoreCase(loginpass)){
map.put("reloginpass", "两次输入的密码不一样");
} //检查邮箱
String email = user.getEmail();
if(email == null || email.isEmpty()){
map.put("email", "登陆邮箱不能为空");
}
//检查邮箱的格式是否正确
if(!email.matches("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$")){
map.put("email", "邮箱格式不正确");
} //检查验证码是否相等
String verifyCode = user.getVerifyCode();
//获得session中保存的验证码
String sessionCode =(String) request.getSession().getAttribute("vCode");
if(!verifyCode.equalsIgnoreCase(sessionCode)){
map.put("verifyCode", "验证码不正确");
} return map; } }

对应激活这个操作:激活业务的结果就是:

激活成功

激活码无效

重复激活

三种结果

所以在业务层,如果是激活码无效和重复激活这两个业务操作失败的我们需要通过抛出异常,让外面的调用者servlet知道业务失败的原因,然后servlet对异常进行处理,在对应的界面msg.jsp中将业务操作的结果显示处理。

同时在业务操作的过程中,还存在其他异常导致业务操作失败,列如数据库的sql异常,但是这个异常不是业务本身的异常,而是数据库的异常,这个时候我们不想让servlet调用者知道,我们就直接在业务层中

  throw new RuntimeException(e.getMessage());抛出一个运行时的异常,直接退出程序。这就是
throw new RuntimeException(e.getMessage())和throw new Exception(e.getMessage())的区别。

JavaWeb网上图书商城完整项目--day02-12.激活功能各层实现的更多相关文章

  1. JavaWeb网上图书商城完整项目--day02-6.ajax校验功能之页面实现

    1 .现在我们要在regist.js中实现ajax的功能,使用用户名到后台查询是否注册,邮箱是否到后台注册,验证码是否正确的功能 我们来看regist.js的代码 //该函数在html文档加载完成之后 ...

  2. JavaWeb网上图书商城完整项目--day02-5.ajax校验功能之服务器端三层实现

    regist.jsp页面中有异步请求服务器来对表单进行校验: l  校验登录名是否已注册过: l  校验Email是否已注册过: l  校验验证码是否正确. 这说明在UserServlet中需要提供相 ...

  3. JavaWeb网上图书商城完整项目--day02-19.修改密码功能流程分析

    我们来看看修改密码的业务流程操作:

  4. JavaWeb网上图书商城完整项目--day02-4.regist页面提交表单时对所有输入框进行校验

    1.现在我们要将table表中的输入的参数全部提交到后台进行校验,我们提交我们是按照表单的形式提交,所以我们首先需要在table表外面添加一个表单 <%@ page language=" ...

  5. JavaWeb网上图书商城完整项目--24.注册页面的css样式实现

    现在框架已经做好了,即下来我们要对页面进行装饰了,第一步给每一个元素添加id 1.最外面的div添加id为divMain 2.第二个div添加id为divTitle,里面的span对应的id为span ...

  6. JavaWeb网上图书商城完整项目--12.项目所需jquery函数介绍之ajax

    jquery中使用ajax发送异步请求 下面的一个案例在input输入框失去焦点的时候发送一个异步的请求: 我们来看程序的案例: 这里要强调的是返回值最好选择是json,json对应的就是对象,Jav ...

  7. JavaWeb网上图书商城完整项目--过滤器解决中文乱码

    我们知道,如果是POST请求,我们需要调用request.setCharacterEncoding(“utf-8”)方法来设计编码:如果是GET请求,我们需要自己手动来处理编码问题.如果我们使用了En ...

  8. JavaWeb网上图书商城完整项目--13.项目所需环境的搭建

    1.首先安装mysql 创建项目所需的数据库,直接运行项目提供的goods.sql文库 2.myeclipse创建一个web project ,项目的名称是goods 把视频中提供的项目原型下的提供的 ...

  9. JavaWeb网上图书商城完整项目--BaseServlet

    1.以前进行操作的时候,例如我们进行登陆操作我们使用LoginServlet进行处理,进行注册操作我们使用RegisterServlet,很多业务的操作的时候我们就要定义很多个Servlet 有了Ba ...

  10. JavaWeb网上图书商城完整项目--day02-21.退出功能的实现

    1.当用户点击退出的时候,跳转到登陆页面 当用户点击退出的时候,需要将session中保存的登陆的用户销毁掉 当用户点击退出的时候,调用UserServlet的quit方法 退出按钮在top.jsp中 ...

随机推荐

  1. spring-kafka之KafkaListener注解深入解读

    简介 Kafka目前主要作为一个分布式的发布订阅式的消息系统使用,也是目前最流行的消息队列系统之一.因此,也越来越多的框架对kafka做了集成,比如本文将要说到的spring-kafka. Kafka ...

  2. static关键字修饰属性

    static 静态的,可以修饰属性,方法,代码块(或初始化块) , 内部内 非static修饰的属性(实例变量):各个对象各自拥有一套各自的副本 static修饰属性(l类变量): 1.由类创建的所有 ...

  3. Excel表格中无法中间插入新行列! 提示:在当前工作表的最后一行或列中,存在非空单元格,解决方案

    excel中新增行列时报错: 提示:在当前工作表的最后一行或列中,存在非空单元格,所以无法插入新行或新列.

  4. F5忘记密码修改教程

    !!!首先查看系统版本,13版本和14版本修改密码方式不一致 首先介绍13版本修改密码 注:12版本也适用,11版本未测试,应该也可以,有问题欢迎留言) 1. 将终端连接到BIG-IP串行控制台端口. ...

  5. Java实现 LeetCode 589 N叉树的前序遍历(遍历树)

    589. N叉树的前序遍历 给定一个 N 叉树,返回其节点值的前序遍历. 例如,给定一个 3叉树 : 返回其前序遍历: [1,3,5,6,2,4]. 说明: 递归法很简单,你可以使用迭代法完成此题吗? ...

  6. Java实现 LeetCode 563 二叉树的坡度(又是一个遍历树)

    563. 二叉树的坡度 给定一个二叉树,计算整个树的坡度. 一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值.空结点的的坡度是0. 整个树的坡度就是其所有节点的坡度之和. ...

  7. Java实现 LeetCode 52 N皇后 II

    52. N皇后 II n 皇后问题研究的是如何将 n 个皇后放置在 n×n 的棋盘上,并且使皇后彼此之间不能相互攻击. 上图为 8 皇后问题的一种解法. 给定一个整数 n,返回 n 皇后不同的解决方案 ...

  8. Java实现 蓝桥杯 算法提高 字符串压缩

    试题 算法提高 字符串压缩 资源限制 时间限制:1.0s 内存限制:256.0MB 问题描述 编写一个程序,输入一个字符串,然后采用如下的规则对该字符串当中的每一个字符进行压缩: (1) 如果该字符是 ...

  9. 第七届蓝桥杯JavaC组国(决)赛真题

    解题代码部分来自网友,如果有不对的地方,欢迎各位大佬评论 题目1.平方末尾 能够表示为某个整数的平方的数字称为"平方数" 比如,25,64 虽然无法立即说出某个数是平方数,但经常可 ...

  10. Python基础语法之“print()”函数

    print()函数是Python入门的第一个必学知识点,它经常被用来调试已写的代码,检验效果,今天小老鼠就带你盘点一下print()函数在Python中如何使用. print()函数的工作流程是这样的 ...