繁体   English   中英

如何在 spring 引导中使用 @Pathvariable 注释调用 Post 方法?

[英]How to call Post method with @Pathvariable annotation in spring boot?

我应该如何从浏览器中使用 @PathVariable 调用 Post 方法? 搜索了所有问题,这个问题没有直接的答案。 不喜欢使用其他注解。

@RestController
@RequestMapping("/api")
public class PlugController {

    @PostMapping(value = "/command/{cmd}")
    public String command(@PathVariable(value = "cmd") String command) {
        return command;
    }

}

从浏览器调用如下:

http://localhost:8080/api/command/on

错误:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.


There was an unexpected error (type=Method Not Allowed, status=405).

您可以发布您的***Application代码或任何日志,我使用您的代码并且它有效。

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
@RestController
@RequestMapping("/api")
public class TestController {

    @PostMapping(value = "/command/{cmd}")
    public String command(@PathVariable(value = "cmd") String command) {
        return command;
    }
}

在此处输入图像描述

- -更新 - -

如果您想通过浏览器请求它,请使用@GetMappingPostMapping

如果你想通过浏览器请求 POST,你需要使用 javascript 创建一个表单提交事件,url 如下:

javascript要求让浏览器知道这是 javascript。

javascript:(function(){document.body.innerHTML='<form method="POST" action="http://localhost:8080/api/command/aaa"></form>';document.forms[0].submit()})();

请注意,在javascript:(function()...之间没有空格。

尝试在 postman 中测试此发布请求。 由于一些限制,我们的浏览器不支持发布请求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM