注:以用戶登錄攔截爲例,session爲空不允許操作。
1、編寫Action方法類
public class UserAction{
private String message;
public String getMessage(){
return this.message;
}
public void setMessage(String message){
this.message=message;
}
public String execute() throw Exception{
return "success";//設置想要到達的視圖
}
//................
}
2、Session實現用戶登錄攔截
原理:判斷Session中用於記錄用戶的登錄狀態是否爲空。
設置Session的屬性值,在login.jsp頁面設置:
<%
User user=new User("zhangsan","123456");
request.getSession().setAttribute("user",user);
%>
使用EL表達式接收頁面消息: ${message}
3、實現自定義攔截器
自定義攔截器需要實現Interceptor接口:
public class MyInterceptor implements Interceptor {
public void destroy() {
// TODO Auto-generated method stub
}
public void init() {
// TODO Auto-generated method stub
}
public String intercept(ActionInvocation invocation) throws Exception {
Object user=ActionContext.getContext().getSession().get("user");
if(user!=null)return invocation.invoke();
else{
ActionContext.getContext.put("message","用戶無該操作權限!");
return "message";
}
}
}
4、struts.xml下配置消息頁面和註冊攔截器
<!-- 配置消息頁面 -->
<global-results>
<result name="message">/WEB-INF/page/message.jsp</results>
<result name="success">/WEB-INF/page/index.jsp</results>
</global-results>
</global-results>
<!-- 配置Action類 -->
<action name="list_*" class="com.struts.action.UserAction" method="{1}"></action>
<!-- 註冊攔截器 -->
<interceptors>
<interceptor name="promission" class="com.struts.interceptor.MyInterceptor"></interceptor>
</interceptors>
5、攔截器的引用
在action中的引用
<action name="user" class="com.struts.action.UserAction">
<interceptor-ref name="permission"/>
</action>
注:在action中引用攔截器時,默認的攔截器會失效。
6、攔截器棧
爲了解決自定義攔截器影響而使struts2的默認攔截器失效,故引入堆棧。
<interceptor-stack name="permissionStack">
<interceptor-ref name="defaultStack"/><!-- 必須先調用默認的棧攔截器實現 -->
<interceptor-ref name="permission"/>
</interceptor-stack>
設置全局的默認攔截器:
<default-interceptor-ref name="permissionStack"/>
注:全局的默認攔截器與<interceptors></interceptors>同級。