public class LoginCheckFilter implements Filter {
private FilterConfig config=null;
private String webroot=null;
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request=(HttpServletRequest)req;
HttpServletResponse response=(HttpServletResponse)resp;
HttpSession session=request.getSession(false); //取得当前会话的session,没有session也不创建session,同request.getSession()一样
String url=request.getRequestURI(); //获取当前输入的 /项目/当前访问的路径 与我们定义的路径是否相同
if(url!=nullurl.equals(webroot+"/login.jsp")url.equals(webroot+"/LoginServlet")){
chain.doFilter(req,resp);
}else{
if(session==null){
response.sendRedirect(webroot+"/login.jsp");
}else{
String user2=(String)session.getAttribute("user1");
if(user2==null){
response.sendRedirect(webroot+"/login.jsp");
}else{
chain.doFilter(request, response);
}
}
}
}
@Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
this.config=config;
ServletContext ctx=config.getServletContext(); //获取url /项目名
webroot=ctx.getContextPath(); //项目名
}
}