通过 Spring AOP 将数据发送到 HTML 模板?
Send Data to HTML Template through Spring AOP?
我想使用 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>
以下方面可以设置request属性显示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
的可能性
我想使用 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>
以下方面可以设置request属性显示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