Filter Authentication 登录认证

【编程式配置】可用webxml配置替换
@WebListener
public class FilterListenerConfigurator implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent e) {
ServletContext context = e.getServletContext();
FilterRegistration.Dynamic registration = context.
addFilter("authenticationFilter",new AuthenticationFilter());
registration.setAsyncSupported(true);
registration.addMappingForUrlPatterns(null,false,"/sessions","/tickets");
  }
【Authentication过滤器】
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpSession session = ((HttpServletRequest)req).getSession(false);
//如果session当中不存在username(登录时保存在attribute)
if (session!=null&&session.getAttribute("username")==null){
((HttpServletResponse)resp).sendRedirect("login");
}else{
filterChain.doFilter(req,resp);
}
}


posted @ 2018-03-23 17:21  chenhui7373  阅读(1542)  评论(0编辑  收藏  举报