web.xml配置过滤器
<!-- sessionfilter -->
<filter>
<filter-name>timoutFilter</filter-name>
<filter-class>com.ssm.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>timoutFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<!--以上截止sessionfilter -->
建filter类
package com.ssm.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SessionFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) arg0;
HttpServletResponse httpResponse = (HttpServletResponse) arg1;
String loginUrl = httpRequest.getContextPath() + "/index";
String url = httpRequest.getRequestURI();
if (!url.contains("index") && httpRequest.getSession(false) == null) {//index是我的登录页的路径
String str = "<script language='javascript'>alert('会话过期,请重新登录');"
+ "window.top.location.href='"
+ loginUrl
+ "';</script>";
httpResponse.setContentType("text/html;charset=UTF-8");// 解决中文乱码
PrintWriter writer = httpResponse.getWriter();
writer.write(str);
writer.flush();
return;
}
chain.doFilter(httpRequest, httpResponse);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
如果是ajax(经常用到)
$.ajax({
url: "${basePath}/ssm/DeleteWorkLog",
type: "POST",
dataType: "text",
data: {'logid':$("#NewWorkLogID").val()},
success: function (jsonResult) {
if(jsonResult=="fail"){
layer.msg('删除失败', {icon: 2});
}
else if(jsonResult=="success"){
layer.msg('删除成功', {icon: 1});
RefreshWorkLogList();
NewWorkLog();
}
else{
document.write(jsonResult);//当session过期时,data即为filter中返回的请求
}
},
error: function (x, e) {
alert('NG');
}