[JFinal 1] JFinal和SSH中使用拦截器的对比

导读:先前在做.NET项目时,拦截的功能主要是依靠缓存session来实现。当需要跳转到某个页面,使用某个功能查询一些数据时,会根据session中的用户值来判断是否已经正常登录,如果没有,则重定向到登录页面。那么,在java里面,是怎样做的呢。本篇博客主要是介绍一些自己在做项目的过程中的一些处理方式。


一、SSH框架中的拦截

1.1,建立拦截类,添加拦截方法

<span style="font-family:KaiTi_GB2312;font-size:18px;">public class PrivilegeInterceptor extends MethodFilterInterceptor{  
  
    @Override  
    //执行拦截的方法  
    protected String doIntercept(ActionInvocation actionInvocation) throws Exception {  
        // 判断session中是否保存了后台用户的信息  
        AdminUser existAdminUser = (AdminUser)ServletActionContext.getRequest().getSession().getAttribute("existAdminUser");  
        if(existAdminUser == null){  
            //没有登录进行访问  
            ActionSupport actionSupport = (ActionSupport)actionInvocation.getAction();  
            actionSupport.addActionError("亲!您还没有登录,请先登录!");  
            return "loginFail";  
        }else{  
            //已经登录  
            return actionInvocation.invoke();  
        }  
    }  
      
}  </span>

1.2,在struts2里面进行配置

<span style="font-family:KaiTi_GB2312;font-size:18px;"><interceptors>  
            <interceptor name="PrivilegeInterceptor" class="cn.itcast.shop.interceptor.PrivilegeInterceptor"/>  
        </interceptors> </span>

在需要使用拦截器的struts.XML中的Action配置后面配置:

<span style="font-family:KaiTi_GB2312;font-size:18px;"><interceptor-ref name="PrivilegeInterceptor"></interceptor-ref>  
    <interceptor-ref name="defaultStack"></interceptor-ref>  </span>

说明:第一行的是用户自己写的拦截,第二行是配置的默认拦截。至此,拦截就配置好了。如果没有登录的情况下去使用系统,则会将请求拦截,并根据拦截器的配置做出相应的反应,一般情况是跳转到登陆页。


二、JFinal框架中的拦截

总体说来,JFinal中的拦截配置,比SSH或者说之前的.NET项目使用都要简单。

2.1,建立拦截类

<span style="font-family:KaiTi_GB2312;font-size:18px;">package itoo.jrkj.interceptor;
import itoo.jrkj.common.model.TjUser;
import javax.servlet.http.HttpSession;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;


public class LoginInterceptor implements Interceptor{
	
	public void intercept(Invocation ai) {
        //获取缓存
        HttpSession session = ai.getController().getSession();
        
        //获取缓存中的user对象
        TjUser user = (TjUser)session.getAttribute("user");
        if (user != null) {
        	 ai.invoke();
		}else {
			ai.getController().redirect("/main/login");   //若缓存中不存在user则跳转至登录页
		}    
    }
}

</span>

2.2,配置拦截


如图,将拦截类建立好了之后,只要在页面跳转的方法前,加上圈出来的一句话,就可以实现拦截效果。简单、粗暴,但有用。


三、总结

不管是什么样的方式实现,事实上都有一个共同的流程:1,将登录用户的信息放在session里面;2,在拦截方法中去判断session里面的用户值是否为空;3,为空,重定向;不为空,访问数据。

但JFinal明显封装的比较厉害,将拦截类方法写好之后,只需要添加一句话就Ok了,真心是让人有点心神晃荡。。。。。。

原文地址:https://www.cnblogs.com/hhx626/p/6010354.html