单个过滤器
如果只是定义一个过滤器,直接通过@Configuration注解即可。
package Net.XiangCaoWuYu.Configurations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
/**
* ClassName: CustomFilter <br/>
* Description: <br/>
* date: 2019/7/25 22:04<br/>
*
* @author lisen01<br />
* @since JDK 1.8
*/
@WebFilter(filterName = "CustomFilter", urlPatterns = "{/*}")
public class CustomFilter implements Filter {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* Called by the web container to indicate to a filter that it is being
* placed into service. The servlet container calls the init method exactly
* once after instantiating the filter. The init method must complete
* successfully before the filter is asked to do any filtering work.
* <p>
* The web container cannot place the filter into service if the init method
* either:
* <ul>
* <li>Throws a ServletException</li>
* <li>Does not return within a time period defined by the web
* container</li>
* </ul>
*
* @param filterConfig The configuration information associated with the
* filter instance being initialised
* @throws ServletException if the initialisation fails
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.info("初始化过滤器CustomFilter");
}
/**
* The <code>doFilter</code> method of the Filter is called by the container
* each time a request/response pair is passed through the chain due to a
* client request for a resource at the end of the chain. The FilterChain
* passed in to this method allows the Filter to pass on the request and
* response to the next entity in the chain.
* <p>
* A typical implementation of this method would follow the following
* pattern:- <br>
* 1. Examine the request<br>
* 2. Optionally wrap the request object with a custom implementation to
* filter content or headers for input filtering <br>
* 3. Optionally wrap the response object with a custom implementation to
* filter content or headers for output filtering <br>
* 4. a) <strong>Either</strong> invoke the next entity in the chain using
* the FilterChain object (<code>chain.doFilter()</code>), <br>
* 4. b) <strong>or</strong> not pass on the request/response pair to the
* next entity in the filter chain to block the request processing<br>
* 5. Directly set headers on the response after invocation of the next
* entity in the filter chain.
*
* @param request The request to process
* @param response The response associated with the request
* @param chain Provides access to the next filter in the chain for this
* filter to pass the request and response to for further
* processing
* @throws IOException if an I/O error occurs during this filter's
* processing of the request
* @throws ServletException if the processing fails for any other reason
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
logger.info("过滤器CustomFilter开始工作,并转入下一个过滤");
chain.doFilter(request, response);
logger.info("CustomFilter继续过滤");
}
/**
* Called by the web container to indicate to a filter that it is being
* taken out of service. This method is only called once all threads within
* the filter's doFilter method have exited or after a timeout period has
* passed. After the web container calls this method, it will not call the
* doFilter method again on this instance of the filter. <br>
* <br>
* <p>
* This method gives the filter an opportunity to clean up any resources
* that are being held (for example, memory, file handles, threads) and make
* sure that any persistent state is synchronized with the filter's current
* state in memory.
*/
@Override
public void destroy() {
logger.info("过滤器CustomFilter销毁");
}
}
多个过滤器
如果定义多个过滤器,需要通过FilterRegistrationBean
提供setOrder
方法,可以为filter设置排序值,让spring在注册web filter之前排序后再依次注册。启动类中利用@bean
注册FilterRegistrationBean
*温馨提示
过滤器定义与上面类似,去掉@Configuration
注解即可,这里不再赘述,然后修改启动类,增加以下代码
/*
* Copyright (C) 2019 木子网https://www.xiangcaowuyu.net
* 项目名称:Net.XiangCaoWuYu.Idea
* 文件名称:App.java
* Date:19-7-19 上午1:21
* Author:lisen@lisen.org
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package Net.XiangCaoWuYu;
import Net.XiangCaoWuYu.Configurations.CustomFilter;
import Net.XiangCaoWuYu.Configurations.CustomFilterOther;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@SpringBootApplication
//SpringBoot 默认从App类往下面的包扫描
//所以如果控制器、实体等类与App不在一个包,同时不在下面的包时,必须手动指定包
//@ComponentScan(basePackages = {"Net.XiangCaoWuYu.Controllers", "Net.XiangCaoWuYu.Services"})
@EnableJpaRepositories(basePackages = {"Net.XiangCaoWuYu.Repositories", "Net.XiangCaoWuYu.Services"})
//@EntityScan(basePackages = {"Net/XiangCaoWuYu/Pojos"})
public class App {
private static final Logger logger = LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
// System.setProperty("log.root","DEBUG,info,error");
//
// System.setProperty("log.base","D:\\log4j\\base");
SpringApplication.run(App.class, args);
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new CustomFilter());
filterRegistrationBean.setOrder(10);
return filterRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBeanOther() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new CustomFilterOther());
filterRegistrationBean.setOrder(20);
return filterRegistrationBean;
}
}
这个看起来不错,谢谢。