从其他方法调用Spring Controller方法,通过RequestMapping
问题描述:
我需要在服务器端调用一堆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()正确吗?它不会扫描每个呼叫的所有类。问题是,这张地图在扫描和加载后会在哪里,并且只有一个控制器开发人员可以访问它?
答
你想要的是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;
}
答
这是一个总的黑客,但完全适用:
@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;
}
}
无法使用JavaScript/jQuery的? – sura2k
编号服务器端在这一个任务。 – mmaceachran
然后尝试RestTemplate https://spring.io/guides/gs/consuming-rest/ – sura2k