2017-06-05 41 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>