通过Spring AOP发送数据到HTML模板吗?

问题描述 投票:0回答:1

我想使用Spring AOP封装所有控制器方法以进行错误处理。

但是,如何正确地将catch块中的e.getMessage()发送到error.html中的$ {errorMessage}?

感谢您的回复!


    @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>
spring-mvc thymeleaf spring-aop
1个回答
0
投票

以下方面可以将请求属性设置为显示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;
}

我建议您请探索@ControllerAdvice的可能性

© www.soinside.com 2019 - 2024. All rights reserved.