1.要在struts.xml文件中添加下面的代码:
<package name="struts2" extends="struts-default">
<!--自定义拦截器(没有登录的就返回到login)-->
<interceptors>
<interceptor name="sessionNull" class="com.hoperun.action.SessionNullInterceptor">
</interceptor>
</interceptors>
<global-results>
<result name="login" type="redirect">/sessionValid.jsp</result>
</global-results>
还要在具体action的跳转配置中添加下面代码:
<action name="orderSearch" class="com.hoperun.action.OrderSearchAction">
<result name="success" >/orderSearch.jsp</result>
<interceptor-ref name="sessionNull"></interceptor-ref>
<interceptor-ref name="defaultStack"/>
</action>
如果不加上面蓝色的部分,页面域中的值就不能带到下个页面,因为定义了自己的拦截器,系统传值的拦截器就失效了,所以加上这条系统默认的拦截器就生效了
2.下面是SessionNullInterceptor的拦截器具体代码:
package com.hoperun.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
/**
* session为空拦截器
*/
public class SessionNullInterceptor implements Interceptor {
private static final long serialVersionUID = 1L;
public void destroy() {
}
public void init() {
}
public String intercept(ActionInvocation invocation) throws Exception {
HttpServletRequest req = ServletActionContext.getRequest();
if (req.getSession().getAttribute("username") == null) {
return Action.LOGIN;
} else {
return invocation.invoke();
}
}
}
3,对了还不能忘记在login.acton中添加如下代码:
if(result==true)
{
Map<String,String> map = ActionContext.getContext().getSession();
map.put("username",username);
return SUCCESS;
}
这样如果你没有充login.jsp登录进来而直接去访问系统的其他页面时,就不能查看你想看的页面,而是会自动跳转到sessionValid.jsp页面去