为每个控制器内的每个动作设置模型属性 [英] Setting model attributes for every action within each controller
问题描述
我想在我的模型中为Spring Boot应用程序中许多控制器中的每个@RequestMapping
设置三个通用属性.我已经读过关于@ModelAttribute
的内容,但是需要将其放置在每个Controller中.我的应用程序中有20多个控制器,每个控制器都有10个以上的@RequestMapping
.
I would like to set three common attributes on my model for each @RequestMapping
within the many controllers in a Spring Boot application. I have read about @ModelAttribute
but it needs to be placed within each Controller. I have more than 20 controllers in my application and each having more than 10 @RequestMapping
.
有没有办法在一个地方设置这种模型属性,并在应用程序启动时对其进行初始化?
Is there a way to set such model attributes in one place which gets initialized at the start of the application?
推荐答案
如果您想在Spring Boot启动时执行一些代码,请考虑以下问题:
If you want to execute some code on Spring Boot startup, consider this:
但是我想您确实想要与控制器相关的行为,我建议您使用全局拦截器.
使用全局拦截器,您可以干扰Spring中的请求-响应生命周期.
With global interceptor, you can interfere with the request-response lifecycle in Spring.
它使您可以在3个不同的点上向请求-响应生命周期添加功能:
It lets you add functionality to request-response life cycle in 3 different points:
- 在控制器处理请求之前
- 处理程序完成其功能后
- 视图将要呈现给最终用户时.
只需创建一个从HandlerInterceptorAdapter
扩展的类,并使用所需的功能覆盖三个方法之一即可.
Just create a class which extends from HandlerInterceptorAdapter
and override one of three methods, with your desired functionality.
例如:
public class MyInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
request.setAttribute("myFirstAttribute", "MyFirstValueHere");
return super.preHandle(request, response, handler);
}
}
以下是有关如何使用Spring Boot进行操作的示例:
Here's an example on how to do it with Spring Boot:
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(...)
...
registry.addInterceptor(myInterceptor);
}
}
这篇关于为每个控制器内的每个动作设置模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!