struts2拦截器使用(部分拦截和全局拦截器)

应用场景:在请求处理之前拦截请求,做出相关处理。比如在一个网站中,用户尚未登录那么他是无法查看个人信息界面的。这时候我们就可以使用拦截器来拦截他访问个人信息的界面的请求。具体如下(这里主要是struts2自定义拦截器的方法):

struts2自定义拦截器:

1  实现Iterceptor接口或者继承AbstractInterceptor

2 在struts.xml文件配置拦截器

3 在需要使用拦截器的action中引用上述拦截器(部分拦截),也可以将上述拦截器定义为默认拦截器(全局拦截),这样可以拦截所有请求

 

部分拦截

1 本案例是自定义拦截器是继承AbstractInterceptor:

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {

	private static final long serialVersionUID = -4334179734031489644L;

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		Object action=actionInvocation.getAction();
		System.out.println(action.toString()+"========="+action);
		    String user=(String) actionInvocation.getInvocationContext().getSession().get("user");
		    if(user==""||user==null){
		    	System.out.println("尚未登录拦截请求,返回登录界面");
		    	return "login";
		    }
		   return  actionInvocation.invoke();
	}
}

2 在struts.xml配置拦截器:





  
   
           
   
   
     
   
   
   
          
     /index.jsp
   
   
     
     
       /success.jsp
       /error.jsp
     
     
         
             /index.jsp
             /register.jsp
     
     
     
            /index.jsp
               
            
     
     
     
              /index.jsp
              
              
     
   
   

 

全局拦截:

思路如下在一个(假如叫做A)里定义好拦截器,并且通过设置成默认拦截器,然后在另一个(假如叫做B)继承它,那么B中的所有action将被拦截到:





  
  
  
  
  
     
       
       
           
                   
            
     
    
  
  
  
  
   
       
   
   
     /index.jsp
   
   
     
       /success.jsp
       /error.jsp
     
     
         
             /index.jsp
             /register.jsp
     
     
     
            /index.jsp          
     
     
     
              /index.jsp     
     
   
   

 

 

 

 

你可能感兴趣的:(struts)