Use Spring container in Servlet Filter
Definefilter, ImplementationApplicationContextAwareInterface:
Public class CacheFilter implements Filter, ApplicationContextAware {private static ApplicationContext ctx; // It must be declared as static @ Override public void init (FilterConfig config) throws ServletException {}@ Override public void doFilter (ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {filterChain. doFilter (servletRequest, servletResponse) ;}@ Override public void destroy () {}@ Override public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {CacheFilter. ctx = applicationContext; // Save the spring container to the static variable}
Then, configurefilterTo make it the bean of container management:
Finallyweb.xmlDeclare the filter in:
Cache Filter
com.fh.taolijie.servlet.CacheFilter
Cache Filter
appServlet
Then, we candoFilter()Directly throughApplicationContextRetrieve the required bean:
StringRedisTemplate redis = (StringRedisTemplate)ctx.getBean("redisTemplate");