首先新建一个拦截器类
//LoginInterceptor.java
package com.stu.interceptor;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class LoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
String namespace = invocation.getProxy().getNamespace();
String actionName = invocation.getProxy().getActionName();
if(("/".equals(namespace) && "alogin".equals(actionName)) ||
("/".equals(namespace) && "alogout".equals(actionName))||
("/".equals(namespace) && "nolog".equals(actionName))){
return invocation.invoke();
} else {
Map<String, Object> session = ActionContext.getContext().getSession();
String name = (String) session.get("admin_name");
if(name == null) {
System.out.println("执行拦截器----------");
return "login";
} else {
return invocation.invoke();
}
}
}
}
//struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.objectFactory" value="spring" />
<!-- 定义包 -->
<package name="default" extends="json-default">
<!-- 添加拦截器 -->
<interceptors>
<!-- 添加登陆拦截器 -->
<interceptor name="loginValidate" class="com.stu.interceptor.LoginInterceptor"/>
<!-- 新建一个站,把登陆拦截器和默认的站放进去 -->
<interceptor-stack name="myStack">
<interceptor-ref name="defaultStack"/>
<interceptor-ref name="loginValidate"/>
</interceptor-stack>
</interceptors>
<!-- 修改默认拦截器 -->
<default-interceptor-ref name="myStack"/>
<!-- 拦截器未登录跳转 -->
<global-results>
<result name="login" type="chain">
nolog
</result>
</global-results>
<action name="alogin" class="adminAction" method="alogin">
<result name="success">/index.jsp</result>
<result name="input">/index.jsp</result>
</action>
<action name="alogout" class="adminAction" method="alogout">
<result name="success">/index.jsp</result>
</action>
<action name="nolog" class="adminAction" method="nolog">
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
action名不符合且未登录的就拦截下来,返回login。struts.xml配置拦截器,返回login就跳转到nolog.action