最近在做关于filter登录验证的功能,防止未登录的用户直接通过地址进入系统
LoginFilter类:继承Filter接口
package com.ss.filter;
import java.io.IOException;
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;
import javax.servlet.http.HttpSession;
public class LoginFilter implements Filter{
@Override
public void init(FilterConfig filterconfig) throws ServletException { }
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest servletRequest = (HttpServletRequest)request;
HttpServletResponse servletResponse = (HttpServletResponse)response;
HttpSession session = servletRequest.getSession();
String path = servletRequest.getRequestURI(); //获取用户请求的uri
if(session.getAttribute("admin")==null && path.indexOf("/html/login")==-1) {
servletResponse.sendRedirect(servletRequest.getContextPath()+"/html/login.html");
return;
}
else {
filterChain.doFilter(request, response);
}
}
@Override
public void destroy() { }
}
在web.xml中配置session及filter:
<!-- 设置session过期时间 min -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<!-- session过滤器配置相关 -->
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>com.ss.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>