【问题标题】:Call Spring Controller method from other method, via the RequestMapping通过 RequestMapping 从其他方法调用 Spring Controller 方法
【发布时间】:2016-06-13 21:56:41
【问题描述】:

我需要在服务器端调用一堆 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 自动连接到控制器中,这样就可以了。正确的? :)

编辑

重定向不是我想要的。我不想链接调用,每个调用也必须能够被网络浏览器作为独立方法使用

更新

我突然想到,当 spring 启动时,它会进行组件扫描,查找 @Controllers 和 @RequestMapping 并且必须制作某种 Map 来映射 URL class.method() 对吗?它不会扫描每个调用的所有类。问题是,这张地图一旦被扫描和加载到哪里去了,一个控制器的开发者可以访问它吗?

【问题讨论】:

标签: java spring spring-mvc


【解决方案1】:

你想要的是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;
}

【讨论】:

    【解决方案2】:

    这是一个完全的黑客,但完全有效:

    @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;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-01-07
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      相关资源
      最近更新 更多