2016-12-01 221 views
4

我有以下三種REST API方法:春天開機:RequestMapping

@RequestMapping(value = "/{name1}", method = RequestMethod.GET) 
    public Object retrieve(@PathVariable String name1) throws UnsupportedEncodingException { 
     return configService.getConfig("frontend", name1); 
    } 

@RequestMapping(value = "/{name1}/{name2}", method = RequestMethod.GET) 
public Object retrieve(@PathVariable String name1, @PathVariable String name2) throws UnsupportedEncodingException { 
    return configService.getConfig("frontend", name1, name2); 
} 

@RequestMapping(value = "/{name1}/{name2}/{name3}", method = RequestMethod.GET) 
public Object retrieve(@PathVariable String name1, @PathVariable String name2, @PathVariable String name3) { 
    return configService.getConfig("frontend", name1, name2,name3); 
} 

getConfig方法被配置爲接受多個參數,如:

public Object getConfig(String... names) { 

我的問題是:是否有可能實現上述RequestMapping只使用一個方法/ RequestMapping?

謝謝。

+0

只是備案,這是一個Spring MVC的問題。春季啓動更多的是一個包裝 - 對所有春天的東西autoconfig –

回答

3

簡單的方法指定選項

您可以使用/**在映射抓住任何URL,然後提取映射路徑中的所有參數。 Spring有一個常量,它允許你從HTTP請求中獲取路徑。您只需刪除映射中不必要的部分,然後拆分其餘部分以獲取參數列表。

import org.springframework.web.servlet.HandlerMapping; 

@RestController 
@RequestMapping("/somePath") 
public class SomeController { 

    @RequestMapping(value = "/**", method = RequestMethod.GET) 
    public Object retrieve(HttpServletRequest request) { 
     String path = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString(); 
     String[] names = path.substring("/somePath/".length()).split("/"); 
     return configService.getConfig("frontend", names); 
    } 

} 

更好的方法

然而,路徑變量應而用於您的應用程序特定的資源,而不是作爲一個參數給定的資源。在這種情況下,建議堅持簡單的請求參數。

http://yourapp.com/somePath?name=value1&name=value2 

你映射處理程序將看起來更簡單:

@RequestMapping(method = RequestMethod.GET) 
public Object retrieve(@RequestParam("name") String[] names) { 
    return configService.getConfig("frontend", names); 
} 
1

您可以使用request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)檢索完整路徑,然後解析它以獲取所有值。

2

你應該使用@RequestParam來代替方法POST來實現你想要的。

@RequestMapping(name = "/hi", method = RequestMethod.POST) 
@ResponseBody 
public String test(@RequestParam("test") String[] test){ 

    return "result"; 
} 

然後你發佈這樣的:

enter image description here

所以你的字符串數組將包含兩個值

此外,在REST的路徑對應的資源,所以你應該問你自己「我暴露的資源是什麼?」。它可能會像/配置/前端,然後你通過請求參數和/或HTTP動詞

1

這應該工作:

@SpringBootApplication 
@Controller 
public class DemoApplication { 


public static void main(String[] args) { 
    SpringApplication.run(DemoApplication.class, args); 
} 

@RequestMapping(value ={"/{name1}","/{name1}/{name2}","/{name1}/{name2}/{name3}"}) 
public @ResponseBody String testMethod(
     @PathVariable Map<String,String> pathvariables) 
{ 
    return test(pathvariables.values().toArray(new String[0])); 
} 

private String test (String... args) { 
    return Arrays.toString(args); 
} 

}