编程语言
首页 > 编程语言> > java-Spring Rest Controller,重写方法的论点上的路径变量

java-Spring Rest Controller,重写方法的论点上的路径变量

作者:互联网

我有一个用@RestController注释的控制器,它实现了一个接口:

 public interface ContratEndpoint {

      String ROOT = "/api/contrats";

      String GET_CONTRAT = "";

      String GET_CONTRAT_PER_PK = "/{idContrat}";

      @RequestMapping(value = GET_CONTRAT)
      Contrat getContrat(@RequestParam(value = "contratId")Long contratId);


      @RequestMapping(value = GET_CONTRAT_PER_ID)
      ExtContrat getContratById(@PathVariable("idContrat") Long idContrat);
}

控制器:

@RestController
@RequestMapping(value = ContratEndpoint.ROOT)
public class ContratController implements ContratEndpoint {

    //Injecting Services....

    @Resource
    private Mapper mapper;


    @Override
    public Contrat getContrat(Long contratId) {
    return mapper.map(contratService.get(contratId),Contrat.class);
    }

    @Override
    public ExtContrat getContratById(@PathVariable("idContrat") Long idContrat){
        Preconditions.checkArgument(idContrat !=null);
        return mapper.map(contratService.get(idContrat),ExtContrat.class);
    }

上面的代码工作正常.

.但是对于第一个继承的方法,我不必使用@RequestParam注释参数,并且效果很好.

至于我最初尝试的第二种方法:

 @Override
        public ExtContrat getContratById(Long idContrat){
            Preconditions.checkArgument(idContrat !=null);
            return mapper.map(contratService.get(idContrat),ExtContrat.class);
        }

.我期望像第一个方法一样的行为,但是我错了,由于在ligne Preconditions.checkArgument(idContrat!= null)中的检查,代码最终引发了IllegalArgumentException.

我的问题是我错过了@PathVariable的具体问题?
还是我的方法有问题?

谢谢.

解决方法:

Request参数和path变量之间有区别,请参见下面的文章,您可以使用uri确认异常的原因:

@PathVariable is to obtain some placeholder from the uri (Spring call it an URI Template) — see Spring Reference Chapter 16.3.2.2 URI Template Patterns
@RequestParam is to obtain an parameter — see Spring Reference Chapter 16.3.3.3 Binding request parameters to method parameters with @RequestParam

假定此地址为http://localhost:8080/SomeApp/user/1234/invoices?date=12-05-2013(今天获取用户1234的发票)

@RequestMapping(value="/user/{userId}/invoices", method = RequestMethod.GET)
public List<Invoice> listUsersInvoices(
            @PathVariable("userId") int user,
            @RequestParam(value = "date", required = false) Date dateOrNull) {
  ...
}

标签:path-variables,rest,spring-data,spring,java
来源: https://codeday.me/bug/20191027/1946415.html