public
Last active

Example Filter that binds spring-managed beans into the request

  • Download Gist
SpringMappingFilter.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
 
public class SpringMappingFilter implements Filter {
private ServletContext context;
 
public void destroy() { }
 
public void init(FilterConfig filterConfig) {
this.context = filterConfig.getServletContext();
}
 
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter)
throws IOException, ServletException {
// the Spring Context would have been configured by the SpringContextListener
 
ApplicationContext springContext = this.context.getAttribute(XmlWebApplicationContext.DEFAULT_CONFIG_LOCATION);
request.setAttribute("myBean", springContext.getBean("myBean");
 
filterChain.doFilter(request, response);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.