如何在REST WebService中实现动态URL

时间:2019-02-19 09:58:23

标签: java spring rest web-services spring-mvc

我正在尝试为我的应用程序开发新的Web服务。
为此,我正在使用Spring REST-webservice
在控制器端,我试图根据传递的代理获取记录列表。现在需求可以传递代理,也可以为空。如果代理为空,则应选择所有记录,否则仅选择那些记录待提取。

根据以下搜索结果之一,尝试使用以下代码来实现动态性。

@RequestMapping(value = "/staging/{agentCode: [^/]*?}" , method = 
RequestMethod.GET)

这是我现有的代码:

@Controller
@RequestMapping(value="/batches")   
public class BatchController {

    @SuppressWarnings({ "rawtypes" })
    @RequestMapping(value="/staging/{agentCode}", method = 
 RequestMethod.GET)         
    @ResponseBody
    public ResponseEntity IntmBatch(@PathVariable("agentCode") String 
   agentCode)       
   {
    //code here 
   }

案例1 :当我使用。,

之类的网址时
        www.example.com/myapplication/batches/staging/1234

它工作正常,并且获取了所需的结果。

案例2 :但是,如果我没有传递任何参数,则

    www.example.com/myapplication/batches/staging/

在中,我没有传递任何参数。它说我没有找到映射。

能否让我知道如何在REST GET请求方法调用中实现此动态URL。

提前谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用@Pathvariable来代替URL中的可选值,而不必使用@RequestParam


所以您的URL会像这样。


案例1 www.example.com/myapplication/batches/staging?agentCode=1234
案例2 www.example.com/myapplication/batches/staging

希望它可以解决您的问题。

 @SuppressWarnings({ "rawtypes" })
 @RequestMapping(value="/staging", method = RequestMethod.GET)         
 @ResponseBody
 public ResponseEntity IntmBatch(@RequestParam(name="agentCode",required=false) String   agentCode)       
   {
    //code here 
   }

答案 1 :(得分:1)

使用@RequestMapping(value =“ / staging”,method = RequestMethod.GET)在控制器中创建另一个方法,如下所示。

@RequestMapping(value = "/staging", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity returnAll() {
    System.out.println("returning  all ");
    // code here
return null;

}