spring-mvc - 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>
解决方案
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
推荐阅读
- vue.js - 如何定位编辑按钮?
- c# - ASP.NET MVC 中的 Ajax 重定向
- java - 如何在 Room Android 中使用具有多个实体的单个模型?
- docker - Docker 文件更新量
- flutter - Flutter - 健康包未加载 STEP 数据
- c# - 在 List.ForEach 中声明 Func<> 会导致内存泄漏并增加进程内存吗?
- python - 带有两个 pyc 脚本的 Python ValueError
- spring - 我们如何将 Apple Provider 与 Spring Security oauth2 客户端一起使用
- python - 绘制 MSA 级别人口普查 Coroplethmapbox python
- moodle - 如何在 Moodle 3.8 中包含附加信息课程概览块