アクションリクエストクラス
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も入力されます。これは、カスタムアクセス許可インターセプターが実際に有効であることを示しています。