AOP思想,可以用于日志,权限等
*实现一个如果用户没有登录,那么久不能访问好友列表,Friend.action自动到登录页面
1. 创建验证拦截器类
import java.util.Map;
import com.dyp.struts2.services.FriendServices;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class Interceptor extends AbstractInterceptor {
public String intercept(ActionInvocation ai) throws Exception {
Map session = ai.getInvocationContext().getSession();
//获取Session中的user属性
String user = (String)session.get("user");
//如果user属性不为空,且该属性值为scott
if (user != null && user.equals("scott"))
{
return ai.invoke();
}
else
{
return Action.LOGIN;
}
}
}
那么Action里就不用判断用户是否登录。比如原先的如下代码:
//获取Session中的user属性
String user = (String)ActionContext.getContext().getSession().
get("user");
//如果user属性不为空,且该属性值为scott
if (user != null && user.equals("scott"))
{
FriendServices fs = new FriendServices();
//将业务逻辑组件的返回值设置成该Action的属性
this.setFriends(fs.getFriends());
return SUCCESS;
}
else
{
return LOGIN;
}
可以改为
FriendServices fs = new FriendServices();
//将业务逻辑组件的返回值设置成该Action的属性
this.setFriends(fs.getFriends());
return SUCCESS;
1. 配置struts.xml文件
<interceptors>
<interceptor name ="auth" class ="com.dyp.struts2.action.Interceptor"/>
</interceptors>
<action name="Friend" class="friendAction">
<interceptor-ref name ="auth"/>
<!-- 如果处理结果返回login,进入login.jsp页面 -->
<result name="login">/login.jsp</result>
<!-- 如果处理结果返回success,进入showBook.jsp页面 -->
<result name="success">/showFriend.jsp</result>
</action>