背景:
我们都知道strut2的action是可以直接通过超链接直接访问的,但在我们访问某个网站时,用户如果没有登录是不可以直接访问某些页面的,这时候就需要用到拦截器将用户的请求拦截下来,然后判断用户是否登录。
1.首先编写我们自己的拦截类,继承MethodFilterInterceptor类
package com.action.interceptor;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.action.admin.AdminAction;
import com.action.user.UserAction;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;
public class MyInterceptor extends MethodFilterInterceptor{
/*
1.interceptor接口
2.继承AbstractInterceptor类
3.继承MethodFilterInterceptor类,可以实现指定放行的方法,最后在拦截器类拦截action
*/
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
// TODO Auto-generated method stub
System.out.print("方法拦截器");
//当请求的是userAction则拦截下来,默认将strut2.xml中配置好的方法放行,例如用户的登录祖册等
//拦截用户请求,判断是否登录
if(UserAction.class.equals(invocation.getAction().getClass()))
{
HttpServletRequest request=ServletActionContext.getRequest();
String user=(String)request.getSession().getAttribute("user");
if(user==null||user.equals(""))
{
System.out.print("拦截请求,用户未登录");
return "defail";
}
else
{
return invocation.invoke();
}
}
//拦截管理员请求,判断是否登录
if(AdminAction.class.equals(invocation.getAction().getClass()))
{HttpServletRequest request=ServletActionContext.getRequest();
String admin=(String)request.getSession().getAttribute("admin");
if(admin==null||admin.equals(""))
{
System.out.print("拦截请求,管理员未登录");
return "defail";
}
else
{
return invocation.invoke();
}
}
// invocation.invoke();
return null;
}
}
2.在strut2.xml中配置我们的相关拦截信息
<!-- 配置拦截栈和自己的拦截器 -->
<interceptors>
<interceptor name="myinterceptor" class="com.action.interceptor.MyInterceptor">
<!-- 拦截器放行的指定方法, 例如:用户登录注册,管理员登录--userLogin,adminLogin,userRegister这些都是一些处理用户登录注册的方法>
<param name="excludeMethods">userLogin,adminLogin,userRegister</param>
<!-- 拦截器拦截的指定方法: <param name="includeMethods ">edit,add</param>-->
</interceptor>
<!-- 自己设定拦截栈 -->
<interceptor-stack name="mystack">
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="myinterceptor">
</interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 设置自己的拦截栈为默认的,所有的action都会默认走 -->
<default-interceptor-ref name="mystack"></default-interceptor-ref>
注:所有的请求都默认的走拦截栈中的拦截器,自己设定的放行方法将不会被拦截。
在拦截类中我们判断是用户请求操作还是管理员请求操作,然后执行相应的判断。