Struts2 自定义拦截器

自定义拦截器(权限管理),包含了对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;
}
} }
上一篇:关于什么时候用pop什么时候用dismiss


下一篇:SIGAR - System Information Gatherer And Reporter