1. 程式人生 > >springmvc和struts2攔截器的簡單使用以及配置

springmvc和struts2攔截器的簡單使用以及配置

public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("進入方法之後。");
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
HttpSession session = request.getSession();
String name = (String) session.getAttribute("login_name");
if(name != null && name != "") {
return true;           //true表示放行,false表示攔截、不向下執行
}else { 
response.sendRedirect("login");
return false;
}
}
}
(2).在springcxm.xml中配置攔截器:
 
<!-- 配置攔截器 -->
<mvc:interceptors>
<mvc:interceptor>
  <!-- 攔截的請求 -->
  <mvc:mapping path="/**"/>
  <!-- 不攔截的請求 -->
  <mvc:exclude-mapping path="/loginController/login.do"/>
  <!-- 攔截器所在類路徑 -->
  <bean class="com.manage.inteceptor.LoginInteceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>

2、struts2攔截器
 (1).先定義一個攔截器,繼承MethodFilterInterceptor類,實現方法並在doIntercept方法裡邊處理邏輯:
package com.inteceptor;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class LoginInteceptor extends MethodFilterInterceptor {

@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
ActionContext actionContext = ActionContext.getContext();
Map<String, Object> session = actionContext.getSession();
String username = (String) session.get("username");
String result = null;
if(username != null && username != ""){
System.out.println("登入名="+username);
result = invocation.invoke();
}
return result;
}
}
還有兩個方法自己提供了空實現,這裡就沒有寫。

(2).在struts.xml中配置攔截器類:
<package name="default" extends="struts-default" namespace="/">
<interceptors>
<interceptor name="loginInteceptor" class="com.inteceptor.LoginInteceptor">
</interceptor>
<interceptor-stack name="myInteceptor">
  <!-- struts預設執行的攔截器 -->
  <interceptor-ref name="defaultStack"></interceptor-ref>
  <interceptor-ref name="loginInteceptor">
     <param name="excludeMethods">login,doLogin</param> 
  </interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myInteceptor"></default-interceptor-ref>

 <action name="login" class="com.action.LoginAction" method="login">
  <result name="success" >/WEB-INF/jsp/hello.jsp</result>
  <result name="error">index.jsp</result>
 </action>
 <action name="hello" class="com.action.LoginAction" method="list">
  <result name="success">/WEB-INF/jsp/list.jsp</result>
  <result name="error">/error.jsp</result>
 </action>
</package>
  這裡注意的是一定要配置預設的攔截器defaultStack,而且要放到自定義攔截器的前面。這樣它才會首先載入struts預設一定要載入的攔截器。