java_web用户的自动登录模块的实现

java_web用户的自动登录模块的实现_第1张图片java_web用户的自动登录模块的实现_第2张图片java_web用户的自动登录模块的实现_第3张图片

javaBean代码

package bean;

import java.io.Serializable;

public class Admin implements Serializable{

   private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    private String pass;

    public Admin() {
        super();
        // TODO Auto-generated constructor stub
    }

    public Admin(Integer id, String name, String pass) {
        super();
        this.id = id;
        this.name = name;
        this.pass = pass;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    @Override
    public String toString() {
        return "AdminBean [id=" + id + ", name=" + name + ", pass=" + pass
                + "]";
    }

}
dao的基础接口类
package dao;

import java.util.List;

public interface BaseDao {
    /**
     * 插入数据
     */
    boolean insert(T entity);

    /**
     * 根据实体删除数据
     */
    boolean delete(T entity);

    /**
     * 根据ID删除数据
     */
    boolean deleteById(PK id);

    /**
     * 修改数据
     */
    boolean update(T entity);

    /**
     * 查询所有数据
     */
    List findAll();

    /**
     * 根据ID查询数据
     */
    T findById(PK id);

    /**
     * 根据当前页查询数据
     */
    List findNowPageInfo(int nowpage, int pagesize,String sortName,String sortOrder);

    /**
     * 返回总页数
     */
    Integer getCountPage(int pagesize);

    /**
     * 批量删除
     */

    boolean deletes(Object ids[]);

}
对admin操作的接口类,继承自basedao
package dao;

import bean.Admin;

public interface AdminDao extends BaseDao {
    Admin checkLogin(String name,String pass);
    Admin checkLogin(String name);
    
}
dao操作实体的实现类
package daoImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import util.JdbcUtil;
import bean.Admin;
import dao.AdminDao;

public class AdminDaoImpl implements AdminDao {

    private Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    @Override
    public boolean insert(Admin entity) {
        return JdbcUtil.upDate("insert into admin (name,pass) values (?,?)",
                new Object[] { entity.getName(), entity.getPass() });
    }

    @Override
    public boolean delete(Admin entity) {
        // TODO Auto-generated method stub
        return deleteById(entity.getId());
    }

    @Override
    public boolean deleteById(Integer id) {
        // TODO Auto-generated method stub
        return JdbcUtil.upDate("delete from admin where id=?",
                new Object[] { id });
    }

    @Override
    public boolean update(Admin entity) {
        // TODO Auto-generated method stub
        return JdbcUtil.upDate(
                "update admin set name=?,pass=? where id=?",
                new Object[] { entity.getName(), entity.getPass(),
                        entity.getId() });
    }

    @Override
    public List findAll() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Admin findById(Integer id) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List findNowPageInfo(int nowpage, int pagesize,
            String sortName, String sortOrder) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Integer getCountPage(int pagesize) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean deletes(Object[] ids) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Admin checkLogin(String name, String pass) {
        // TODO Auto-generated method stub
        Admin entity = null;
        String sql = "select * from admin where name=? and pass=?";
        conn = JdbcUtil.getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            int index = 1;
            pstmt.setString(index++, name);
            pstmt.setString(index++, pass);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                entity = new Admin();
                entity.setId(rs.getInt("id"));
                entity.setName(rs.getString("name"));
                entity.setPass(rs.getString("pass"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.release(rs, pstmt);
        }
        return entity;
    }

    @Override
    public Admin checkLogin(String name) {
        Admin entity = null;
        String sql = "select * from admin where name=?";
        conn = JdbcUtil.getConn();
        try {
            pstmt = conn.prepareStatement(sql);
            int index = 1;
            pstmt.setString(index++, name);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                entity = new Admin();
                entity.setId(rs.getInt("id"));
                entity.setName(rs.getString("name"));
                entity.setPass(rs.getString("pass"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtil.release(rs, pstmt);
        }
        return entity;
    }

}
服务器接口类,用来将操作数据库的方法与记录历史的方法或其他的方法分离开,作用是增强代码的可读性以及条理性,

package service;

import java.util.List;

public interface BaseService {
    /**
     * 插入数据
     */
    boolean insert(T entity);

    /**
     * 根据实体删除数据
     */
    boolean delete(T entity);

    /**
     * 根据ID删除数据
     */
    boolean deleteById(PK id);

    /**
     * 修改数据
     */
    boolean update(T entity);

    /**
     * 查询所有数据
     */
    List findAll();

    /**
     * 根据ID查询数据
     */
    T findById(PK id);

    /**
     * 根据当前页查询数据
     */
    List findNowPageInfo(int nowpage, int pagesize,String sortName,String sortOrder);

    /**
     * 返回总页数
     */
    Integer getCountPage(int pagesize);

    /**
     * 批量删除
     */

    boolean deletes(Object ids[]);

}
package service;

import bean.Admin;

public interface AdminService extends BaseService {
    Admin checkLogin(String name,String pass);
    Admin checkLogin(String name);
}
实现服务器接口方法的实现类
package serviceImpl;

import java.util.List;

import dao.AdminDao;
import daoImpl.AdminDaoImpl;

import bean.Admin;
import service.AdminService;

public class AdminServiceImpl implements AdminService {
    AdminDao adminDao = new AdminDaoImpl();

    @Override
    public boolean insert(Admin entity) {
        return adminDao.insert(entity);
    }

    @Override
    public boolean delete(Admin entity) {
        return false;
    }

    @Override
    public boolean deleteById(Integer id) {
        return false;
    }

    @Override
    public boolean update(Admin entity) {
        return false;
    }

    @Override
    public List findAll() {
        return null;
    }

    @Override
    public Admin findById(Integer id) {
        return null;
    }

    @Override
    public List findNowPageInfo(int nowpage, int pagesize,
            String sortName, String sortOrder) {
        return null;
    }

    @Override
    public Integer getCountPage(int pagesize) {
        return null;
    }

    @Override
    public boolean deletes(Object[] ids) {
        return false;
    }

    @Override
    public Admin checkLogin(String name, String pass) {
        Admin entity = adminDao.checkLogin(name, pass);
        return entity;
    }

    @Override
    public Admin checkLogin(String name) {
        Admin entity = adminDao.checkLogin(name);
        return entity;
    }

}
用来将页面传入的信息进行分析处理的服务器类,
package servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.jms.Message;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.mail.util.BASE64DecoderStream;
import com.sun.mail.util.BASE64EncoderStream;

import service.AdminService;
import serviceImpl.AdminServiceImpl;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import bean.Admin;

public class AdminServlet extends HttpServlet {

    private AdminService adminService = new AdminServiceImpl();

    // 规定时间常量,为一天
    private final int EXPIRES =  60 * 60 * 24;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // request.setCharacterEncoding("UTF-8");

        String oper = request.getParameter("oper");
        if ("adminLogin".equals(oper)) {
            adminLogin(request, response);
        }
        if ("login".equals(oper)) {
            request.getRequestDispatcher("./login.jsp").forward(request,
                    response);
        }

    }

    private void adminLogin(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        
        //获取表单提交的数据
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        String mark = request.getParameter("mark");
        String day = request.getParameter("day");

//      System.out.println(name + "====" + pass + "====" + mark
//              + "============" + day);

        //根据获取的数据向数据库发送数据请求,
        Admin entity = adminService.checkLogin(name, pass);

        //判断查询结果
        if (entity != null) {
            //判断用户是否进行记录密码和自动登陆的操作
            if ("mark".equals(mark)) {
                // 获取当前的时间并加上要保存的时间长度
                long time = System.currentTimeMillis()
                        + (EXPIRES * Integer.valueOf(day)*1000);

                // 声明cookie
                Cookie autoCookie = null;
                // 获取所有的cookie的数组
                Cookie cookies[] = request.getCookies();
                // 遍历判断
                for (Cookie cookie : cookies) {
                    // 判断是否已经存在cookie记录
                    if ("autoLogin".equals(cookie.getName())) {
                        // 存在即直接赋值
                        autoCookie = cookie;
                        // 并改变内容
                        String newValue = name
                                + ":"
                                + time
                                + ":"
                                + md5Value(pass + ":" + name + ":" + time
                                        + ":donghongyujava");
                        autoCookie.setValue(newValue);
                    } else {
                        String cookieValue = name
                                + ":"
                                + time
                                + ":"
                                + md5Value(pass + ":" + name + ":" + time
                                        + ":donghongyujava");
                        /*
                         * Control character in cookie value or attribute.
                         * 当存入的数据是中文时,cookie会出现乱码现象 需要进行编码的转换
                         */
                        autoCookie = new Cookie("autoLogin", URLEncoder.encode(
                                cookieValue, "UTF-8"));
                    }
                }
                // 设置cookie的最长的存活时间
                autoCookie.setMaxAge(EXPIRES * Integer.valueOf(day));
                response.addCookie(autoCookie);
            }
            // 将admin存入到session
            request.getSession().setAttribute("admin", entity);
            // 设置成功后就登陆操作
            request.getRequestDispatcher("./sc.jsp").forward(request, response);
        } else {
            
            request.setAttribute("msg", "用户名或密码错误请重试");
            request.getRequestDispatcher("./login.jsp").forward(request,
                    response);
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);
    }

    //加密的操作方法
    public String md5Value(String value) {
        try {
            // 获取md5加密的对象
            MessageDigest digest = MessageDigest.getInstance("md5");
            // 将传入的数据装换为byte字节,在用digest进行转换(加密)成新的字节数组,
            byte result[] = digest.digest(value.getBytes());
            //需要的jdk版本myeclipse2013中自带的com.sun.java.jdk.win32.x86_64_1.6.0.u43
            //jdk1.7.0_25没有相关的包
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回加密后的数据
            return encoder.encode(result);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    };

}
过滤器类,用来设置请求的编码
package filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class EncodingFilter implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        // 编码的设置
        request.setCharacterEncoding(filterConfig.getInitParameter("encoding"));
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        this.filterConfig=filterConfig;
    }

}
自动登录的过滤类,用来控制用户的自动的登录操作的相关
package filter;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Admin;

import service.AdminService;
import serviceImpl.AdminServiceImpl;
import sun.misc.BASE64Encoder;

public class AutoLoginFilter implements Filter {

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res,
            FilterChain chain) throws IOException, ServletException {
        // 强制造型为子类型
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        // 1.首先判断session
        Object object = request.getSession().getAttribute("admin");

        if (object != null) {
            request.getRequestDispatcher("./sc.jsp").forward(request, response);
            return;
        }

        // 2.判断cookie中是否存在用户的记录
        Cookie autoCookie = null;
        // 获取所有的cookie进行遍历判断
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // 判断是否已经存贮用户记录
                if ("autoLogin".equals(cookie.getName())) {
                    autoCookie = cookie;
                }
            }

            // 判断是否存在用户自动登录记录
            if (autoCookie == null) {
                chain.doFilter(request, response);
                return;
            }

            // 3.判断cookie的值
            // 获取cookie值
            String value = autoCookie.getValue();
            // 拆分
            String temps[] = value.split(":");

            // 判断长度是否是自定义的长度
            if (temps.length != 3) {
                chain.doFilter(request, response);
                return;
            }
            // 获取拆分后的数据
            String name = temps[0];
            
            String time = temps[1];
            
            String service_md5Value = temps[2];

            // 4.根据时间判断是否失效
            if (Long.valueOf(time) <= System.currentTimeMillis()) {
                chain.doFilter(request, response);
                return;
            }

            // 5.根据用户名查询数据
            AdminService adminService = new AdminServiceImpl();
            // 向数据库发送数据请求
            Admin entity = adminService.checkLogin(name);
            if (entity == null) {
                chain.doFilter(request, response);
                return;
            }

            // 6.拼接字符串在进行二次判断,
            String md5Temp = entity.getPass() + ":" + entity.getName() + ":"
                    + time + "donghongyujava";
            if (!(md5Value(md5Temp).equals(service_md5Value))) {
                chain.doFilter(request, response);
                return;
            }

            // 7.如果以上的判断都通过,那么就发送成功的转跳连接
            request.getSession().setAttribute("admin", entity);
            request.getRequestDispatcher("./sc.jsp").forward(request, response);
        } else {
            chain.doFilter(request, response);
            return;
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

    // 加密的操作函数
    public String md5Value(String value) {
        try {
            // 获取md5加密的对象
            MessageDigest digest = MessageDigest.getInstance("md5");
            // 将传入的数据装换为byte字节,在用digest进行转换(加密)成新的字节数组,
            byte result[] = digest.digest(value.getBytes());
            BASE64Encoder encoder = new BASE64Encoder();
            // 返回加密后的数据
            return encoder.encode(result);

        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "";
    };

}
web的配置,主要配置的是servlet和filter的配置


    jqueryeasyui
    
        AdminServlet
        servlet.AdminServlet
    

    
        AdminServlet
        /AdminOPer.do
    


    
        AutoLoginFilter
        filter.AutoLoginFilter
    

    
        AutoLoginFilter
        /AdminOPer.do
    


    
        EncodingFilter
        filter.EncodingFilter
        
        
            encoding
            UTF-8
        
    

    
    
        EncodingFilter
        /*
    

    
        index.html
        index.htm
        index.jsp
        default.html
        default.htm
        default.jsp
    
用来跳转的jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>



  
    
    
    My JSP 'index.jsp' starting page
    
    
    
        
    
    
    

  
  
  
   登录操作
  
要登陆的表单界面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@include file="/common/tag.jsp"%>
<%@include file="/common/jquery.jsp"%>






My JSP 'index.jsp' starting page









    
${requestScope.msg}
用户名:
密码:
下次记住密码
一天 三天 一周
成功登录后的界面jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>






My JSP 'sc.jsp' starting page












    欢迎  ${sessionScope.admin.name}进入

原文地址: http://my.oschina.net/donghongyu/blog/190504

你可能感兴趣的:(其他,jsp+servlet)