維護用戶狀態(tài)――Spring中session bean的使用
來源:程序員人生 發(fā)布時間:2015-01-18 10:02:28 閱讀次數(shù):2703次
我們都知道,在web開發(fā)中1旦用戶登陸系統(tǒng),那末在他注銷登陸之前,系統(tǒng)需要保護用戶的狀態(tài),這樣他才能看到自己的內(nèi)容(比如個人主頁、消息等)。
那末如何保護用戶的狀態(tài)呢?在Spring中提供了1種bean的作用域機制,可以幫助我們輕松地管理用戶狀態(tài)。
這里用到的主要是session bean,從名字上就可以看出來,它的作用域是和session綁定的,也就是說,每個session會對應1個session bean,session bean之間互不影響。
比如我們這里想要保護的用戶狀態(tài)包括:用戶名和工號。為了方便管理,我們建立1個類UserPreferences
public class UserPreferences implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String empno;
private String name;
public String getEmpno() {
return empno;
}
public void setEmpno(String empno) {
this.empno = empno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
現(xiàn)在我們想要做的就是將UserPreferences和session綁定,那末根據(jù)bean的作用域機制,我們需要把UserPreferences的作用域設(shè)置成session:
<bean id="userPreferences" class="com.test.dto.UserPreferences" scope="session">
<aop:scoped-proxy />
</bean>
這樣的話生成的是1個代理對象,由于在singleton中注入session bean,request bean 或是 global session bean時,singleton bean只會初始化1次,而它的依賴也只會被注入1次。若不加<aop:scoped-proxy/>,那末操作的都是同1個session bean,也就是最早被注入的那個(不過在使用中,我發(fā)現(xiàn)不加<aop:scoped-proxy/>是會有毛病提示的)。而加上<aop:scoped-proxy/>后,注入到singleton中的userPreferences實際上是1個代理對象,而這個代理對象與userPreferences有著相同的public方法。調(diào)用代理對象的方法時,它會去從Http
session中尋覓真實的userPreferences對象,然后調(diào)用其對應的方法。這樣我們就能夠在singleton(比如Controller)中使用session bean了。
下面做個簡單的登陸實例:先來寫個登陸頁面:
<html>
<head><title>Login</title></head>
<body>
<form action="login" method="post">
<table>
<tr><td>工號:</td><td><input name="empno"/></td></tr>
<tr><td>姓名:</td><td><input name="name"/></td></tr>
<tr><td colspan="2"><input type="submit"/></td></tr>
</table>
</form>
</body>
</html>
然后是登陸的后臺方法:
@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView login(Employee employee) {
preferences.setEmpno(employee.getEmpno());
preferences.setName(employee.getName());
ModelAndView mv = new ModelAndView("kft/success.htm");
return mv;
}
success頁面用來展現(xiàn)登陸的用戶名和工號:
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/
jquery⑴.8.0.js"></script>
<title>Success</title>
</head>
<body>
$!preferences.empno<br/>
$!preferences.name<br/>
<input type="button" onclick="logout()" value="logout">
</body>
<script type="text/javascript">
function logout(){
window.location.href = 'logout';
}
</script>
</html>
然后通過logout按鈕注銷登陸。
Spring的這個機制給我們提供了方便,而本質(zhì)上,還是利用HttpSession來保護用戶的狀態(tài)的。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學習有所幫助,可以手機掃描二維碼進行捐贈