Struts2拦截器-实现登录拦截实例

阅读更多

【1】struts.xml:

 

   
          
              
              
            
              
              
                  
                  
              
        
        
         
        
           
          
              
            /login.jsp  
        
        
        
          
            /main.jsp  
              
              
          
        
        
        
        
            /login.jsp  
            /login.jsp 
        
       

 【2】自定义拦截器org.interceptot.LoginInterceptor:

package org.interceptot;
import java.util.Map;  

import com.opensymphony.xwork2.Action;  
import com.opensymphony.xwork2.ActionContext;  
import com.opensymphony.xwork2.ActionInvocation;  
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;  
public class LoginInterceptor extends AbstractInterceptor {  
 
    @Override  
    public String intercept(ActionInvocation invocation) throws Exception {  
  
        // 取得请求相关的ActionContext实例  
        ActionContext ctx = invocation.getInvocationContext();  
        Map session = ctx.getSession();  
        String user = (String) session.get("username");  
  
        // 如果没有登陆,即用户名不存在,都返回重新登陆  
        System.out.println("user:"+user);
        if (user != null) {  
            System.out.println("test");  
            return invocation.invoke();  
        }  
        System.out.println("你还没有登录"); 
        ctx.put("tip", "你还没有登录");  
        return Action.LOGIN;    //返回一个叫login的result结果
  
    }  
  
}  

 【3】进入主页面的Action:org.action.showAction

package org.action;

import com.opensymphony.xwork2.ActionSupport;  

public class showAction extends ActionSupport {  
 public String execute() {  
  return "success";  
 }  
}  

 

 

【4】LoginAction:

private boolean isInvalid(String value) {     
return (value == null || value.length() == 0);     
}  
if (isInvalid(user.getUsername()))   
       return INPUT;     
 if (isInvalid(user.getPassword()))     
       return INPUT;    
 //登录成功将User放入session中
HttpServletRequest request = ServletActionContext.getRequest();
Map  map=ActionContext.getContext().getSession();
map.put("username", user.getUsername());

 转自http://blog.sina.com.cn/s/blog_77cb836301015m3y.html

你可能感兴趣的:(Struts2拦截器-实现登录拦截实例)