同一瀏覽器中同一JavaWeb程式不共享session方法
1、要求
在使用struts1開發JavaWeb專案中,要求超級管理員登入進入之後,展示普通使用者列表,在普通使用者列表中新增管理使用者按鈕,點選後,在瀏覽器中另外彈出一個標籤頁,而且該標籤頁是選中的普通使用者登入後的介面。
2、產生問題
a、點選普通使用者登入後,session中的使用者資訊已經變為了該使用者的資訊了,如果再次重新整理超級管理員登入的介面,此時,介面就變為選中的普通使用者登入的介面了。
b、同一個系統,在同一瀏覽器中的session的ID是相同的,此sessionID是伺服器建立session產生的,無法在客戶端修改sessionid,若想修改sessionid,得從伺服器端修改(沒試過)。
3、解決辦法
a、生成一個不重複的值,我取名為sid
例、Random random = new Random();
StringBuffer sid = new StringBuffer();
sid = sid.append(System.currentTimeMillis()); //取系統時間
// 加上10為0-9隨機數確保sid不重複
for (int i = 0; i < 10; i++) {
sid = sid.append(random.nextInt(10));
}
b、把需要的使用者相關的欄位和sessionid一起寫到一個Map
例、Map sessionMap = new HashMap();
sessionMap.put("username", username);
sessionMap.put("userpwd", userpwd);
sessionMap.put("sessionid", session.getId());
sessionMap.put("usertype", userbean.getUsertype());
c、把sid和map關聯起來新增到session中
例、session.setAttribute(sid.toString(), sessionMap);
d、把sid傳遞給jsp頁面(需通過sid獲取使用者資訊)
例、ActionRedirect redirect = new ActionRedirect(actionMapping
.findForward("index"));
redirect.addParameter("sid",sid.toString()); request.getSession().setAttribute("userbean",userbean);
return redirect;
e、jsp頁面通過sid獲取使用者資訊
例、String sid = request.getParameter("sid");
Map utitle = new HashMap();
utitle = (Map)request.getSession().getAttribute(sid);
String username = (String)utitle.get("username");
String usertype = (String)utitle.get("usertype");
String uid = (String)utitle.get("uid");
System.out.println(uid+"=====uid===~~~====");
f、把獲取的值傳遞給需要的頁面
例、 <iframe scrolling="auto" frameborder="0" height="100%" width="100%"src="<%=appContext %>/main/main.jsp?usertype=<%=usertype %>&uid=<%=uid %>" name="mainFrame"></iframe>
g、jsp頁面獲取需要的值
例、String usertype1 = "";
String uid = "";
usertype1 = (String)request.getParameter("usertype");
uid = (String)request.getParameter("uid");
http://www.blogjava.net/DreamAngel/archive/2012/06/08/380306.html和
http://aazham.iteye.com/blog/1184220