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.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Component @WebFilter(urlPatterns = { "/*" }, filterName = "tokenAuthorFilter") public class TokenAuthorFilter implements Filter { private static Logger logger = LoggerFactory.getLogger(TokenAuthorFilter.class); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String token = req.getHeader("token"); logger.info("token:{}", token); if (null == token || token.isEmpty()) { throw new ServletException("用戶受權認證沒有經過!客戶端請求參數中無token信息"); } else { if (this.volidateToken(token)) { //經過校驗 logger.info("token過濾ok!"); chain.doFilter(request, response); } else { throw new ServletException("用戶受權認證沒有經過!客戶端請求參數token信息無效"); } } } public boolean volidateToken(String token) { //對token內包含的用戶名以及密碼進行校驗 if(true) { return true; } return false; } @Override public void destroy() {} @Override public void init(FilterConfig filterConfig) throws ServletException {} }