Struts2 拦截器——LoginInterceptor

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.latitude.bsemgr.model.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
*
* @author HuangHui
*
*/
@SuppressWarnings("serial")
public class LoginInterceptor extends AbstractInterceptor {

public String intercept(ActionInvocation invocation) throws Exception {

ActionContext context = ActionContext.getContext();
HttpServletResponse response = (HttpServletResponse) context
.get(ServletActionContext.HTTP_RESPONSE);

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

// 对LoginAction不做该项拦截
Object action = invocation.getProxy().getActionName();
if (action.equals("login") || action.equals("logout")) {
return invocation.invoke();
}

// 确认session 中是否存在loginSession
User loginSession = (User) ActionContext.getContext().getSession().get("login");
if (loginSession != null) {
// 存在的情况下,进行后续操作
return invocation.invoke();
} else {
// 否则终止后续操作,返回LOGIN_PAGE
response.setStatus(301);
out.println("您还没有登录,3秒后自动转入登录页面!!!");
response.setHeader("refresh", "3;url=/bsemgr/login.jsp");
return null;
}

}

}


-------------------------- struts.xml 配置如下 --------------------------------
<interceptors>
             <interceptor name="LoginInterceptor"      class="com.weidu.imp.util.LoginInterceptor"/>
        <interceptor-stack name="loginInterceptorStack">
        <interceptor-ref name="LoginInterceptor"/>
        <interceptor-ref name="defaultStack"/>
        </interceptor-stack>
</interceptors>
<!-- 配置成默认的拦截器,每个action都经过此拦截器-->
<default-interceptor-ref name="loginInterceptorStack"/>


猜你喜欢

转载自hospop.iteye.com/blog/1743614