我正在创建一个执行添加功能的java Web服务。现在,我已经在我的方法中设置了默认值(firstNumber是2,secondNumber是2)所以当我运行应用程序(localhost)时,我得到{"firstNumber":2,"secondNumber":2,"sum":4}
作为输出。是否有可能使用户在firstNumber和secondNumber中输入作为URL的一部分并显示总和?如何将URL设为http://localhost:8080/addition/firstNumber=2&secondNumber=2
,并显示总和。我应该在AdditionController.java中添加什么?
以下是我的代码:
Addition.java
public class Addition {
private int firstNumber, secondNumber, sum;
public Addition(String firstNumber, String secondNumber) {
this.firstNumber = Integer.parseInt(firstNumber.trim());
this.secondNumber = Integer.parseInt(secondNumber.trim());
updateSum();
}
public int getFirstNumber() {
return firstNumber;
}
public void setFirstNumber(int firstNumber) {
this.firstNumber = firstNumber;
updateSum();
}
public int getSecondNumber() {
return secondNumber;
}
public void setSecondNumber(int secondNumber) {
this.secondNumber = secondNumber;
updateSum();
}
public int getSum() {
return sum;
}
public void updateSum() {
this.sum = this.firstNumber + this.secondNumber;
}
@Override
public String toString() {
return String.format("Addition [firstNumber=%d, secondNumber=%d, sum=%d%n", //
firstNumber, secondNumber, sum);
}
}
AdditionController.java
@RestController
public class AdditionController {
private static final String template = " %s";
@RequestMapping("/addition")
@ResponseBody
public Addition addition (
@RequestParam(value="firstNumber", defaultValue="2") String firstNumber,
@RequestParam(value="secondNumber", defaultValue="2") String secondNumber,
@RequestParam(value="sum", defaultValue="2") String sum){
return new Addition(
(String.format(template, firstNumber)), String.format(template, secondNumber));
}
}
有人请指导我应该在哪些地方进行更改。非常感谢你。
答案 0 :(得分:1)
您可以使用pathparam通过url发送int1和int2,并在服务器端提取它。 url: http:localhost:port/appname/path/param1/param2
server end:
@GET
@Path("{param1}/{param2}")
public Response getSum(@PathParam("param1") int A,@PathParam("param2") int B)