Springboot 中使用 Filter

文章:
https://github.com/Snailclimb/springboot-guide/blob/master/docs/basis/springboot-filter.md
https://blog.csdn.net/weixin_39933264/article/details/100181291

demo源碼:https://github.com/FDzhang/demo-study/tree/master/demo-springboot/demo-filter

2020-02-19


  • 1 pom.xml 依賴
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  • 2 springboot的啟動類添加注解 @ServletComponentScan
@SpringBootApplication
@ServletComponentScan
public class DemoFilterApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoFilterApplication.class, args);
    }
}
  • 3 簡單使用
/**
 * order(number)  : 過濾器的順序
 * filterName : 過濾器名稱
 * urlPatterns : 需要過濾的路徑
 * initParams : 初始化參數(shù),存于FilterConfig中
 */
@Order(1)
@WebFilter(filterName = "DemoFilter1", urlPatterns = "/*" , initParams = {})
public class DemoFilter1 implements Filter {
    /**
     * filter對象只會創(chuàng)建一次,init方法也只會執(zhí)行一次。
     */
    @Override
    public void init(FilterConfig filterConfig) {
    }
    /**
     * 主要的業(yè)務(wù)代碼編寫方法
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 獲取請求參數(shù)中的cityCode
        String cityCode = request.getParameter("cityCode");

        // 如果 cityCode==001 則通過
        if ("001".equals(cityCode)){
            // 放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            // 返回錯誤信息
            Map<String,Object> map = new HashMap<>(4);
            map.put("code","301");
            map.put("message","cityCode錯誤");

            // 設(shè)置編碼 和 數(shù)據(jù)格式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");

            Gson gson = new Gson();
            response.getWriter().write(gson.toJson(map));
        }
    }
    /**
     * 在銷毀Filter時自動調(diào)用。
     */
    @Override
    public void destroy() {
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容