Java for Web学习笔记(四三):Filter(5)用于认证

时间:2021-07-18 18:28:00

一个简单的认证Filter

简单的Filter,登录界面为/login,如果登录成功,session中带有username。

public class AuthenticationFilter implements Filter {

public void init(FilterConfig fConfig) throws ServletException { }

public void destroy() {}

public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException{
HttpSession session = ((HttpServletRequest)request).getSession(false);
if(session == null || session.getAttribute("username") == null){
System.out.println("redirect to /login ... ");
((HttpServletResponse)response).sendRedirect("/login");
}else{
System.out.println("username = " + session.getAttribute("username"));
chain.doFilter(request, response);
}
}
}

定义Filter

采用代码设置方式,对/sessions,/tickets的url要求经过认证的filter。

public class Configurator implements ServletContextListener {

public void contextDestroyed(ServletContextEvent sce) {
}

public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
FilterRegistration.Dynamic registration = context.addFilter("AuthenticationFilter", AuthenticationFilter.class);
//registration.setAsyncSupported(true);
registration.addMappingForUrlPatterns(null, false, "/sessions","/tickets");
}
}

相关链接: 我的Professional Java for Web Applications相关文章