Close

Spring MVC - @ControllerAdvice Examples

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.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class MyControllerAdvice {

@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleException (Exception exception, Model model) {
model.addAttribute("exception", exception);
return "exception-page";
}
}
package com.logicbig.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExampleController1 {

@RequestMapping("/test1")
public String handleRequest1 () throws Exception {
String msg = String.format("Test exception from class: %s",
this.getClass().getSimpleName());

throw new Exception(msg);
}
}
package com.logicbig.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ExampleController2 {

@RequestMapping("/test2")
public String handleRequest2 () throws Exception {
String msg = String.format("Test exception from class: %s",
this.getClass().getSimpleName());

throw new RuntimeException(msg);
}
}
Original Post




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




See Also