2014-11-24 69 views
1

我有一個基於Spring MVC的應用程序,我想添加一個功能,其中一些控制器將根據參數的值返回相同的視圖。Spring:配置xml使控制器根據參數返回視圖

@RequestMapping("/someView") 
public String returnView(Model model, HttpServletRequest request, String param){ 
    if(param.equals("condition")){ 
     return "commonView"; 
    } 

    // do stuff 

    return "methodSpecificView"; 
} 

有沒有辦法可以在xml中配置第一個if條件?由於類似的功能需要在許多控制器中實現,並且我不想編寫樣板代碼,所以xml配置可以使事情變得更簡單。

此外,如果第一個是可能的,是否可以擴展以從請求映射方法簽名中消除參數param並將其放入xml中?

回答

0

你應該考慮通過AOP - Around建議如下所示。

@Around("@annotation(RequestMapping)") // modify the condition to include/exclude specific methods 
public Object aroundAdvice(ProceedingJoinPoint joinpoint) throws Throwable { 

    Object args[] = joinpoint.getArgs(); 
    String param = args[2]; // change the index as per convenience 
    if(param.equals("condition")){ 
     return "commonView"; 
    } else { 
     return joinpoint.proceed(); // this will execute the annotated method 
    } 
} 
1

您可以使用@RequestMapping:

@RequestMapping(value = {"/someView", "/anotherView", ...}, params = "name=condition") 
public String returnCommonView(){ 
    return "commonView"; 
} 
1

在Spring 3.2這是基於註解下面的代碼片段會給你一個想法你的問題:

@RequestMapping("formSubmit.htm") 
public String onformSubmit(@ModelAttribute("TestBean") TestBean testBean,BindingResult result, ModelMap model, HttpServletRequest request) { 
    String _result = null; 
    if (!result.hasErrors()) { 
      _result = performAction(request, dataStoreBean);//Method to perform action based on parameters recieved 
     } 
     if(testBean.getCondition()){ 
     _result = "commonView"; 
     }else{ 
     _result = "methodSpecificView"; 
     }  
     return _result; 

    } 
TestBean//Class to hold all the required setters and getters 

說明: 由於來自視圖的請求來自此方法,如果從視圖獲取條件,那麼ModelAttribute引用將保存視圖中的所有值,而不是從模型屬性直接獲取它並返回相應的視圖。 如果您的條件是在應用某些邏輯之後獲得的,則您可以在testBean中設置條件並再次獲取它以返回相應的視圖。

相關問題