Web.xml中配置:
<filter-name>sessionFilter</filter-name>
<filter-class>xyt.first.web.filter.SessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
SessionFilter配置:
public class SessionFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
// TODO Auto-generated method stub
// 不过滤的uri
String[] notFilter = new String[] { "first.html", "index.html" };
// 请求的uri
String uri = request.getRequestURI();
System.out.println(uri);
boolean doFilter = true;
for (String s : notFilter) {
if (uri.indexOf(s) != -1) {
// 如果uri中包含不过滤的uri,则不进行过滤
doFilter = false;
break;
}
}
if (doFilter) {
// 执行过滤
// 从session中获取登录者实体
Object obj = request.getSession().getAttribute("loginUser");
if (null == obj) {
System.out.println("loginUser"+" :NULL");
// 如果session中不存在登录者实体,则弹出框提示重新登录
// 设置request和response的字符集,防止乱码
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");//用于response.getWriter()输出的字符流的乱码问题
response.setContentType("text/html;charset=UTF-8");//控制浏览器进行解码
PrintWriter out = response.getWriter();
String loginPage = "user/first.html";
StringBuilder builder = new StringBuilder();
builder.append("<script type=\"text/javascript\">");
builder.append("alert('网页过期,请重新登录!');");
builder.append("window.top.location.href='");
builder.append(loginPage);
builder.append("';");
builder.append("</script>");
out.print(builder.toString());
} else {
// 如果session中存在登录者实体,则继续
System.out.println("loginUser有值:"+obj.toString());
filterChain.doFilter(request, response);
}
} else {
// 如果不执行过滤,则继续
filterChain.doFilter(request, response);
}
}
}
转载于:https://blog.51cto.com/yt0116/1737102