import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse) servletResponse;
HttpServletRequest req = (HttpServletRequest) servletRequest;
User user = (User) req.getSession().getAttribute("user");
if (user != null){
filterChain.doFilter(req,resp);
return;
}
resp.sendRedirect("重定向到的地址");
}
@Override
public void destroy() {
}
}
web.xml
<filter>
<filter-name>Login</filter-name>
<filter-class>com.xiaoyou.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>