2016-06-13 105 views
0

我需要在服務器端調用一堆Spring Controller方法,但是我只需要@RequestMapping值就可以繼續。有沒有辦法做到這一點?從其他方法調用Spring Controller方法,通過RequestMapping

我知道這可以做,因爲它通過MockMvc在測試框架中使用。我想要的確切功能:

String a = mockMvc.perform(get("/foo/bar/{id}", foobarId)).andReturn().getResponse().getContentAsString(); 
String b = mockMvc.perform(get("/foo/car/{id}", foobarId)).andReturn().getResponse().getContentAsString(); 
String totals = a + b; 

坦率地說,我正在考慮使用它,因爲它似乎正是我想要做的事情。使用它會有問題嗎?我只是將WebApplicationContext自動裝入控制器,並且可以工作。對? :)

編輯

重定向是不是我想要的。我不想鏈通話,每次通話也必須能夠通過網絡瀏覽器作爲一個獨立的方法,以及

UPDATE

它發生,我認爲,當春天啓動,它執行組件掃描,查找@Controllers和@RequestMapping,並且必須創建一個映射URL的Map class.method()正確嗎?它不會掃描每個呼叫的所有類。問題是,這張地圖在掃描和加載後會在哪裏,並且只有一個控制器開發人員可以訪問它?

+0

無法使用JavaScript/jQuery的? – sura2k

+0

編號服務器端在這一個任務。 – mmaceachran

+0

然後嘗試RestTemplate https://spring.io/guides/gs/consuming-rest/ – sura2k

回答

0

你想要的是redirect,如:

@RequestMapping(value = "/foo/bar/{foobarId}") 
public String testView (@PathVariable("foobarId") String foobarId) { 
    return "any view"; 
} 

@RequestMapping(value = "test") 
public String test (String msg) { 
    String foobarId = .....; 
    return "redirect:/foo/bar/" + foobarId; 
} 
0

這是一個總的黑客,但完全適用:

@Controller 
@RequestMapping(value = "/TEST") 
public class TestController { 

private MockMvc mockMvc; 
private WebApplicationContext wbctx = null; 
@Autowired 
ServletContext servletContext; 

public void init() { 
    if(wbctx==null) { 
     wbctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); 
     mockMvc = MockMvcBuilders.webAppContextSetup(wbctx).build(); 
    } 
} 

@RequestMapping(value = "/test") 
@ResponseBody 
public String testme() throws Exception { 
    init(); 
    String a = mockMvc.perform(get("/foo/bar/{id}", 1)).andReturn().getResponse().getContentAsString(); 
    String b = mockMvc.perform(get("/foo/car/{id}", 1)).andReturn().getResponse().getContentAsString(); 
    return a+b; 
} 
} 
相關問題