登陆:用户表-----(页面session增加,此session用上下文的request获取,传入工具类,设置)---session表------session历史表
退出:删除登录时增加的session表---页面session去除(在登陆时后台设置的session 中的当前用户,包括页面session,数据表中的session)
看别人的程序,看过程后,选择性的修订代码
sesion的工具类:
package ces.platform.system.common;
import javax.servlet.http.*;
import java.util.*;
/**
* <p>标题:
* <font class=titlefont>
* 《会话属性》类
* </font>
* <p>描述:
* <font class=descriptionfont>
* <br>会话绑定
* </font>
* <p>版本号:
* <font class=versionfont>
* Copyright (c) 2.50.2003.0925
* </font>
* <p>公司:
* <font class=companyfont>
* 上海中信信息发展有限公司
* </font>
* @author 王辉
* @version 2.50.2003.0925
*/
public class SessionProperty {
HttpSession session=null;
Hashtable table=new Hashtable();
public SessionProperty() {
}
public SessionProperty(HttpSession session) {
this.session=session;
}
public void setAttribute(String name,Object obj){
if(session!=null){
session.setAttribute(name,obj);
}else{
table.put(name,obj);
}
}
public Object getAttribute(String name){
if(session!=null){
return session.getAttribute(name);
}else{
return table.get(name);
}
}
/**
* 将context会话中的变量存入HttpSession中
* @param session
*/
public void reverseToSession(HttpSession session){
for(Enumeration enu=table.keys();enu.hasMoreElements();){
String key=(String)enu.nextElement();
session.setAttribute(key,table.get(key));
}
}
}
===利用session设置用户session====
package ces.platform.system.dbaccess;
import ces.frame.util.dao.PlatformDao;
import ces.platform.system.common.*;
import java.sql.*;
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
public class UserSession extends OperationBase implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 静态常量:登录标志----成功
**/
public static final String LOGIN_SUCCESS = "1";
/**
* 静态常量:登录标志----不成功,并发用户数超过
**/
public static final String LOGIN_FAIL_CONN = "2";
/**
* 静态常量:登录标志----不成功,口令三次错误
**/
public static final String LOGIN_FAIL_PASSWORD = "3";
/**
* 静态常量:退出标志----未退出
**/
public static final String LOGOUT_NO = "0";
/**
* 静态常量:退出标志----正常退出
**/
public static final String LOGOUT_NORMAL = "1";
/**
* 静态常量:退出标志----注销退出
**/
public static final String LOGOUT_CANCEL = "2";
/**
* 静态常量:将会话变量存入session中
**/
public static final String STORE_SESSION = "1";
/**
* 静态常量:将会话变量存入property中
**/
public static final String STORE_PROPERTY = "2";
/**
* 成员变量:会话编号
**/
protected String sessionID;
/**
* 成员变量:会话开始时间,对应于t_sys_user_session.begin_date
**/
protected java.sql.Timestamp beginDate;
/**
* 成员变量:IP地址,对应于t_sys_user_session.ip_address
**/
protected String ipAddress;
/**
* 成员变量:用户对象
**/
protected User user;
/**
* 成员变量:网卡地址
**/
protected String macNO;
/**
* 成员变量:用户登录ID
*/
protected String loginID;
/**
* 缺省构造函数
*
**/
public UserSession() {
//
}
/**
* 构造函数1
*
* @param sessionID 会话编号
**/
public UserSession(String sessionID) {
//
this.sessionID = sessionID;
}
/**
* 构造函数2
*
* @param sessionID 会话编号
* @param beginDate 会话开始时间
* @param ipAddress IP地址
* @param macNO 网卡地址
* @param loginID 用户登录ID
* @param user 用户对象
**/
public UserSession(String sessionID ,
java.sql.Timestamp beginDate ,
String ipAddress ,
String macNO ,
String loginID,
User user) {
//
this.sessionID = sessionID;
this.beginDate = beginDate;
this.ipAddress = ipAddress;
this.macNO = macNO;
this.loginID=loginID;
this.user = user;
}
/**
* 设置会话编号
*
* @param sessionID 会话编号
**/
public void setSessionID(String sessionID) {
//
this.sessionID = sessionID;
}
/**
* 设置会话开始时间
*
* @param beginDate 会话开始时间
**/
public void setBeginDate(java.sql.Timestamp beginDate) {
//
this.beginDate = beginDate;
}
/**
* 设置IP地址
*
* @param ipAddress IP地址
**/
public void setIpAddress(String ipAddress) {
//
this.ipAddress = ipAddress;
}
/**
* 设置用户
*
* @param user 用户对象
**/
public void setUser(User user) {
//
this.user = user;
}
/**
* 设置网卡地址
*
* @param macNO 网卡地址
**/
public void setMacNO(String macNO) {
//
this.macNO = macNO;
}
/**
* 获取会话编号
*
* @return 会话编号
**/
public String getSessionID() {
//
return this.sessionID;
}
/**
* 获取会话开始时间
*
* @return 会话开始时间
**/
public java.sql.Timestamp getBeginDate() {
//
return this.beginDate;
}
/**
* 获取IP地址
*
* @return IP地址
**/
public String getIpAddress() {
//
return this.ipAddress;
}
/**
* 获取用户
*
* @return 用户对象
**/
public User getUser() {
//
return this.user;
}
/**
* 获取网卡地址
*
* @return 网卡地址
**/
public String getMacNO() {
//
return this.macNO;
}
/**
* 获取用户登录ID
* @return 登录ID
*/
public String getLoginID() {
return loginID;
}
/**
* 设置用户登录ID
* @param loginID
*/
public void setLoginID(String loginID) {
this.loginID = loginID;
}
//////////////////////////////////////////////////////////////////////////
//以下成员函数有具体应用
/**
* 验证该用户会话对象在数据库中是否存在
*
* @return true: 该对象在数据库中存在
* false: 该对象在数据空中不存在
* @throws Exception
* 如果验证有问题,将抛出异常
*/
public boolean isExist() throws Exception
{
boolean returnValue = false;
Connection conn = null;
PreparedStatement ps = null;
ResultSet result = null;
String strQuery = "SELECT session_id FROM " + Common.USER_SESSION_TABLE
+ " WHERE session_id = ?";
try
{
conn = PlatformDao.getDataSource().getConnection();
ps = conn.prepareStatement(strQuery);
ps.setString(1 , this.sessionID);
result = ps.executeQuery();
if (!result.next())
{
returnValue = false;
}
else
{
returnValue = true;
}
}
finally
{
close(conn, ps, result);
}
return returnValue;
}
/**
* 验证该用户会话对象在数据库中是否存在
*
* @return true: 该对象在数据库中存在
* false: 该对象在数据空中不存在
* @throws Exception
* 如果验证有问题,将抛出异常
*/
public boolean isExist(Connection con) throws Exception {
boolean returnValue = false;
PreparedStatement ps = null;
ResultSet result = null;
String strQuery = "SELECT session_id FROM " + Common.USER_SESSION_TABLE
+ " WHERE session_id = ?";
try {
ps = con.prepareStatement(strQuery);
ps.setString(1 , this.sessionID);
result = ps.executeQuery();
if (!result.next()) {
returnValue = false;
} else {
returnValue = true;
}
} catch (SQLException se) {
throw new Exception(
"User_session.isExist(): SQLException: \n\t" + se);
} finally {
close(null, ps, result);
}
return returnValue;
}
/**
* 从数据库中重新装入该用户会话对象信息
*
* @return true: 装入成功
* false: 装入不成功
* @throws Exception
* 如果装入有问题,将抛出异常
*/
public boolean load() throws Exception
{
boolean returnValue = false;
Connection conn = null;
PreparedStatement ps = null;
ResultSet result = null;
String strQuery =
"SELECT ut.user_id,ut.user_name,ut.login_name,ut.flag_emp,"
+
"ut.user_cryptogram,ut.flag_lock,ut.flag_define,ut.ic_no,ut.conn_num,"
+
"ut.flag_check,ut.flag_active,ut.flag_sa,ut.show_order,ut.position_x,ut.position_y,ut.type,"
+ "ust.session_id,ust.begin_date,ust.ip_address,ust.mac_no,ust.login_id "
+ "FROM " + Common.USER_TABLE + " ut, "
+ Common.USER_SESSION_TABLE + " ust "
+ "WHERE ut.user_id = ust.user_id "
+ "AND ust.session_id = ?";
try
{
conn = PlatformDao.getDataSource().getConnection();
ps = conn.prepareStatement(strQuery);
ps.setString(1 , this.sessionID);
result = ps.executeQuery();
int i=1;
ValueAsc va=new ValueAsc(i);
if (!result.next())
{
returnValue = false;
}
else
{
i = 1;
va.setStart(i);
User uTemp = User.generateUser(result,va);
this.user = uTemp;
this.sessionID = result.getString(va.next());
this.beginDate = result.getTimestamp(va.next());
this.ipAddress = result.getString(va.next());
this.macNO = result.getString(va.next());
this.loginID=result.getString(va.next());
returnValue = true;
}
}
finally
{
close(conn, ps, result);
}
return returnValue;
}
/**
* 新建该用户会话对象
* @param conn 连接对象
* @throws Exception
* 如果新建有问题,将抛出异常
*/
protected void doNew(Connection conn) throws Exception
{
if (!isValidate()) {
throw new Exception(
"User_session.doNew(): Illegal data values for insert");
}
PreparedStatement ps = null;
String strQuery = "INSERT INTO " + Common.USER_SESSION_TABLE
+ "(session_id,user_id,begin_date,ip_address,mac_no,login_id)"
+ "VALUES (?,?,?,?,?,?)";
try {
ps = conn.prepareStatement(strQuery);
ps.setString(1 , this.sessionID);
ps.setInt(2 , this.user.getUserID());
ps.setTimestamp(3 , this.beginDate);
ps.setString(4 , this.ipAddress);
ps.setString(5 , this.macNO);
ps.setString(6 , this.loginID);
int resultCount = ps.executeUpdate();
if (resultCount != 1) {
throw new Exception(
"User_session.doNew(): ERROR Inserting data "
+ "in T_SYS_USER_SESSION INSERT !! resultCount = " +
resultCount);
}
} catch (SQLException se) {
throw new Exception(
"User_session.doNew(): SQLException while inserting new user_session; "
+ "session_id = " + this.sessionID + " :\n\t" + se);
} finally {
close(null, ps, null);
}
}
/**
* 更新该用户会话对象
* @param conn 连接对象
* @throws Exception
* 如果更新有问题,将抛出异常
*/
protected void doUpdate(Connection conn) throws Exception {
if (!isValidate()) {
throw new Exception("User_session.doUpdate(): Illegal data values for update");
}
PreparedStatement ps = null;
String strQuery = "UPDATE " + Common.USER_SESSION_TABLE + " SET "
+ "user_id = ?, begin_date = ? , "
+ "ip_address = ?, mac_no = ?, login_id= ? "
+ "WHERE session_id = ?";
//logger.debug(strQuery);
try {
ps = conn.prepareStatement(strQuery);
ps.setInt(1, this.user.getUserID());
ps.setTimestamp(2, this.beginDate);
ps.setString(3, this.ipAddress);
ps.setString(4, this.macNO);
ps.setString(5,this.loginID);
ps.setString(6, this.sessionID);
int resultCount = ps.executeUpdate();
if (resultCount != 1) {
throw new Exception("User_session.doUpdate(): ERROR updating data in T_SYS_USER_SESSION!! "
+ "resultCount = " + resultCount);
}
} catch (SQLException se) {
throw new Exception("User_session.doUpdate(): SQLException while updating user_session; "
+ "session_id = " + this.sessionID + " :\n\t" + se);
} finally {
close(null, ps, null);
}
}
/**
* 根据IP更新该用户会话对象
*
* @throws Exception
* 如果更新有问题,将抛出异常
*/
public void doUpdateByIP() throws Exception {
if (!isValidate()) {
throw new Exception("User_session.doUpdateByIP(): Illegal data values for update");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet result = null;
String strQuery = "UPDATE " + Common.USER_SESSION_TABLE + " SET "
+ "session_id = ?, user_id = ?, begin_date = ? , "
+ " mac_no = ?, login_id= ? "
+ "WHERE ip_address = ?";
try {
conn=PlatformDao.getDataSource().getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement(strQuery);
ps.setString(1, this.sessionID);
ps.setInt(2, this.user.getUserID());
ps.setTimestamp(3, this.beginDate);
ps.setString(4, this.macNO);
ps.setString(5,this.loginID);
ps.setString(6, this.ipAddress);
int resultCount = ps.executeUpdate();
if (resultCount != 1) {
conn.rollback();
throw new Exception("User_session.doUpdateByIP(): ERROR updating data in T_SYS_USER_SESSION!! "
+ "resultCount = " + resultCount);
}
conn.commit();
} catch (SQLException se) {
if(conn!=null){
conn.rollback();
}
throw new Exception("User_session.doUpdateByIP(): SQLException while updating user_session; "
+ "session_id = " + this.sessionID + " :\n\t" + se);
} finally {
conn.setAutoCommit(true);
close(conn, ps, result);
}
}
/**
* 根据登录ID更新该用户会话对象
*
* @throws Exception
* 如果更新有问题,将抛出异常
*/
public void doUpdateByLoginID() throws Exception {
if (!isValidate()) {
throw new Exception("User_session.doUpdateByLoginID(): Illegal data values for update");
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet result = null;
String strQuery = "UPDATE " + Common.USER_SESSION_TABLE + " SET "
+ "session_id = ?, user_id = ?, begin_date = ? , "
+ "ip_address = ?, mac_no = ? "
+ "WHERE login_id= ?";
try {
conn=PlatformDao.getDataSource().getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement(strQuery);
ps.setString(1, this.sessionID);
ps.setInt(2, this.user.getUserID());
ps.setTimestamp(3, this.beginDate);
ps.setString(4, this.ipAddress);
ps.setString(5, this.macNO);
ps.setString(6,this.loginID);
int resultCount = ps.executeUpdate();
if (resultCount != 1) {
conn.rollback();
throw new Exception("User_session.doUpdateByLoginID(): ERROR updating data in T_SYS_USER_SESSION!! "
+ "resultCount = " + resultCount);
}
conn.commit();
} catch (SQLException se) {
if(conn!=null){
conn.rollback();
}
throw new Exception("User_session.doUpdateByLoginID(): SQLException while updating user_session; "
+ "session_id = " + this.sessionID + " :\n\t" + se);
} finally {
conn.setAutoCommit(true);
close(conn, ps, result);
}
}
/**
* 在数据库中删除该用户会话对象,不提交。
* @param conn 连接对象
* @throws Exception
* 如果删除有问题,将抛出异常
*/
public void doDelete(Connection conn) throws Exception {
PreparedStatement ps = null;
// Organize org = null;
String strQuery = "DELETE FROM " + Common.USER_SESSION_TABLE
+ " WHERE session_id = ?";
try {
ps = conn.prepareStatement(strQuery);
ps.setString(1, this.sessionID);
int resultCount = ps.executeUpdate();
if (resultCount != 1) {
throw new Exception("User_session.doDelete(): ERROR deleting data in T_SYS_USER_SESSION!! "
+ "resultCount = " + resultCount);
}
} catch (Exception se) {
throw new Exception("User_session.doDelete(): Exception while deleting user_session; "
+ "session_id = " + this.sessionID + " :\n\t" + se);
} finally {
close(null, ps, null);
}
}
/**
* 返回数据库中的所有用户会话对象
*
* @return 用户会话对象集合
* @throws Exception
* 如果查找有问题,将抛出异常
*/
public Vector getAllUserSessions() throws Exception
{
Vector vAllUserSessions = new Vector();
Connection conn = null;
PreparedStatement ps = null;
ResultSet result = null;
String strQuery = "SELECT ut.user_id,ut.user_name,ut.login_name,ut.flag_emp,"
+ "ut.user_cryptogram,ut.flag_lock,ut.flag_define,ut.ic_no,ut.conn_num,"
+ "ut.flag_check,ut.flag_active,ut.flag_sa,ut.show_order,ut.position_x,ut.position_y,ut.type,"
+ "ust.session_id,ust.begin_date,ust.ip_address,ust.mac_no,ust.login_id "
+ "FROM " + Common.USER_TABLE + " ut, "
+ Common.USER_SESSION_TABLE + " ust "
+ "WHERE ut.user_id = ust.user_id";
try {
conn = PlatformDao.getDataSource().getConnection();
ps = conn.prepareStatement(strQuery);
result = ps.executeQuery();
int i = 1;
ValueAsc va = new ValueAsc(i);
while (result.next())
{
i = 1;
va.setStart(i);
User uTemp = User.generateUser(result,va);
UserSession usTemp = UserSession.generateUserSession(result,va,uTemp);
vAllUserSessions.addElement(usTemp);
}
}
catch (SQLException se)
{
throw new Exception("User_session.getAllUserSessions(): SQLException: \n\t" + se);
}
finally
{
close(conn, ps, result);
}
return vAllUserSessions;
}
/**
* 生成查询会话对象
* @param result 查询结果集
* @param v 计数器
* @return 返回生成的对象
*/
public static UserSession generateUserSession(ResultSet result,ValueAsc v,User user) {
UserSession usTemp=new UserSession();
try{
usTemp.setSessionID(result.getString(v.next()));
usTemp.setBeginDate(result.getTimestamp(v.next()));
usTemp.setIpAddress(result.getString(v.next()));
usTemp.setMacNO(result.getString(v.next()));
usTemp.setLoginID(result.getString(v.next()));
usTemp.setUser(user);
}catch(Exception e){
e.printStackTrace();
}
return usTemp;
}
/**
* 验证存入用户会话表中的数据
*
* @return true: 验证成功
* false: 验证失败
*/
protected boolean isValidate()
{
if ( (this.sessionID == null) ||
(this.user == null) ||
(this.user.getUserID() == 0))
{
return (false);
}
else
{
return (true);
}
}
/**
* 存储会话变量,放入session还是自定义的属性集合
* @param type 1:放入session中,2:放入自定义的属性集合中
*/
public static SessionProperty setAttributeBatch(String type,HttpSession session,User user) throws Exception {
SessionProperty sp=null;
if(type.equals(UserSession.STORE_SESSION)){
sp=new SessionProperty(session);
}else{
sp=new SessionProperty();
}
//设置session变量
Vector authorities=null;
try{
authorities=user.getAuthoritiesFromContext();
//authorities=new Vector();
sp.setAttribute("authority",authorities);
sp.setAttribute("user",user);
sp.setAttribute("sa",user.getFlagSA());
}catch(Exception e){
throw e;
}
/*
for(int i=0;i<authorities.size();i++){
Authority au=(Authority)authorities.get(i);
logger.debug(au.getAuthorityID());
logger.debug(au.getPath());
}
*/
return sp;
}
/**
* 服务器启动时清空会话表
*/
public static void clearSession() throws Exception
{
try
{
Vector vAllSession = new UserSession().getAllUserSessions();
int nNum = vAllSession.size();
UserSession[] delTemp=new UserSession[nNum];
UserSessionHistory[] addTemp=new UserSessionHistory[nNum];
for (int i=0; i<nNum; i++)
{
UserSession us=(UserSession)vAllSession.get(i);
String strSessionID=us.getSessionID();
Timestamp tBegin=us.getBeginDate();
String strIP=us.getIpAddress();
String strMacNO=us.getMacNO();
User user=us.getUser();
User admin=new User(1);
admin.load();
delTemp[i]=us;
//在历史表中增加一条记录
UserSessionHistory ush=new UserSessionHistory(strSessionID);
ush.setBeginDate(tBegin);
ush.setEndDate(Common.getSysDate());
ush.setIpAddress(strIP);
ush.setMacNO(strMacNO);
ush.setUser(user);
ush.setLoginFlag(UserSession.LOGIN_SUCCESS);
ush.setLogoutFlag(UserSession.LOGOUT_NO);
ush.setCancelPerson(admin);
addTemp[i]=ush;
}
new UserSession().doDeleteBatch(delTemp);
new UserSessionHistory().doAddBatch(addTemp);
}
catch(Exception e)
{
e.printStackTrace();
throw new Exception("UserSession.clearSession(): SQLException: \n\t" + e);
}
}
}
========上面的session是这里传过来的===
package ces.frame.module.login.action;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import ces.frame.module.utilize.bo.ArchiveExborrowBO;
import ces.frame.util.CommonUtil;
import ces.frame.util.Transition;
import ces.frame.util.dao.CommonDao;
import ces.platform.system.action.UserSessionAction;
import ces.platform.system.common.MD5;
import ces.platform.system.common.SessionBind;
import ces.platform.system.dbaccess.LoginableTime;
import ces.platform.system.dbaccess.User;
import ces.platform.system.dbaccess.UserSession;
import ces.platform.system.form.UserSessionForm;
/**
*
* @author nfs
*
*/
public class LoginAction extends DispatchAction
{
private ArchiveExborrowBO archiveExborrowBO = null;
public ArchiveExborrowBO getArchiveExborrowBO() {
return archiveExborrowBO;
}
public void setArchiveExborrowBO(ArchiveExborrowBO archiveExborrowBO) {
this.archiveExborrowBO = archiveExborrowBO;
}
/**
* ��¼
* @param request
* @param form
* @return
*/
public ActionForward login(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
String target = "success";
String tip = "tip";
//�û������Ƿ�ҪMD5
String encrypt = "true";
HttpSession session = request.getSession(true);
DynaActionForm dForm = (DynaActionForm)form;
Vector vector = new Vector();
HashMap map = new HashMap();
map.put("urlName", "���µ�¼");
map.put("urlValue", "/login.jsp");
vector.add(map);
request.setAttribute("loginTip","1");
String loginName = dForm.get("loginName").toString();
String userPass = dForm.get("userPass").toString();
//0�������ʲ�ݵ�½ 1�����������ҵ�½
String is_szdag = dForm.get("is_szdag").toString();
if (!"false".equals(encrypt))
{
//�ѱ����ϵ�����MD5
userPass = new MD5().getMD5ofStr(userPass);
}
int userID = 0;
User user = null;
String strSessionID = "";
String strCount = "";
int intCount = 0;
UserSession usAdd = null;
try
{
int ID = new User().getUserID(loginName);
boolean flag = new LoginableTime().isLoginable();
if (ID!=1)
{
if (!flag)
{
request.setAttribute("url", vector);
request.setAttribute("message", "��ֹ��¼��");
return mapping.findForward(tip);
}
}
/*
//���Ϊ���������ҵ�½���ж��û��Ƿ���ڿɵ�½
String sql = "select count(*) from t_role_user t where t.user_id='"+ID+"' and t.role_id=(select t.role_id from t_role t where t.rolekey='CDRY')";
int count = CommonDao.getJdbcTemplate().queryForInt(sql);
if(count==0 && "1".equals(is_szdag)){
//loginName="";
}*/
//======================
}
catch (Exception e)
{
request.setAttribute("url", vector);
request.setAttribute("message", e.getMessage());
return mapping.findForward(tip);
}
strCount = (String)session.getAttribute("count");
if ((strCount!=null) && (!strCount.equals("")))
{
intCount = java.lang.Integer.parseInt(strCount);
}
// if (intCount>=3)
// {
// request.setAttribute("messageKey", messageKey + "overlogin");
// return mapping.findForward("error");
// // "�Բ������Ѿ��Ƿ���¼3�Σ����
登陆登出
猜你喜欢
转载自yuhuiblog6338999322098842.iteye.com/blog/2162930
今日推荐
周排行