用拦截器实现登录验证功能AuthorizationInterceptor:
package com.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.*;
import com.opensymphony.xwork2.*;
import java.util.*;
/**
* @author http://xp9802.iteye.com/
*/
public class AuthorizationInterceptor extends AbstractInterceptor {
private String ignoreActions;
// ignoreActions属性的getter方法
public String getIgnoreActios() {
return ignoreActions;
}
// ignoreActions属性的setter方法
public void setIgnoreActions(String ignoreActions) {
this.ignoreActions = ignoreActions;
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ctx = invocation.getInvocationContext();
Map session = ctx.getSession();
String user = (String) session.get("username");
boolean ignore = false;
String currentAction = invocation.getProxy().getActionName();
String[] actions = ignoreActions.split(",");
for (String action : actions) {
if (currentAction.matches(action.trim())) {
ignore = true;
break;
}
}
if (user != null || ignore == true) {
return invocation.invoke();
} else {
return Action.LOGIN;
}
}
}
在struts.xml文件里面配置该拦截器:
<interceptors>
<interceptor name="authorization" class="com.interceptor.AuthorizationInterceptor" />
<interceptor-stack name="myStack">
<interceptor-ref name="authorization">
<param name="ignoreActions"> validate_code,register.*,.*login.*,upload,connector</param>
</interceptor-ref> <interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myStack"/>