码迷,mamicode.com
首页 > 其他好文 > 详细

Struts2 自定义拦截器

时间:2015-06-23 17:46:39      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

自定义拦截器(权限管理),包含了对ajax和表单请求的拦截

package com.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

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

public class AuthorityInterceptor extends AbstractInterceptor{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Override
    /* session过期及操作的权限验证拦截器 */
    public String intercept(ActionInvocation invocation) throws Exception {
        // TODO Auto-generated method stub
        // 取得请求相关的ActionContext实例 
        ActionContext context=invocation.getInvocationContext();
        Map session=context.getSession();
        String employ=(String)session.get("employ");
        
        
        if(!ServletActionContext.getRequest().isRequestedSessionIdValid()){
            // session 过期
             //return Action.LOGIN;
            //对ajax请求的拦截
            return isAjax();
        }else if (employ==null) {
            //没有登陆,将服务器提示设置成一个HttpServletRequest属性  
            context.put("tip","您还没有登录,请登陆系统"); 
            return isAjax();           
            
        }else {
            return invocation.invoke();
        }
        
        
    }// end function

    private String isAjax() {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setCharacterEncoding("text/html;charset=utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String flag = "";
        if (request.getHeader("X-Requested-With") != null
        && request.getHeader("X-Requested-With").equalsIgnoreCase(     
        "XMLHttpRequest")) {  
            
            flag = "sessionfalse";
            pw.write(flag);
            return null;
         }else{
           return Action.LOGIN;
        }
    }
    

}

 

Struts2 自定义拦截器

标签:

原文地址:http://www.cnblogs.com/heyesp/p/4595677.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!