簡單實現Struts2的許可權攔截器
阿新 • • 發佈:2021-01-01
技術標籤:Struts2Struts2interceptorAOP攔截器
Action請求類
package action;
public class SystemAction {
public String execute() {
return "success";
}
}
自定義攔截器
package interceptors; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class PermissionInterceptor extends AbstractInterceptor { @Override public String intercept(ActionInvocation invocation) throws Exception { String currentUser = (String)ActionContext.getContext().getSession().get("currentUser"); if (null != currentUser) { // 執行Action中的方法或呼叫其後的攔截器 return invocation.invoke(); } return "fail"; // 當前使用者為null時跳轉至fail檢視 } }
Struts2核心配置struts.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="strutsCore" namespace="/interceptor" extends="struts-default"> <interceptors> <!-- 註冊自定義PermissionInterceptor攔截器 --> <interceptor name="permissionInterceptor" class="interceptors.PermissionInterceptor"/> </interceptors> <action name="systemAction" class="action.SystemAction"> <!-- 為Action關聯自定義攔截器,此後系統預設的攔截器自動失效 --> <interceptor-ref name="permissionInterceptor"/> <!-- 開啟strust-default.xml中的預設攔截器棧 --> <interceptor-ref name="defaultStack"/> <result name="success">/welcome.jsp</result> <result name="fail">/fail.jsp</result> </action> </package> </struts>
檢視:index.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<h2>This is page index!</h2>
</body>
</html>
檢視:welcome.jsp
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Welcome</title> </head> <body> <h2>This is page welcome!</h2> </body> </html>
檢視:login.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<% session.setAttribute("currentUser", "WanAkiko"); %>
<h2>提示:登入成功,WanAkiko,歡迎回來!</h2>
</body>
</html>
檢視:logout.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Logout</title>
</head>
<body>
<% session.removeAttribute("currentUser"); %>
<h2>提示:當前使用者已退出!</h2>
</body>
</html>
檢視:fail.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Fail</title>
</head>
<body>
<h2>This is page fail!</h2>
</body>
</html>
使用Chrome與IE對自定義攔截器進行測試
測試結果:專案啟動後即訪問index.jsp,此時若未登入,則通過SystemAction訪問的是fail.jsp,若進入login.jsp後再次對SystemAction進行請求則訪問welcom.jsp,此後若再執行logout.jsp後又執行SystemAction則亦會進入fail.jsp,由此可見我們自定義的許可權攔截器確實在生效。