作者L_J
上篇我们讲了用户的注册、邮件的发送、及账号的激活那么。既然讲了注册那么必不可少的就是什么?登录嘛,那么今天我就分享一下我学到的账号登录在登录前你的账号得先激活才能进行登录,并实现自动登录功能。温馨提示:请先看完上篇文章再看本篇文章否则你会产生许多的疑惑
一、登录界面
还是一样的既然有登录必不可少的就是页面,今天登录页面的编写我同样用到的是easyui进行的搭建今天我就不在这里细说了我上篇文章邮件的发送和账号的激活及一些芝士的引入中有讲到easyui页面搭建的使用。在这里放上篇文章忘记放的easyui官网的网址:Jquery EasyUI 中文文档 登录界面代码如下:
第一次看我文章的可能会疑惑我的form提交路径为什么是customer?action=login这样写?同样的在我上一篇文章中也有讲解有疑惑的可以参考我的上一篇文章。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="themes/icon.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.easyui.min.js"></script>
</head>
<body class="easyui-layout" style="background:url('${ctp }/img/ssmbackground.jpg') no-repeat;background-size: 100%;">
<div id="w" class="easyui-window" title="用户登录" collapsible="false"
minimizable="false" maximizable="false" icon="icon-save"
style="width: 450px; height: 330px; padding: 30px; background: #fafafa;"
data-options="closable:false,draggable:false">
<form id="formlogin" method="post" action="customer?action=login">
<!-- menulogin -->
<div style="margin-bottom: 20px">
<input class="easyui-textbox" id="loginname" name="name"
prompt="请输入用户名/邮箱" iconWidth="28"
data-options="label:'用户名:',required:true"
style="width: 300px; height: 34px; padding: 10px;">
</div>
<div style="margin-bottom: 20px">
<input class="easyui-passwordbox" id="password" name="pass"
prompt="请输入密码" iconWidth="28"
data-options="label:'密码:',required:true"
style="width: 300px; height: 34px; padding: 10px">
</div>
<div>
<input name="checkbox1" value="T" type="checkbox" class="easyui-checkbox" label="记住密码" labelPosition="after" labelWidth="70" />
<input name="autologin" value="autologin" type="checkbox" class="easyui-checkbox" label="自动登录" labelPosition="after" labelWidth="70" />
</div>
<div style="text-align: center; padding: 5px 0">
<input type="submit" value="登录" style="width: 80px" id="login-submit-btn" class="easyui-linkbutton">
</div>
</form>
</div>
</body>
</html>
二、mvc开发模式 进行用户的登录
有人可能不太清楚mvc开发模式是什么?
servlet层代码如下:
看到这可能又有人会有疑惑了为什么我说重定向到什么什么页面却是用的返回值呢?而不是
response.sendRedirect();这个语句呢?这里就又涉及到了我上篇文章所讲到的内容了有疑惑可去我上篇文章进行解惑。本文章的开篇有上篇文章的链接
public String login(HttpServletRequest req,HttpServletResponse resp){
//拿到表单中的数据并映射到对象中去
Customer customer = ConverterBeanUtils.toBean(req.getParameterMap(),Customer.class);
//通过表单中的数据查询数据库表中的数据
Customer c=service.login(customer);
//拿到复选框中提交的数据 用于判断用户是否勾选了自动登录
String autologin = req.getParameter("autologin");
//通过用户名查到了数据
if(c!=null){
//判断密码是否正确
if(customer.getPass().equals(c.getPass())){
//判断账号是否激活
if(c.getActivate()==1){
//判断用户是否勾选了自动登录
if("autologin".equals(autologin)){
System.out.println("选中了自动登录");
//将用户名和密码保存到cookie中
Cookie u=new Cookie("u",c.getName());
Cookie p=new Cookie("p",c.getPass());
//设置cookie时效
u.setMaxAge(60*60*24*7);
p.setMaxAge(60*60*24*7);
//将cookie相=响应到客户端中
resp.addCookie(u);
resp.addCookie(p);
}
//登录成功将对象保存到session域中
req.getSession().setAttribute("c",c);
//重定向到主界面
return "r:index2.jsp";
}else{
//重定向到错误页面 错误:账号未激活
return "r:error.jsp?error=inactive";
}
}else{
//重定向到错误页面 错误:密码错误
return "r:error.jsp?error=perror";
}
}else{
//重定向到错误页面 错误:找不到该账号
return "r:error.jsp?error=nouser";
}
}
service层代码如下:
看过我上一篇文章的应该能看懂我的service层和dao层。在这我就不做过多的解释了这里的service层和dao层也包含了一些上一篇文章中的一些代码。
public interface CustomerService {
boolean register(Customer customer);
Customer active(String code);
boolean updateCustomer(Customer c);
Customer login(Customer customer);
Customer login2(String user);
}
serviceImp层代码如下:
public class CustomerServiceImp implements CustomerService {
CustomerDao dao=new CustomerDaoImp();
public boolean register(Customer customer) {
boolean b=dao.register(customer);
if(b){
boolean sendEmail = EmailUtils.sendEmail(customer.getEmail(),"网站激活码",
"<h3>恭喜你成功注册为我站会员请点击下方链接进行激活</h3><br><a href='http://"+HostUtils.getHost()+":8080/SchickenSieEine-Email2/customer?action=active&code="+customer.getCode()+"'>立即激活</a>");
return sendEmail;
}
return false;
}
@Override
public Customer active(String code) {
return dao.active(code);
}
@Override
public boolean updateCustomer(Customer c) {
return dao.updateCustomer(c);
}
@Override
public Customer login(Customer customer) {
return dao.login(customer);
}
@Override
public Customer login2(String user) {
// TODO Auto-generated method stub
return dao.login2(user);
}
}
dao层代码如下:
public interface CustomerDao {
boolean register(Customer customer);
Customer active(String code);
boolean updateCustomer(Customer c);
Customer login(Customer customer);
Customer login2(String user);
}
daoImp层代码如下:
public class CustomerDaoImp implements CustomerDao {
QueryRunner runn=new QueryRunner(MyC3p0Utils.getDatSoutrce());
//注册 将注册信息添加到数据库表中
@Override
public boolean register(Customer customer) {
String sql="insert into customer values(null,?,?,?,?,?)";
try {
int update = runn.update(sql,customer.getName(),customer.getPass(),customer.getActivate(),customer.getCode(),customer.getEmail());
return update>0?true:false;
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
//查询是否有这个激活码
@Override
public Customer active(String code) {
String sql="select * from customer where code=?";
try {
return runn.query(sql,new BeanHandler<>(Customer.class),code);
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
//查询到了激活码并激活了 修改数据库表中的activate 并将激活码置空避免用户重复激活
@Override
public boolean updateCustomer(Customer c) {
String sql="update customer set activate=?,code=? where id=?";
try {
int update = runn.update(sql,c.getActivate(),c.getCode(),c.getId());
return update>0?true:false;
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
//查询 通过 customer中的name属性去查询数据库表中的值
@Override
public Customer login(Customer customer) {
String sql="select * from customer where name=? or email=?";
try {
return runn.query(sql,new BeanHandler<Customer>(Customer.class),customer.getName(),customer.getName());
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
//查询 通过 cookie中的user属性去查询数据库表中的值
@Override
public Customer login2(String user) {
String sql="select * from customer where name=? or email=?";
try {
return runn.query(sql,new BeanHandler<Customer>(Customer.class),user,user);
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
}
}
三、过滤器
过滤器JavaWeb的三大组件之一。service的三大组件:Servlet、Filter、Listener
这里我们用到了Filter过滤器 它的作用是什么呢?(过滤用户的请求)
Filter 代码如下:
当用户访问主界面时进行过滤 实现自动登录功能详情请看代码的注释
//用注解配置filter
@WebFilter("/index2.jsp")
public class FilterIndex implements Filter {
//服务器关闭filter销毁
@Override
public void destroy() {
System.out.println("销毁");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println("初始化");
}
//过滤请求时触发
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
//将ServletRequest及ServletRequest向下转型
//因为父类中拿不到我们想要的方法
HttpServletRequest req=(HttpServletRequest) arg0;
HttpServletResponse resp=(HttpServletResponse) arg1;
//拿到session域
HttpSession session = req.getSession();
//拿到存放在域中的值
Customer customer= (Customer)session.getAttribute("c");
//定义变量用于存放cookie中获取到的值
String user="";
String pass="";
//没有登录
if(customer==null){
//拿到cookie
Cookie[] cookies = req.getCookies();
if(cookies!=null){
//遍历cookie
for (Cookie cookie : cookies) {
//由于cookie存放模式为键值对 我们通过键去拿到cookie中的值
if("u".equals(cookie.getName())){
user=cookie.getValue();
}
if("p".equals(cookie.getName())){
pass=cookie.getValue();
}
}
//判断账号和密码的正确性
CustomerService service=new CustomerServiceImp();
//通过cookie中的user去查询数据库表中的信息
Customer c=service.login2(user);
if(c!=null){
//用数据库表中查到的密码与cookie中存放的密码进行比较
if(c.getPass().equals(pass)){
//账号是否激活
if(c.getActivate()==1){
//将对象存放到session域中
session.setAttribute("c",c);
}
}
}else{
req.getRequestDispatcher("/Login.jsp").forward(req, resp);
}
}
//已经登录了 放行
arg2.doFilter(arg0, arg1);
}
}
}
四、总结
在本次用到的知识点easyui、mvc开发模式、数据库的操作、Filter过滤器的使用。再次提醒在进行数据库操作前一定不要忘记先进行数据库的连接。