【问题标题】:Why are both Jersey endpoints being hit?为什么泽西岛的两个端点都被击中?
【发布时间】:2020-01-17 17:06:19
【问题描述】:

当我转到.../bank/1 时,我会看到预期的帐户信息。 很好,很好,很好。

当我转到 .../bank/1/description 时,我看到了描述(good),但我也看到了帐户信息(notgood)。

我习惯了 Spring 的 GetMapping,如果多条路径匹配,事情就会中断——但即便如此,AFAIK,在我的代码中,只有一个 应该匹配吗?

为什么AccountActions 都被触发了?


银行.java

Path("/bank")
public class Bank {

    @Context
    UriInfo uriInfo;

    @Context
    Request request;

    // ... Other irrelevant constructors, methods, and attributes

    @GET
    @Path("{acct}")
    public AccountAction getAccount(@PathParam("acct") String id) {
        LOGGER.log(Level.INFO, "- URL: " + uriInfo.getPath());
        return new AccountAction(uriInfo, request, id, accounts);
    }

    @GET
    @Path("{acct}/description")
    public AccountAction getDescription(@PathParam("acct") String id) {
        LOGGER.log(Level.INFO, "- URL: " + uriInfo.getPath());
        return new AccountAction(uriInfo, request, id, accounts);
    }
}


AccountAction.java

public class AccountAction {

    @Context
    UriInfo uriInfo;

    @Context
    Request request;

    // ... Other irrelevant constructors, methods, and attributes

    public AccountAction(UriInfo uriInfo, Request request, String id, AccountStore accounts) {
        this.uriInfo = uriInfo;
        this.request = request;
        this.id = new Integer(id);
        this.accounts = accounts;
    }

    @GET
    @Path("/{id:\\d+}/description")
    @Produces(MediaType.TEXT_PLAIN)
    public String getDescription() {
        LOGGER.log(Level.INFO, "- URL: " + uriInfo.getPath());
        Account a = accounts.find(id);
        if (a == null) {
            throw new RuntimeException("No such account: " + id);
        }
        return a.getDescription();
    }

    @GET
    @Path("/{id:\\d+$}")
    @Produces(MediaType.APPLICATION_XML)
    public Account getAccount() {
        LOGGER.log(Level.INFO, "- URL: " + uriInfo.getPath());
        Account a = accounts.find(id);
        if (a == null) {
            throw new RuntimeException("No such account: " + id);
        }
        return a;
    }
}


日志输出:

17-Jan-2020 11:54:57.526 INFO [http-nio-8080-exec-1] edu...Bank.getDescription - URL: bank/1/description
17-Jan-2020 11:54:58.139 INFO [http-nio-8080-exec-1] edu...AccountAction.getAccount - URL: bank/1/description
17-Jan-2020 11:54:58.140 INFO [http-nio-8080-exec-1] edu...AccountAction.getDescription - URL: bank/1/description

【问题讨论】:

标签: java jax-rs jersey-2.0


【解决方案1】:

替换此代码

@Path("/{id:\d+$}")

@Path("/{id: [0-9]*}")

【讨论】:

  • 这不起作用,也不能解释为什么两条路径都会被命中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 2018-07-06
  • 1970-01-01
相关资源
最近更新 更多