有的时候根据我们业务的需要,我们需要在web项目中定义一个自己的filter,并想在这个filter中使用@Autowired注入bean供我们使用。如果直接使用的话是不行的,需要我们在xml文件中进行配置。下面就根据我的一个项目写一个示例:
步骤一、定义一个ClientSessionFilter,在这个Filter中注入我们想要的bean
public class ClientSessionFilter implements Filter {private static Logger log = Logger.getLogger(ClientSessionFilter.class);@Autowiredprivate RequestData requestData; //我们想要注入的bean@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {ObjectMapper mapper = new ObjectMapper();HttpServletRequest httpServletReq = (HttpServletRequest) request;String session = httpServletReq.getHeader("S");ClientSession cs;if(StringUtils.isNotBlank(session)) {try {cs = mapper.readValue(session, ClientSession.class);} catch (Exception e) {log.error("Session序列化错误" + e);throw new BusinessException(401, "Session序列化错误");}if(log.isDebugEnabled()) {log.debug(cs);}requestData.setClientSession(cs);}chain.doFilter(request, response);}@Overridepublic void destroy() {} }
步骤二、在spring的配置文件application.xml中配置我们想要的bean和自定义的filter
<bean id="requestData" scope="request" class="cn.ucmed.common.cache.RequestData"><aop:scoped-proxy/> //这个标签可以参考上一遍博客
</bean><bean id="clientSessionFilter" class="cn.ucmed.baseline.d2d.filter.ClientSessionFilter" />
步骤三、在web.xml中配置fileter
<filter><filter-name>filterProxy</filter-name><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class><async-supported>true</async-supported><init-param><param-name>targetBeanName</param-name><param-value>clientSessionFilter</param-value></init-param><init-param><param-name>targetFilterLifecycle</param-name><param-value>true</param-value></init-param> </filter> <filter-mapping><filter-name>filterProxy</filter-name><url-pattern>/registeryuyue/*</url-pattern> </filter-mapping>