有时候我们要在java项目下写一个过滤器来实现某些功能,但是如果我们想在过滤器中通过某个bean查找数据库数据(filter依赖bean),这就会出问题,因为web.xml中元素加载顺序为conten-param -> listener -> filter -> servlet,在filter加载完成时,项目中的bean并没有装配,所以filter所依赖的bean为null,不能实现该功能。我们可以用DelegatingFilterProxy来实现这个功能!
filter实现bean
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.entity.data.User;
import com.service.UserService;
@Component
public class UserFilter implements Filter {
@Autowired
private UserService userService;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
User user = userService.getUser(1);
/**
* do something
*/
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
web.xml添加下面代码
<filter>
<filter-name>userFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>userFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
以上filter配置,我并没有将UserFilter的bean配置进去,只是有filter-name为userFilter,那是因为DelegatingFilterProxy会自动根据filter-name装配userFilter。DelegatingFilterProxy其实就是一个filter的代理,我们把filter当做一个bean来处理,然后用delegatingFilterProxy代理filter就行了。