有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何对方法执行post请求返回整数

在下面的示例中,我试图了解在下面的代码中,我如何在给定initVar()方法的情况下执行POST请求。 我尝试按如下方式执行post请求:

http://localhost:8080/root/initVar/id/2->error
http://localhost:8080/root/initVar/id?2->error

但当我从方法返回Int数据类型时,它不起作用。 请让我知道如何修复此错误

请注意,此方法返回Int

代码

@RestController
@RequestMapping("root")
class Controller1 {

val sayHiLazy by lazy {
    "hi from get"
}

@GetMapping(value = "/sayHi")
@ResponseBody
fun  sayHi() : String {
    return sayHiLazy
}

@PostMapping("/initVar/id")
@ResponseBody
fun initVar(@PathVariable id : Int) : Int {
    return 11
}
}to use spring annotation with koltin in intellij. i used spring annotation with java projects in intellij. but for koltin, it does not work.

在下面的示例中,HelloController带有红色下划线,我收到以下警告:

    classes annotated with @Configurations cannto be implicily subclassed and must be final

请让我知道怎么去

控制器1

@SpringBootConfiguration
@RequestMapping("/app")
public class HelloController {

@RequestMapping(value = "/hello")
fun SayHello(): String {
    return "success"
}
}

共 (1) 个答案

  1. # 1 楼答案

    1. 如果要使用@PathVariable,必须执行以下操作:
    @RequestMapping(value="/stuff/{id}")
    @ResponseBody
    public String doStuff(@PathVariable("id") int id){
        return "id="+id;
    }
    
    1. 通常情况下,编写POST方法时末尾不带变量。对于这种情况,您应该使用PUT-https://restfulapi.net/rest-put-vs-post/

    2. 我不确定是否可以返回纯整数作为响应,但可以选择将整数包装成字符串-String.valuOf(id);

    问候