struts2小小專案 經驗總結(2) 攔截器
阿新 • • 發佈:2018-12-10
- 如果說一個網站可以直接訪問到需要登入後才能訪問的網頁,這是很失敗的,所以,必須實現這樣一個功能,就是客戶端不可以直接訪問非登入介面的網頁,這個功能可以使用struts2的攔截器來實現,就是如果有使用者賦值拿已經登入的網頁貼上訪問的話,是會跳到登入介面的。
- 要使用struts2的攔截器,要在配置配置檔案中配置好攔截器,做法是醬紫的
- 在struts.xml的package標籤中配置攔截器
<!--使用interceptors宣告一個攔截器--> <interceptors> <interceptor name="authotity" class="intercepter.AuthorityInterceptor"/> </interceptors>
包括宣告攔截器的名字和它的實現類,實現類如下
package intercepter; import action.dao.DbBean; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; import java.util.Map; /** * Demo class * * @author lin * @date 2018/11 * 攔截器類 */ public class AuthorityInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception{ ActionContext actionContext = invocation.getInvocationContext(); String name = invocation.getInvocationContext().getParameters().get("name").getValue(); String pass = invocation.getInvocationContext().getParameters().get("pass").getValue(); // 通過上面的方法獲得從jsp介面表單傳過來的name和pass DbBean dbBean = new DbBean(name, pass); // 例項化一個數據庫bean例項 // 使用資料庫bean例項的驗證登入方法來驗證是否為合法輸入,如果是則不攔截,否則返回login, // 跳回index.jsp if(dbBean.verifyLogin()){ return invocation.invoke(); } actionContext.put("tip", "還沒有登入~~"); return "login"; } }
-
然後在需要使用攔截器攔截的action下配置,需要注意的是,要先用預設的攔截器攔截之後,才可以使用自定義的攔截器攔截
<action name="loginAction" class="action.Actions.LoginAction"> <result>searchPics.jsp</result> <result name="error">index.jsp</result> <result name="login">index.jsp</result> <interceptor-ref name="defaultStack"/> <interceptor-ref name="authotity"/> </action>
- 在struts.xml的package標籤中配置攔截器