维护用户状态——Spring中session bean的使用

我们都知道,在web开发中一旦用户登陆系统,那么在他注销登陆之前,系统需要维护用户的状态,这样他才能看到自己的内容(比如个人主页、消息等)。

那么如何维护用户的状态呢?在Spring中提供了一种bean的作用域机制,可以帮助我们轻松地管理用户状态。

这里用到的主要是session bean,从名字上就能看出来,它的作用域是和session绑定的,也就是说,每一个session会对应一个session bean,session bean之间互不影响。

比如我们这里想要维护的用户状态包括:用户名和工号。为了方便管理,我们建立一个类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;
	}

}

现在我们想要做的就是将UserPreferences和session绑定,那么根据bean的作用域机制,我们需要把UserPreferences的作用域设置成session:

	<bean id="userPreferences" class="com.test.dto.UserPreferences" scope="session">
		<aop:scoped-proxy />
	</bean>

这样的话生成的是一个代理对象,因为在singleton中注入session bean,request bean 或是 global session bean时,singleton bean只会初始化一次,而它的依赖也只会被注入一次。若不加<aop:scoped-proxy/>,那么操作的都是同一个session bean,也就是最早被注入的那个(不过在使用中,我发现不加<aop:scoped-proxy/>是会有错误提示的)。而加上<aop:scoped-proxy/>后,注入到singleton中的userPreferences实际上是一个代理对象,而这个代理对象与userPreferences有着相同的public方法。调用代理对象的方法时,它会去从Http session中寻找真正的userPreferences对象,然后调用其对应的方法。这样我们就可以在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页面用来展示登陆的用户名和工号:

<html>
	<head>
		<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
		<title>Success</title>
	</head>	
	<body>
		$!preferences.empno<br/>
		$!preferences.name<br/>
		<input type="button" οnclick="logout()" value="logout">
	</body>
	<script type="text/javascript">
		function logout(){
			window.location.href = 'logout';
		}
	</script>
</html>

然后通过logout按钮注销登陆。


Spring的这个机制给我们提供了方便,而本质上,还是利用HttpSession来维护用户的状态的。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值