[英]Getting error in a Dropwizard resource method
I am trying to study Dropwizard and so, I am trying to build a simple calculator. 我正在尝试学习Dropwizard,因此,我正在尝试构建一个简单的计算器。
This is the relevant code I wrote: 这是我写的相关代码:
In the application class: 在应用程序类中:
@Override
public void run(final CalDropWizServerDemoConfiguration configuration,
final Environment environment) {
final CalDropWizServerDemoResource resource = new CalDropWizServerDemoResource();
environment.jersey().register(resource);
final TemplateHealthCheck healthCheck = new TemplateHealthCheck();
environment.healthChecks().register("Sum", healthCheck);
}
The resource class: 资源类:
@Path("/calculator")
@Produces(MediaType.APPLICATION_JSON)
public class CalDropWizServerDemoResource {
private final AtomicLong counter;
public CalDropWizServerDemoResource(){
this.counter = new AtomicLong();
}
@GET
@Timed
@Path("/sum")
public Sum calcSum(@PathParam("a") int a, @PathParam("b") int b) {
System.out.println(a);
System.out.println(b);
return new Sum(counter.incrementAndGet(), a + b);
}
}
The api (POJO of the json response) class: api(json响应的POJO)类:
public class Sum {
private long id;
private int sum;
public Sum() {
// Jackson deserialization
}
public Sum(long id, int sum) {
this.id = id;
this.sum = sum;
}
@JsonProperty
public long getId() {
return id;
}
@JsonProperty
public int getSum() {
return sum;
}
}
I don't use a configuration yaml so the configuration class is the default one. 我不使用配置yaml,因此配置类是默认类。
My problem is that when I call, for example: 我的问题是当我打电话时,例如:
http://localhost:8080/calculator/sum?a=1&b=5 http:// localhost:8080 / calculator / sum?a = 1&b = 5
I get 0 as the sum. 总和为0。 I debugged and found out that the values of a and b in the calcSum() method are accepted as 0. Why is that?
我进行了调试,发现calcSum()方法中a和b的值被接受为0。为什么?
Thanks!! 谢谢!!
If you are using @PathParams
to input a
and b
, you need to have placeholders for them in your @Path
url. 如果使用
@PathParams
输入a
和b
,则需要在@Path
URL中使用占位符。 It can be like this: 可能是这样的:
@Path("/sum/{a}/{b}")
The label given to each placeholder in @Path
should match the value passed to corresponding @PathParam
declaration. @Path
给每个占位符的标签应与传递给相应@PathParam
声明的值匹配。
Replace @PathParam
with @QueryParam
and it should work fine. 将
@PathParam
替换为@QueryParam
,它应该可以正常工作。
@GET
@Timed
@Path("/sum")
public Sum calcSum(@QueryParam("a") int a, @QueryParam("b") int b) {
System.out.println(a);
System.out.println(b);
return new Sum(counter.incrementAndGet(), a + b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.