k2.interceptor.AbstractInterceptor。
Struts 2的基石——拦截器(Interceptor)(4)
时间:2011-06-29 BlogJava Max
以下例子演示通过继承AbstractInterceptor,实现授权拦截器。
首先,创建授权拦截器类tutorial.AuthorizationInterceptor,代码如下:
package tutorial;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class AuthorizationInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation ai) throws Exception {
Map session = ai.getInvocationContext().getSession();
String role = (String) session.get( " ROLE " );
if ( null != role) {
Object o = ai.getAction();
if (o instanceof RoleAware) {
RoleAware action = (RoleAware) o;
action.setRole(role);
}
return ai.invoke();
} else {
return Action.LOGIN;
}
}
}
以上代码相当简单,我们通过检查session是否存在键为“ROLE”的字符串,判断用户是否登陆。如果用户已经登陆,将角色放到Action中,调用Action;否则,拦截直接返回Action.LOGIN字段。为了方便将角色放入Action,我定义了接口tutorial.RoleAware,代码如下:
package tutorial;
public interface RoleAware {
void setRole(String role);
}
接着,创建Action类tutorial.AuthorizatedAccess模拟访问受限资源,它作用就是通过实现RoleAware获取角色,并将其显示到ShowUser.jsp中,代码如下:
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class AuthorizatedAccess extends ActionSupport implements RoleAware {
private String role;
public void setRole(String role) {
this .role = role;
}
public String getRole() {
return role;
}
@Override
public String execute() {
return SUCCESS;
}
}
Struts 2的基石——拦截器(Interceptor)(5)
时间:2011-06-29 BlogJava Max
以下是ShowUser.jsp的代码:
<% @ page contentType = " text/html; charset=UTF-8 " %>
<% @taglib prefix = " s " uri = " /struts-tags " %>
< html >
< head >
< title > Authorizated User </ title >
</ head >
< body >
< h1 > Your role is: < s:property value ="role" /></ h1 >
</ body >
</ html >
然后,创建tutorial.Roles初始化角色列表,代码如下:
package tutorial;
import java.util.Hashtable;
import java.util.Map;
public class Roles {
public Map < String, String > getRoles() {
Map < String, String > roles = new Hashtable < String, String > ( 2 );
roles.put( " EMPLOYEE " , " Employee " );
roles.put( " MANAGER " , " Manager " );
return roles;
}
}
接下来,新建Login.jsp实例化tutorial.Roles,并将其roles属性赋予<s:radio>标志,代码如下:
<% @ page contentTy
|