一個很簡單的使用者登入設計
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[]);
}</t></t></t,>
對admin操作的介面類,繼承自basedao
package dao;
import bean.Admin;
public interface AdminDao extends BaseDao {
Admin checkLogin(String name,String pass);
Admin checkLogin(String name);
}</admin,>
?
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;
}
}</admin></admin>
?
伺服器介面類,用來將操作資料庫的方法與記錄歷史的方法或其他的方法分離開,作用是增強程式碼的可讀性以及條理性,
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 checkLogin(String name,String pass);
Admin checkLogin(String name);
}</admin,></t></t></t,>
實現伺服器介面方法的實現類
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;
}
}</admin></admin>
用來將頁面傳入的資訊進行分析處理的伺服器類,
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+"/";
%>
<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">
-->
登入操作
要登陸的表單介面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="/common/tag.jsp"%>
<%@include file="/common/jquery.jsp"%>
<html>
<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">
-->
<div>
<!-- 登入錯誤時的提示操作 -->
<b>${requestScope.msg}</b>
<!-- ${pageContext.request.contextPath}代表當前專案路徑下的操作 -->
<form action="${pageContext.request.contextPath}/AdminOPer.do" method="post">
<table border="1">
<tbody><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>
</tbody></table>
<input type="hidden" value="adminLogin" name="oper">
</form>
</div>
成功登入後的介面jsp程式碼
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<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">
-->
<!-- 從session域中取出已經存入的使用者物件 -->
歡迎 <b>${sessionScope.admin.name}</b>進入