Spring MVC
@ControllerAdvice is a specialization of @Component. It is typically used to define @ExceptionHandler, @InitBinder, and @ModelAttribute methods that apply to all @RequestMapping methods defined across multiple @Controllers classes.
 package com.logicbig.example;
import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ModelAttribute; import javax.servlet.http.HttpServletRequest; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.LongAdder;
@ControllerAdvice public class PageCountersControllerAdvice { //uri to counter map private ConcurrentHashMap<String, LongAdder> counterMap = new ConcurrentHashMap<>();
@ModelAttribute public void handleRequest(HttpServletRequest request, Model model) { String requestURI = request.getRequestURI(); //counter increment for each access to a particular uri counterMap.computeIfAbsent(requestURI, key -> new LongAdder()) .increment(); //populating counter in the model model.addAttribute("counter", counterMap.get(requestURI).sum()); //populating request URI in the model model.addAttribute("uri", requestURI); } }
Original Post
|
|