struts2 需要加一個攔截器在action中做登錄驗證校驗,主要的思想是登錄後在session中存儲一個標志,然後在過濾器中驗證這個標志,如果有則通過驗證。如果沒有,則返回到登錄頁面。
過濾器代碼如下,我把標志就設置為username,需要修改的同學自己改名字
package com.tc.blacktea.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.ServletRedirectResult;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class LoginInterceptor implements Interceptor {
private static final long serialVersionUID = -2255797147687651066L;
private static final Log log = LogFactory.getLog(LoginInterceptor.class);
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context.get(ServletActionContext.HTTP_REQUEST);
HttpSession session = request.getSession();
String username=(String)session.getAttribute("username");
if (username == null) {
ServletRedirectResult result = new ServletRedirectResult();
result.setLocation("/toLogin.action");
try {
result.execute(invocation);
} catch (Exception ex) {
log.error("Unable to create debugging console", ex);
}
return Action.NONE;
}
return invocation.invoke();
}
public void destroy() {
}
public void init() {
}
}