0070 过滤器调用Spring的bean操作数据库
假设有这样的需求:将用户每次请求的ip、时间、请求、user-agent存入数据库,很明显可以用过滤器实现,在过滤器中获取到这些数据调用mybatis的mapper存入数据库,但问题来了:mybatis的映射接口规则自动生成的Dao实现类存在于Spring容器中,在filter中如何才能注入或者调用呢?
首先是web.xml配置
<filter>
<!-- 注意下面这个过滤器名称要跟下面的spring-context.xml的相同 -->
<filter-name>myRequestLogFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>myRequestLogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
写filter
package net.sonngdemo.wms.util;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.*;
import java.io.IOException;
/**
* Created by Administrator on 2017/7/3.
*/
public class ReqeustFilter implements Filter {
@Autowired
private RequestFilterInSpring requestFilterInSpring; /*注入下面的Spring容器中的bean,实现了具体的过滤器方法*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
requestFilterInSpring.filter(request,response); //具体的过滤规则写在下面一个类中
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
配置Spring-context.xml
<bean name="myRequestLogFilter" class="net.sonngdemo.wms.util.ReqeustFilter" ></bean>
<!-- 注意这个bean的name要跟上面的web.xml中的名称相同 -->
写一个Spring Bean,具体实现过滤器方法
package net.sonngdemo.wms.util;
import net.sonngdemo.wms.dao.RequestLogMapper;
import net.sonngdemo.wms.domain.RequestLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
/**
* Created by Administrator on 2017/7/3.
*/
@Component("requestFilterInSpring") /*注意名称跟上面过滤器中注入的名称相同*/
public class RequestFilterInSpring {
@Autowired
private RequestLogMapper requestLogMapper; /*注入mapper实现类*/
public void filter(ServletRequest request,ServletResponse response){ /*具体实现过滤器方法*/
HttpServletRequest httpRequest=(HttpServletRequest)request;
String uri=httpRequest.getRequestURI();
String regex = "/wms/(css|errorPage|fonts|js|media)/.*";
if (!uri.matches(regex)) {
RequestLog requestLog=new RequestLog();
requestLog.setIp(request.getRemoteHost());
requestLog.setDate(new Date());
requestLog.setRequest(uri);
requestLog.setUserAgent(httpRequest.getHeader("user-agent"));
requestLogMapper.insertLog(requestLog);
}
}
}
其他mapper略
总结:
- web.xml中配置一个过滤器代理
- 写一个过滤器实现Filter接口,通过调用Spring容器中的bean来实现过滤方法
- 在Spring配置文件中,创建该过滤器的bean对象,注意该该bean的名称要跟web.xml中的名称相同
- 写一个bean,具体实现过滤方法,用@component注解