您好,登錄后才能下訂單哦!
Filter 過濾器是web開發中很重要的一個組件,下面以一個session登陸的例子介紹下spring boot中如何使用Filter
首先要準備一個實現了Filter的接口的類 SessionFilter:
import org.slf4j.LoggerFactory; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by mazhenhua on 2016/12/27. * * 過濾器 */ public class SessionFilter implements Filter { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SessionFilter.class); /** * 封裝,不需要過濾的list列表 */ protected static List<Pattern> patterns = new ArrayList<Pattern>(); @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; logger.info("aaaaaaaaaa"); String url = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length()); if (url.startsWith("/") && url.length() > 1) { url = url.substring(1); } if (isInclude(url)){ chain.doFilter(httpRequest, httpResponse); return; } else { HttpSession session = httpRequest.getSession(); if (session.getAttribute("") != null){ // session存在 chain.doFilter(httpRequest, httpResponse); return; } else { // session不存在 準備跳轉失敗 /* RequestDispatcher dispatcher = request.getRequestDispatcher(path); dispatcher.forward(request, response);*/ chain.doFilter(httpRequest, httpResponse); return; } } } @Override public void destroy() { } /** * 是否需要過濾 * @param url * @return */ private boolean isInclude(String url) { for (Pattern pattern : patterns) { Matcher matcher = pattern.matcher(url); if (matcher.matches()) { return true; } } return false; } }
實際開發中往往有很多請求要直接請求進來,不需要鑒權登陸的,所以代碼中過濾掉這種請求的代碼,裝進list就好了。
/** * 配置過濾器 * @return */ @Bean public FilterRegistrationBean someFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(sessionFilter()); registration.addUrlPatterns("/*"); registration.addInitParameter("paramName", "paramValue"); registration.setName("sessionFilter"); return registration; } /** * 創建一個bean * @return */ @Bean(name = "sessionFilter") public Filter sessionFilter() { return new SessionFilter(); }
經過上面這倆步的配置,過濾器基本上就可以了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。