블로그 이미지

Rurony's Training Gym

Rurony의 트레이닝 도장! by Rurony


Spring Bean을 Servlet Filter에서 사용

Spring Bean을 Injection하여 Servlet Filter를 활용한 사용자 접근 통계 예제.
 
1. Service Class
Filter Class에 Injection할 Service Bean.
public class LogServiceImpl implements LogService {
@Autowired
private LogDao logDao;
public void insertLog(LogBean log) {
logDao.insertLog(log);
}
[...]
}

2. Filter Class 

component-scan으로 자동 등록된 Bean은 Injection이 안되는 것 같음? 아래 Spring Bean 설정에서 Bean을 선언 하여 사용.
public class AccessLogFilter implements Filter {
@Autowired
private LogService logService;
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest sReq, ServletResponse sRes, FilterChain chain) throws IOException, ServletException {
[...]
chain.doFilter(sReq, sRes);
logService.insertLog(log);
}

public void destroy() {
}
}

3. Spring Bean 설정
<!-- Service Bean -->
<bean id="logService" class="com.rurony.format.access.service.LogServiceImpl" />
 <!-- Filter Bean -->
<bean id="accessLogFilter" class="com.rurony.format.filter.AccessLogFilter" />

4. web.xml 설정
스프링에서 제공하는 DelegatingFilterProxy를 사용하여 설정, 위 Spring Bean 설정에서 선언된 Filter Bean의 id와 filter-name을 같게 설정.
<filter>
<filter-name>accessLogFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
  
<filter-mapping>
<filter-name>accessLogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Top