JavaWeb网上图书商城完整项目--day02-16.登录功能各层实现
/*1、第一步将用户提交的参数封装成javabean对象
*
*2、对提交的参数的进行合法性的校验
*
*3、通过用户名和密码去查找得到user对象
*如果user对象为null,说明用户名和密码不正确,重定向到login.jsp提示用户名和密码错误
*如果user对象不为null,查看当前用户的激活状态,如果当前用户没有被激活,提示当前用户没有被激活,重定向到login.jsp提示
*如果user对象不为null,并且当前用户处于激活状态,把当前用户保存到session中,显示当前用户是谁
*为了实现页面自定功能,需要把用户名保存到cookie中,主要cookie不支持中文,需要对
*中文进行有效性的处理。
*
*
*
* */
2、cookie解决中文乱码的问题
在学习当中碰到cookie中文乱码问题,问题原因:cookie对中文不太支持,将中文放入cookie中会报错误。
cookie中使用中文,使用URLEncoder进行编码
try {
Cookie cookie = new Cookie("animal",URLEncoder.encode("i love you -- ** 屎壳郎", "UTF-8"));
response.addCookie(cookie);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
浏览器页面中使用cookie的时候使用URLEncoder进行解码
Cookie[] cs = request.getCookies();
for(Cookie c : cs){
if(c.getName().equals("animal")){
try {
System.out.println(URLDecoder.decode(c.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
forward是服务器内部重定向,程序收到请求后重新定向到另一个程序,客户机并不知道;redirect则是服务器收到请求后发送一个状态头给客 户,客户将再请求一次,这里多了两次网络通信的来往。
forward是服务器请求资源,服务器直接访问目标地址的URL,把那个URL的响应内容读取过来,然后把这些内容再发给浏览器.浏览器根本不知道服务器发送的内容从哪里来的,所以它的地址栏还是原来的地址.
redirect是服务端根据逻辑,发送一个状态码,告诉浏览器重新去请求那个地址.所以地址栏显示的是新的URL.
我们来看看程序的代码:
dao数据层:
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>0){
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>0){
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);
} /*
* 通过用户名和密码查找得到对应的用户
* */ public User findUserByLoginnameAndPass(String loginName,String pass) throws SQLException{
String sql = "select * from t_user where loginname = ? and loginpass = ?";
return qr.query(sql, new BeanHandler<User>(User.class),loginName,pass);
} }
业务层的代码:
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);//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()== 1){
throw new Exception("用户已经既激活,不要二次激活");//业务异常,业务失败
}
dao.setUserActivationCode(user.getUid(), 1); //1表示激活
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e.getMessage()); // 不是业务的异常吗,而是电脑环境系统数据库的异常,直接退出线程,无法进行业务的操作了
} } /*
* 用户登录的业务操作,这里传递的参数是一个User对象
* */ public User login(User user){ try {
return dao.findUserByLoginnameAndPass(user.getLoginname(),user.getLoginpass());
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
} } }
Servlet层:
package com.weiyuan.goods.user.web.servlet; import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map; import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
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() > 0){//说明参数错误,跳转到注册界面提示用户输入的参数有误
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 String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("activation is called"); /*1、第一步将用户提交的参数封装成javabean对象
*
*2、对提交的参数的进行合法性的校验
*
*3、通过用户名和密码去查找得到user对象
*如果user对象为null,说明用户名和密码不正确,重定向到login.jsp提示用户名和密码错误
*如果user对象不为null,查看当前用户的激活状态,如果当前用户没有被激活,提示当前用户没有被激活,重定向到login.jsp提示
*如果user对象不为null,并且当前用户处于激活状态,把当前用户保存到session中,显示当前用户是谁
*为了实现页面自定功能,需要把用户名保存到cookie中,主要cookie不支持中文,需要对
*中文进行有效性的处理。
*
*
*
* */ User formUser = CommonUtils.toBean(request.getParameterMap(), User.class);
//对参数进行合法性的校验
//2 、对传递过来的参数进行校验,把错误的信息封装到一个hashMap中
Map errors = validateParams(formUser, request);
if(errors.size() > 0){//说明参数错误,跳转到注册界面提示用户输入的参数有误
request.setAttribute("errors", errors);
request.setAttribute("user", formUser);
return "f:/jsps/user/login.jsp";
}
User user =service.login(formUser); //判断用户是否为null
if(user == null){
request.setAttribute("msg", "输入的用户名和密码不正确");
request.setAttribute("user", formUser);
return "f:/jsps/user/login.jsp";
}else{
if(0 == user.getStatus()){ //没有激活
request.setAttribute("msg", "当前用户没有激活,请先激活该用户");
request.setAttribute("user", formUser);
return "f:/jsps/user/login.jsp";
}
//说明用户登录成功
request.getSession().setAttribute("sessionUser", user);
//将用户名保存到cookie中,因为cookie不支持中文使用URL进行编码
Cookie cookie = new Cookie("cookieLoginName", URLEncoder.encode(user.getLoginname(), "utf-8"));
cookie.setMaxAge(60*60*24);//cookie的有效期是一天
//添加cookie对象,把cookier对象返回给浏览器
response.addCookie(cookie);
//登录成功之后客户端使用redict重新登录到index.jsp主页面
return "r:/index.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() < 3 || loginName.length() > 20){
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() < 3 || loginpass.length() > 20){
map.put("loginname", "登陆密码的长度应该在3到20之间");
} //检查确认密码的信息
//检查登陆密码
String reloginpass = user.getReloginpass();
if(reloginpass == null || reloginpass.isEmpty()){
map.put("reloginpass", "登陆密码不能为空");
}
if(reloginpass.length() < 3 || reloginpass.length() > 20){
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; } public Map validateLoginParams(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() < 3 || loginName.length() > 20){
map.put("loginname", "用户名长度应该在3到20之间");
} //检查验证码是否相等
String verifyCode = user.getVerifyCode();
//获得session中保存的验证码
String sessionCode =(String) request.getSession().getAttribute("vCode");
if(!verifyCode.equalsIgnoreCase(sessionCode)){
map.put("verifyCode", "验证码不正确");
} return map; } }
JavaWeb网上图书商城完整项目--day02-16.登录功能各层实现的更多相关文章
- JavaWeb网上图书商城完整项目--day02-6.ajax校验功能之页面实现
1 .现在我们要在regist.js中实现ajax的功能,使用用户名到后台查询是否注册,邮箱是否到后台注册,验证码是否正确的功能 我们来看regist.js的代码 //该函数在html文档加载完成之后 ...
- JavaWeb网上图书商城完整项目--day02-5.ajax校验功能之服务器端三层实现
regist.jsp页面中有异步请求服务器来对表单进行校验: l 校验登录名是否已注册过: l 校验Email是否已注册过: l 校验验证码是否正确. 这说明在UserServlet中需要提供相 ...
- JavaWeb网上图书商城完整项目--day02-19.修改密码功能流程分析
我们来看看修改密码的业务流程操作:
- JavaWeb网上图书商城完整项目--day02-4.regist页面提交表单时对所有输入框进行校验
1.现在我们要将table表中的输入的参数全部提交到后台进行校验,我们提交我们是按照表单的形式提交,所以我们首先需要在table表外面添加一个表单 <%@ page language=" ...
- JavaWeb网上图书商城完整项目--24.注册页面的css样式实现
现在框架已经做好了,即下来我们要对页面进行装饰了,第一步给每一个元素添加id 1.最外面的div添加id为divMain 2.第二个div添加id为divTitle,里面的span对应的id为span ...
- JavaWeb网上图书商城完整项目--过滤器解决中文乱码
我们知道,如果是POST请求,我们需要调用request.setCharacterEncoding(“utf-8”)方法来设计编码:如果是GET请求,我们需要自己手动来处理编码问题.如果我们使用了En ...
- JavaWeb网上图书商城完整项目--day03-1.图书模块功能介绍及相关类创建
1 前两天我们学习了user用户模块和图书的分类模块,接下来我们学习图书模块 图书模块的功能主要是下面的功能: 2 接下来我们创建对应的包 我们来看看对应的数据库表t_book CREATE TABL ...
- JavaWeb网上图书商城完整项目--13.项目所需环境的搭建
1.首先安装mysql 创建项目所需的数据库,直接运行项目提供的goods.sql文库 2.myeclipse创建一个web project ,项目的名称是goods 把视频中提供的项目原型下的提供的 ...
- JavaWeb网上图书商城完整项目--12.项目所需jquery函数介绍之ajax
jquery中使用ajax发送异步请求 下面的一个案例在input输入框失去焦点的时候发送一个异步的请求: 我们来看程序的案例: 这里要强调的是返回值最好选择是json,json对应的就是对象,Jav ...
- JavaWeb网上图书商城完整项目--BaseServlet
1.以前进行操作的时候,例如我们进行登陆操作我们使用LoginServlet进行处理,进行注册操作我们使用RegisterServlet,很多业务的操作的时候我们就要定义很多个Servlet 有了Ba ...
随机推荐
- [Objective-C] 016_UI篇_UIView(上)
在我们使用app时屏幕上能看到的UI元素(按钮,列表,图片...),我们称之为视图,都是继承与UIView,它们通常有着位置,大小,背景颜色等属性,在appl中视图和窗口展示了应用的用户界面,同时负责 ...
- Chisel3 - 复合数据类型
https://mp.weixin.qq.com/s/rXYqiZKuBpAYL8R94zxgRA Chisel允许用户根据需要,把基本数据类型组合成为复合数据类型使用.如C语言里面的结构体,这样 ...
- (Java实现)蓝桥杯Excel地址
历届试题 Excel地址 原题地址 时间限制:1.0s 内存限制:256.0MB 提交此题 问题描述 Excel单元格的地址表示很有趣,它使用字母来表示列号. 比如, A表示第1列, B表示第2列, ...
- Java实现 蓝桥杯VIP 算法提高 现代诗如蚯蚓
算法提高 现代诗如蚯蚓 时间限制:1.0s 内存限制:256.0MB 问题描述 现代诗如蚯蚓 断成好几截都不会死 字符串断成好几截 有可能完全一样 请编写程序 输入字符串 输出该字符串最多能断成多少截 ...
- Java实现 LeetCode 36 有效的数独
36. 有效的数独 判断一个 9x9 的数独是否有效.只需要根据以下规则,验证已经填入的数字是否有效即可. 数字 1-9 在每一行只能出现一次. 数字 1-9 在每一列只能出现一次. 数字 1-9 在 ...
- java实现第四届蓝桥杯阶乘位数
阶乘位数 题目描述 如图p1.jpg所示,3 x 3 的格子中填写了一些整数. 我们沿着图中的红色线剪开,得到两个部分,每个部分的数字和都是60. 本题的要求就是请你编程判定:对给定的m x n 的格 ...
- PAT 害死人不偿命的(3n+1)猜想
卡拉兹(Callatz)猜想: 对任何一个正整数 n,如果它是偶数,那么把它砍掉一半:如果它是奇数,那么把 ( 3n+1 )砍掉一半.这样一直反复砍下去,最后一定在某一步得到 n=1.卡拉兹在 195 ...
- (易忘篇)java基本语法难点3
本博客随笔主要记录本人学习过程中的知识,欢迎大家一同学习,有不对的地方很高兴读者能详细指出,感激不尽! JVM内存结构 编译完源程序以后,生成一个或多个字节码文件. 我们使用JVM中的类的加载器和解释 ...
- 彻底搞懂 etcd 系列文章(一):初识 etcd
0 专辑概述 etcd 是云原生架构中重要的基础组件,由 CNCF 孵化托管.etcd 在微服务和 Kubernates 集群中不仅可以作为服务注册与发现,还可以作为 key-value 存储的中间件 ...
- mybatis 逆向工程使用姿势不对,把表清空了,心里慌的一比,于是写了个插件。
使用mybatis逆向工程的时候,delete方法的使用姿势不对,导致表被清空了,在生产上一刷新后发现表里没数据了,一股凉意从脚板心直冲天灵盖. 于是开发了一个拦截器,并写下这篇文章记录并分享. 这锅 ...