1、实现原理:com.ioensymphony.xwork2.interceptor.interceptor 接口
2、案例需求:模拟登陆进入 index.jsp ,否则返回 login.jsp
3、页面 index.jsp
<body>
这个主页只有登录才能看到
</body>
4、页面 login.jsp
<body>
${message }
<form action="">
用户名:<input type="text" name ="username" /><br />
密 码:<input type="text" name ="password" /><br />
</form>
</body>
5、struts.xml 中
<struts>
<package name="interceptor" namespace="/interceptor" extends="struts-default">
<action name="visitIndex" class="cn.itcast.action.VisitAction" method="execute">
<result name="success">/index.jsp</result>
<result name="login">/login.jsp</result>
</action>
</package>
</struts>
6、在 VisitAction 中
public class VisitAction {
public String execute(){
return SUCCESS;
}
}
7、自定义拦截器 cn.itheima.interceptor.PermissionInterceptor implements Interceptor
public class PermissionInterceptor implements Interceptor{
// 判断用户是否登录
public String intercept(ActionInvocation invocation) throws Exception{
HttpSession session = ServletActionContext.getRequest().getSession();
Object obj = session.getAttribute("user");
if( obj == null){
// 如果没登录
return "login";
}else{
// 如果登陆了
return invocation.invoke(); // 放行,调用Action方法,这里就是调 VisitAction 的方法
}
}
public void destroy(){
}
public void init(){
}
}
8、使用拦截器,在 struts.xml
<package name="interceptor" namespace="/interceptor" extends="struts-default">
<interceptors>
<interceptor name="permissionInterceptor" class="cn.itheima.interceptor.PermissionInterceptor"></interceptor>
</interceptors>
<action name="visitIndex" class="cn.itcast.action.VisitAction" method="execute">
<interceptor-ref name="defaultStack"></interceptor-ref>#写上框架的拦截器,防止失效,一定放在最前面
<interceptor-ref name="permissionInterceptor"></interceptor-ref>#写了自定义的拦截器,框架默认的拦截器就失效了
<result name="success">/index.jsp</result>
<result name="login">/login.jsp</result>
</action>
</package>
9、模拟用户登录
在 1.jsp 中
<% session.setAttribute("user", "") %>
10、在 login.jsp 页面点击登录,能够进入 index.jsp ,如果8中不模拟登录,就进入不了 index.jsp 页面。