2017-06-05 43 views
0

内的每一个动作,我想对在春季启动应用程序的多个控制器中的每个@RequestMapping设置我的模型三种常见的属性。我已阅读约@ModelAttribute,但它需要放在每个控制器。我在我的申请20多个控制器和每个具有超过10个@RequestMapping设置模型属性为每个控制器

有没有一种方法来设置这样的模式,即得到在应用程序开始时初始化一个地方的属性?

+3

介绍常见的BaseController类,并将'@ ModelAttribute'在班上,让所有的控制器延长BaseController – StanislavL

+1

这就是有'@ ControllerAdvice'注释的类可以为你做。或者使用'HandlerInterceptor'在每个请求上添加公共数据。 –

回答

0

如果你想执行的春天引导启动一些代码,可以这样考虑:

Spring boot startup listener

但我想,你真的想控制相关行为我会建议使用全球拦截

随着全球拦截器,您可以在Spring中的请求 - 响应生命周期的干扰。

它可以让你添加功能的请求 - 响应生命周期在3个不同点:

  1. 控制器处理的请求
  2. 之前之后的处理程序完成时的观点是有关执行其功能
  3. 呈现给最终用户。

只需创建一个类,该类延伸自HandlerInterceptorAdapter并覆盖三种方法之一,并具有所需的功能。

例如:

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引导做一个例子:

@Configuration 
public class WebMvcConfig extends WebMvcConfigurerAdapter { 

    @Autowired 
    MyInterceptor myInterceptor; 

    @Override 
    public void addInterceptors(InterceptorRegistry registry) { 
    registry.addInterceptor(...) 
    ... 
    registry.addInterceptor(myInterceptor); 
    } 
} 
+0

在这种情况下,属性在请求上而不是模型上设置。我对吗? – Reema

+0

我相信最终它也会在模型上设置。使用请求参数 –

+0

那么不需要另外一个步骤在模型上设置它们吗? – Reema

0

我提供由用SpringMVC另一种方法,使用HandlerInterceptor,当你实现它它提供了3种方法,每种方法都包含HttpServletRequest,可以使用request.setAttribute("xx","yy")设置属性,以下是代码:

public class RequestInterceptor implements HandlerInterceptor { 

    public void afterCompletion(HttpServletRequest arg0, 
      HttpServletResponse arg1, Object arg2, Exception arg3) 
      throws Exception { 

    } 

    public void postHandle(HttpServletRequest request, HttpServletResponse arg1, 
      Object arg2, ModelAndView arg3) throws Exception { 
     //you can set attributes here like request.setAttribute("xx","yy") 
    } 

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
      Object arg2) throws Exception { 
     //you can set attributes here like request.setAttribute("xx","yy") 
     return false; 
    } 

} 

然后,你需要自定义拦截器添加到您的Spring MVC应用程序如下图所示:

<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> 
    <property name="interceptors"> 
    <list> 
     <!--class of your custom interceptor--> 
     <bean class="com.xx.RequestInterceptor"/> 
    </list> 
    </property> 
</bean>