0

Do you think it is a good idea to use a servlet Filter to increment number of times a page is visited?

Something like this:

@WebFilter("/posts/*")
public class PostHitCounterFilter implements Filter {

    @Autowired
    private PostService postService; // somehow I autowire this

    @Override
    public void init(FilterConfig filterConfig) {//...}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, filterChain chain) {
        String postUrl = ((HttpServletRequest) request).getRequestURI().substring(7);
        postService.incrementVisits(postUrl);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {//...}
}
Mahozad
  • 18,032
  • 13
  • 118
  • 133
  • 2
    It seems to be a perfectly valid approach. Note that the increment processing : `postService.incrementVisits(postUrl);` should not be interleaved by multiple threads otherwise some increment could be missing. – davidxxx Aug 02 '18 at 20:14
  • 2
    To expand on davidxxx's comment, the counter should probably be an [`AtomicInteger`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicInteger.html) or [`AtomicLong`](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/AtomicLong.html), to prevent multi-threading issues. – Andreas Aug 02 '18 at 20:53
  • For how you can use spring to autowire the service see https://stackoverflow.com/q/6725234/217324 – Nathan Hughes Aug 21 '18 at 22:11
  • Thanks. I've set it up to be autowired in the init method: `SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, filterConfig.getServletContext());` – Mahozad Aug 21 '18 at 22:15
  • Whatever. The way I linked to has a lot less hassle writing a test for it. – Nathan Hughes Aug 21 '18 at 23:57

0 Answers0