これがサンプルプログラムです。
RoleInterceptor.java
package com.sample.common.interceptor;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.util.ValueStack;
public class RoleInterceptor implements Interceptor {
private static final long serialVersionUID = 5031826078189685536L;
@Override
public void init() {
}
@Override
public void destroy() {
}
@Override
public String intercept(ActionInvocation actionInvocation) {
String result = null;
try {
ActionContext actionContext = actionInvocation
.getInvocationContext();
ValueStack vStack = actionContext.getValueStack();
HttpSession httpSession = ServletActionContext.getRequest()
.getSession();
StringBuilder actionUrl = new StringBuilder(actionInvocation
.getProxy().getNamespace());
actionUrl.append("/");
actionUrl.append(actionInvocation.getProxy().getActionName());
if (httpSession != null) {
boolean hasPermission = true; // if the role has the permission
if (hasPermission) {
result = actionInvocation.invoke();
} else {
vStack.set("userMsg",
"You are not authorized to access this link");
result = "user.unauthorized";
}
} else {
vStack.set("userMsg", "Please login to your account");
result = "user.login";
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="userRoleInterceptor">
<interceptors>
<interceptor name="userRole"
class="com.sample.common.interceptor.RoleInterceptor" />
</interceptors>
</package>
<package name="user" namespace="/user" extends="struts-default, json-default, userRoleInterceptor">
<action name="user_details" method="getUserDetails"
class="com.sample.user.web.action.User">
<interceptor-ref name="userRole"/>
<interceptor-ref name="store">
<param name="operationMode">RETRIEVE</param>
</interceptor-ref>
<result name="success">userDetails.jsp</result>
<result name="input">/common/error.jsp</result>
<result name="busy" type="redirectAction" >/common/busy.jsp</result>
<result name="error" type="redirectAction" >/common/test.jsp</result>
<result name="user.login" type="redirectAction" >/common/login.jsp</result>
<result name="user.unauthorized" type="redirectAction" >/common/unauthorizedUser.jsp</result>
</action>
</package>
</struts>