2016-12-01 142 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); 
} 

}