Search code examples
spring-mvcthymeleafspring-aop

Send Data to HTML Template through Spring AOP?


I'd like to wrap all the controller methods using Spring AOP for Error Handling.

But, How to send e.getMessage() in catch block to ${errorMessage} in error.html properly?

Thanks for the response!


    @Pointcut("within(com.test.mvc.controller.*) && @within(org.springframework.stereotype.Controller)")
    public void controllerLayer() {
    }

    @Pointcut("execution(public String *(..))")
    public void publicMethod() {
    }

    @Pointcut("controllerLayer() && publicMethod()")
    public void controllerPublicMethod() {
    }

    @Around("controllerPublicMethod()")
    public String processRequest(ProceedingJoinPoint joinPoint) {

        try {

            return (String) joinPoint.proceed();

        } catch (Throwable e) {

            LOGGER.info("{}", e.getMessage());
            return "error.html";

        }

    }

<body>

        <h1>Something went wrong!</h1>
        <h3 th:text="'Error Message: ' + ${errorMessage}"></h3>

</body>

Solution

  • Following aspect can set the request attribute to display errorMessage.

    @Around("controllerPublicMethod()")
    public Object processRequest(ProceedingJoinPoint joinPoint) {
        Object object=null;
        try {
            object = joinPoint.proceed();
        } catch (Throwable e) {
            RequestContextHolder.getRequestAttributes().setAttribute("errorMessage",e.getMessage(),0); // scope 0 - request , 1 - session
            return "error.html";
        }
        return object;
    }
    

    I recommend you please explore the possibilities of @ControllerAdvice