- 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<T, PK> {
- /**
- * 插入数据
- */
- boolean insert(T entity);
- /**
- * 根据实体删除数据
- */
- boolean delete(T entity);
- /**
- * 根据ID删除数据
- */
- boolean deleteById(PK id);
- /**
- * 修改数据
- */
- boolean update(T entity);
- /**
- * 查询所有数据
- */
- List<T> findAll();
- /**
- * 根据ID查询数据
- */
- T findById(PK id);
- /**
- * 根据当前页查询数据
- */
- List<T> 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, Integer> {
- 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<Admin> findAll() {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public Admin findById(Integer id) {
- // TODO Auto-generated method stub
- return null;
- }
- @Override
- public List<Admin> 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<T, PK> {
- /**
- * 插入数据
- */
- boolean insert(T entity);
- /**
- * 根据实体删除数据
- */
- boolean delete(T entity);
- /**
- * 根据ID删除数据
- */
- boolean deleteById(PK id);
- /**
- * 修改数据
- */
- boolean update(T entity);
- /**
- * 查询所有数据
- */
- List<T> findAll();
- /**
- * 根据ID查询数据
- */
- T findById(PK id);
- /**
- * 根据当前页查询数据
- */
- List<T> 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, Integer> {
- 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<Admin> findAll() {
- return null;
- }
- @Override
- public Admin findById(Integer id) {
- return null;
- }
- @Override
- public List<Admin> 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的配置
- <?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_3_0.xsd"
- id="WebApp_ID" version="3.0">
- <display-name>jqueryeasyui</display-name>
- <servlet>
- <servlet-name>AdminServlet</servlet-name>
- <servlet-class>servlet.AdminServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>AdminServlet</servlet-name>
- <url-pattern>/AdminOPer.do</url-pattern>
- </servlet-mapping>
- <filter>
- <filter-name>AutoLoginFilter</filter-name>
- <filter-class>filter.AutoLoginFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>AutoLoginFilter</filter-name>
- <url-pattern>/AdminOPer.do</url-pattern>
- </filter-mapping>
- <filter>
- <filter-name>EncodingFilter</filter-name>
- <filter-class>filter.EncodingFilter</filter-class>
- <!-- 设置传入的参数是UTF-8 -->
- <init-param>
- <param-name>encoding</param-name>
- <param-value>UTF-8</param-value>
- </init-param>
- </filter>
- <!-- 设置所有的请求操作都进行这个过滤的操作 -->
- <filter-mapping>
- <filter-name>EncodingFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.html</welcome-file>
- <welcome-file>index.htm</welcome-file>
- <welcome-file>index.jsp</welcome-file>
- <welcome-file>default.html</welcome-file>
- <welcome-file>default.htm</welcome-file>
- <welcome-file>default.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
- 用来跳转的jsp代码
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <a href="${pageContext.request.contextPath}/AdminOPer.do?oper=login">登录操作</a>
- </body>
- </html>
- 要登陆的表单界面
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%@include file="/common/tag.jsp"%>
- <%@include file="/common/jquery.jsp"%>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>My JSP 'index.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <div>
- <!-- 登录错误时的提示操作 -->
- <b>${requestScope.msg}</b>
- <!-- ${pageContext.request.contextPath}代表当前项目路径下的操作 -->
- <form action="${pageContext.request.contextPath}/AdminOPer.do"
- method="post">
- <table border="1">
- <tr>
- <td>用户名:</td>
- <td><input type="text" name="name"></td>
- </tr>
- <tr>
- <td>密码:</td>
- <td><input type="text" name="pass"></td>
- </tr>
- <tr>
- <td align="right"><input type="checkBox" name="mark"
- value="mark"></td>
- <td>下次记住密码</td>
- </tr>
- <tr>
- <td colspan="2"><input type="radio" name="day" value="1">一天
- <input type="radio" name="day" value="3">三天 <input
- type="radio" name="day" value="7" checked="checked">一周</td>
- </tr>
- <tr>
- <td align="center" colspan="2"><input type="submit" value="登录"
- id="submit"><input type="reset" value="重置" id="reset"></td>
- </tr>
- </table>
- <input type="hidden" value="adminLogin" name="oper">
- </form>
- </div>
- </body>
- </html>
- 成功登录后的界面jsp代码
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'sc.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- <!-- 从session域中取出已经存入的用户对象 -->
- 欢迎 <b>${sessionScope.admin.name}</b>进入
- </body>
- </html>