歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用 Spring 容器管理 Filter

使用 Spring 容器管理 Filter

日期:2017/3/1 10:19:38   编辑:Linux編程

《使用 Spring 容器管理 Servlet》一文介紹了如何使用 Spring 對 Servlet 進行管理,本文是《使用 Spring 容器管理 Servlet》的姊妹篇,本文介紹如何使用 Spring 對 Filter 進行管理。其實具體原理方法和前者大同小異。

如一般的 J2EE 配置一樣,Spring 在 web.xml 中的配置:

  1. <listener>
  2. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  3. </listener>
  4. <context-param>
  5. <param-name>contextConfigLocation</param-name>
  6. <param-value>/WEB-INF/applicationContext*.xml</param-value>
  7. </context-param>

如一般的 J2EE 配置一樣,Spring 在 applicationContext-service.xml 中定義我們的業務邏輯處理類:

  1. <bean id="logService"
  2. class="com.defonds.cds.system.log.impl.LogServiceImpl"
  3. parent="baseService" scope="singleton" init-method="init" destroy-method="destroy">
  4. </bean>

如同一般的 Struts1/2 的 action 一樣在我們的 Filter 中注入 service:

  1. private LogService logService;
  2. public LogService getLogService() {
  3. return logService;
  4. }
  5. public void setLogService(LogService logService) {
  6. this.logService = logService;
  7. }

在 Filter 中如同一般的 Struts1/2 的 action 一樣調用 service:

  1. String ip = logService.getIpAddr(request);

如同一般的 Filter 我們的這個 Filter 需要實現 javax.servlet.Filter 接口:

  1. public class BlockedIpFilter implements Filter {

根據自己的業務需要去實現 init、doFilter 和 destroy 方法:

  1. @Override
  2. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
  3. FilterChain filterChain) throws IOException, ServletException {
  4. if (ifIpBlocked) {
  5. HttpServletRequest request = (HttpServletRequest)servletRequest;
  6. HttpServletResponse response = (HttpServletResponse) servletResponse;
  7. String ip = logService.getIpAddr(request);
  8. if (logService.ifBlocked(ip)) {
  9. response.getWriter().write("error");
  10. response.getWriter().close();
  11. } else {
  12. filterChain.doFilter(request, response);
  13. }
  14. } else {
  15. filterChain.doFilter(servletRequest, servletResponse);
  16. }
  17. }
  18. @Override
  19. public void init(FilterConfig arg0) throws ServletException {
  20. // TODO Auto-generated method stub
  21. }
  22. @Override
  23. public void destroy() {
  24. // TODO Auto-generated method stub
  25. }
Copyright © Linux教程網 All Rights Reserved