1.定义struts2拦截器(网上例子很多)
代码如下:
package rt.intercepter; import java.util.Map; import javax.servlet.http.HttpServletRequest; import rt.pojo.UserInfo; import rt.util.Struts2Utils; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; public class LoginValidate extends AbstractInterceptor { /** * */ private static final long serialVersionUID = 1L; @Override public String intercept(ActionInvocation invocation) throws Exception { System.out.println("interceptor intercept"); Map<String, Object> session = invocation.getInvocationContext().getSession(); UserInfo userInfo = (UserInfo) session.get("userInfo"); HttpServletRequest request = Struts2Utils.getRequest(); if ("XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With")) || request.getParameter("ajax") != null) { if(null == Struts2Utils.getSession() || null == userInfo){ Struts2Utils.getResponse().getWriter().write("{"statusCode":"301", "message":"会话已过期!请重新登录!"}"); return null; } } return invocation.invoke(); } }
2、配置拦截器
<!-- 用于CRUD Action的parent package --> <package name="crud-default" extends="convention-default"> <!-- 基于paramsPrepareParamsStack, 增加store interceptor保证actionMessage在redirect后不会丢失 --> <interceptors> <span style="color: #ff0000;"><interceptor name="sessionout" class="rt.intercepter.LoginValidate" /></span> <interceptor-stack name="crudStack"> <interceptor-ref name="timer"/> <interceptor-ref name="logger"/> <interceptor-ref name="store"> <param name="operationMode">AUTOMATIC</param> </interceptor-ref> <interceptor-ref name="paramsPrepareParamsStack" /> <span style="color: #ff0000;"><interceptor-ref name="sessionout"/></span> </interceptor-stack> </interceptors> <default-interceptor-ref name="crudStack" /> </package>
3.测试:
登录后,等一分钟,点击出现登录超时,并跳转到了登录页面。
如果想session超时之后设置页面不跳转,而是弹出框登录,请在dwz的初始化页面内修改:
<script type="text/javascript"> $(function(){ DWZ.init("dwz.frag.xml", { loginUrl:"login_dialog.html", loginTitle:"登录", // 弹出登录对话框 //loginUrl:"login.jsp", // 跳到登录页面 statusCode:{ok:200, error:300, timeout:301}, //【可选】 keys: {statusCode:"statusCode", message:"message"}, //【可选】 pageInfo:{pageNum:"pageNum", numPerPage:"numPerPage", orderField:"orderField", orderDirection:"orderDirection"}, //【可选】 debug:false, // 调试模式 【true|false】 callback:function(){ initEnv(); $("#themeList").theme({themeBase:"themes"}); setTimeout(function() {$("#sidebar .toggleCollapse div").trigger("click");}, 10); } }); }); </script>
这样就完成了,希望能给大家带来帮助.