自己学习的一点知识的总结!!
(1)先写一个拦截器的类
package com.vrv.nj.cims.action;
import java.util.Map;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class CheckLoginInterceptor extends AbstractInterceptor {
/**
*
*/
private static final long serialVersionUID = 1L;
public static final String LOGIN_KEY = "username";(session中的key值)
public static final String LOGIN_PAGE = "userLogin.jsp";登录的的页面
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
System.out.println("begin check login interceptor!");
// 对LoginAction不做该项拦截
Object action = actionInvocation.getAction();
if (action instanceof LoginAction) {
System.out.println("exit check login, because this is login action.");
return actionInvocation.invoke();
}
// 确认Session中是否存在LOGIN
Map session = actionInvocation.getInvocationContext().getSession();
String login = (String) session.get(LOGIN_KEY);
if (login != null && login.length() > 0) {
// 存在的情况下进行后续操作。
System.out.println("already login!");
return actionInvocation.invoke();
} else {
// 否则终止后续操作,返回LOGIN
System.out.println("no login, forward login page!");
return Action.LOGIN;
}
}
}
(2)在struts.xml配置文件中配置拦截器
<!-- 拦截器必须要定义在action的上面 -->
<!-- 配置拦截器 -->
<interceptors>
<!-- 定义拦截器 -->
<interceptor name="loginInterceptor"
class="com.vrv.nj.cims.action.CheckLoginInterceptor" />
<!-- 定义成默认的拦截器每个action都能用 -->
<interceptor-stack name="teamwareStack">
<interceptor-ref name="loginInterceptor" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="teamwareStack" />
<!-- 定义全局Result -->
<global-results>
<!-- 当返回login视图名时,转入/login.jsp页面 -->
<result name="login">/userLogin.jsp</result>
</global-results>
<action name="loginAction" class="com.vrv.nj.cims.action.LoginAction">
<result name="loginFail">/userLogin.jsp</result>
<result name="loginSuccess" type="redirectAction">contextList!getAllContext</result>
<result name="outSuccess">/userLogin.jsp</result>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>