使用拦截器来检测用户是否登录
在任何一个系统中,都会有登录界面,因为只有通过验证的用户才能访问网络上的资源,在桌应用程序中,系统的入口就只有一个,那就是main函数,但是在b/s这种结构中,我们可以向服务器请求任何一个页面,也就是说有多个入口,那么我们如何限制用户只能通过登录这个界面进入系统呢,实现的方法有很多,现在介绍一种比较常用的方法,使用structs2中的拦截器:
首先我们定义一个拦截器:
public class MyInterceptor implements Interceptor{public void destroy(){// TODO Auto-generated method stubSystem.out.println("拦截器销毁!");}public void init(){// TODO Auto-generated method stubSystem.out.println("拦截器初始化");}public String intercept(ActionInvocation invocation) throws Exception{// TODO Auto-generated method stubSystem.out.println("拦截器开始验证!");if(LoginAction.class==invocation.getAction().getClass()){return invocation.invoke();}User user=(User)invocation.getInvocationContext().getSession().get("user");if(user==null)return "fail";System.out.println("用户已经登录");return invocation.invoke();}}
然后在struts.xml中配置拦截器
<interceptors> <interceptor name="login" class="com.interceptor.MyInterceptor"></interceptor> <interceptor-stack name="mystack"> <interceptor-ref name="login"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors> <default-interceptor-ref name="mystack"></default-interceptor-ref>
这样如果用户请求登录页面,可以顺利通过,如果用户请求其他页面,就需要检查用户是否已经登录,如果没有登录,则跳回登录页面