Spring Boot:RequestMapping

4

我有以下三个REST API方法:

@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?谢谢。

1
仅供参考,这是一个关于Spring MVC的问题。Spring Boot更像是一个包装器-自动配置所有Spring的事情。 - sashok_bg
4个回答

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

2

您应该使用@RequestParam而不是GET方法,并使用POST方法来实现您想要的内容。

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

    return "result";
}

然后你会像这样发布:

输入图像描述

因此,你的字符串数组将包含两个值。

在REST中,路径对应于资源,所以你应该问自己“我正在公开什么资源?”。它可能是类似于/config/frontend的东西,然后你通过请求参数和/或HTTP动词指定选项。


1
你可以通过 request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE) 获取完整路径,然后解析它以获取所有的值。

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

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接