最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Spring Boot中添加支持POST方法

方法 crifan 1281浏览 0评论
折腾:
【未解决】VSCode中用Java的Spring Boot搭建智能电力系统后端框架
期间,继续去添加post
代码中加上:
import org.springframework.web.bind.annotation.PostMapping;
spring boot PostMapping
Spring @PostMapping Example – @GetMapping Example
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;


    @PostMapping(path = "/greeting", consumes = "application/json", produces = "application/json")
    public void addMember(@RequestBody Member member) {
            //code
    }
此处会报错:
不知道,此处的RequestBody后面,应该怎么写
@RequestMapping和@GetMapping @PostMapping 区别_蜗牛学习笔记-CSDN博客
PostMapping (Spring Framework 5.2.3.RELEASE API)
Spring MVC的@PostMapping注解_天高任鸟飞-CSDN博客
好像是:
可以用
RequestParam(“xxx”) String xxx
去获取输入的参数
而前面的RequestBody,估计是body中的参数,然后自动通过json解析成class对象了?
Spring @PostMapping tutorial – using @PostMapping to map POST requests onto handlers
其用
HttpServletRequest request
再用
request.getParameter(“content”);
去获取值
spring boot postmapping requestbody
@PostMapping and @RequestBody Example in Spring MVC – Apps Developer Blog
    @PostMapping(path = "/greeting", consumes = "application/json", produces = "application/json")
    public void addMember(@RequestBody Greeting greeting) {
            System.out.printf("post greeting=%s\n", greeting);
    }
结果去测试,好像是可以的:
2020-01-31 15:50:52.475  INFO 24675 --- [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 52 ms
post greeting=com.crifan.xxx.Greeting@51c015c6
不过想要去返回一个json
    @PostMapping(path = "/greeting", consumes = "application/json", produces = "application/json")
    public void addMember(@RequestBody Greeting greeting) {
            System.out.printf("post greeting=%s\n", greeting);
            System.out.printf("id=%s\n", greeting.getId());
            System.out.printf("content=%s\n", greeting.getContent());


            return {
                "id": greeting.getId(),
                "content": greeting.getContent()
            };
    }
结果语法报错:
Syntax error, insert ";" to complete ReturnStatement Java(1610612976)
spring boot Syntax error insert ; to complete ReturnStatement
不过其实此处想要返回一个json对象
@PostMapping and @RequestBody Example in Spring MVC – Apps Developer Blog
好像是:
新建new一个对象,设置对应的值,即可
改为:
    @PostMapping(path = "/greeting", consumes = "application/json", produces = "application/json")
    public Greeting newGreeting(@RequestBody String content) {
        return new Greeting(counter.incrementAndGet(), content);
    }
}
效果:
不是我们要的。
我们希望传入content
Spring’s RequestBody and ResponseBody Annotations | Baeldung
spring boot get和post请求,以及requestbody为json串时候的处理
感觉是用RequestParam
    @PostMapping(path = "/greeting", consumes = "application/json", produces = "application/json")
    // public void addMember(@RequestBody Greeting greeting) {
    public Greeting addMember(@RequestParam(value = "content", required = true) String content) {
        System.out.printf("post greeting: content=%s\n", content);
        return new Greeting(counter.incrementAndGet(), content);
    }
结果报错:
{
    "timestamp": "2020-01-31T08:08:42.483+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "Required String parameter 'content' is not present",
    "trace": "org.springframework.web.bind.MissingServletRequestParameterException: Required String parameter 'content' is not present\n\tat org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:204)\n\tat org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114)\n\tat .....
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\n\tat java.lang.Thread.run(Thread.java:745)\n",
    "path": "/greeting"
}
很明显,指的是少了content参数
所以要去搞清楚
post时,如何获取json对象中的值
spring boot post json
java – Trying to use Spring Boot REST to Read JSON String from POST – Stack Overflow
java – Parsing JSON in Spring MVC using Jackson JSON – Stack Overflow
Springboot之接收json字符串的两种方式-yellowcong_yelllowcong的专栏-CSDN博客
springboot接收JSON参数 – SegmentFault 思否
java – How to POST a JSON payload to a @RequestParam in Spring MVC – Stack Overflow
rest – how can i pass Json data in a Post method using spring boot? I want to pass few variables and use that variables in a different java class – Stack Overflow
spring post requestbody
Spring之RequestBody的使用姿势小结 – 掘金
Spring’s RequestBody and ResponseBody Annotations | Baeldung
Can spring map POST parameters by a way other than @RequestBody – Stack Overflow
SpringBoot中@RequestParam @RequestBody @PathVariable的作用 – 简书
@PostMapping and @RequestBody Example in Spring MVC – Apps Developer Blog
MediaType APPLICATION_JSON_VALUE
Spring MVC之@RequestMapping 详解 – 火腿骑士 – 博客园
MediaType (Spring Framework 5.2.3.RELEASE API)
MediaType.APPLICATION_JSON_VALUE
好像属于:org.springframework.http
以及:
“static MediaType
APPLICATION_JSON
Public constant media type for application/json.
static MediaType
APPLICATION_JSON_UTF8
Deprecated.
as of 5.2 in favor of APPLICATION_JSON since major browsers like Chrome now comply with the specification and interpret correctly UTF-8 special characters without requiring a charset=UTF-8 parameter.
static String
APPLICATION_JSON_UTF8_VALUE
Deprecated.
as of 5.2 in favor of APPLICATION_JSON_VALUE since major browsers like Chrome now comply with the specification and interpret correctly UTF-8 special characters without requiring a charset=UTF-8 parameter.
static String
APPLICATION_JSON_VALUE
A String equivalent of APPLICATION_JSON.”
即 APPLICATION_JSON_VALUE 等价于APPLICATION_JSON
但是去试了试:
MediaType.APPLICATION_JSON
结果报错:
然后去看了class定义发现:
即:
APPLICATION_JSON根本没没有值,没法用。
所以最后还是用
MediaType.APPLICATION_JSON_VALUE
MediaType APPLICATION_JSON_VALUE
java – difference between ‘APPLICATION_JSON’ and ‘APPLICATION_JSON_VALUE’ – Stack Overflow
MediaType.APPLICATION_JSON的值的类型是:MediaType
MediaType.APPLICATION_JSON_VALUE的值的类型是:String,即=”application/json”
所以不是一个东西。
【总结】
此处,如果不是想要post新创建一个对象的话,比如只是获取其中一个字段,则可以用Map
代码:
    @PostMapping(path = "/greeting", consumes = "application/json", produces = "application/json")
    public Greeting addMember(@RequestBody Map<String, Object> payload) {
        System.out.printf("post greeting: payload=%s\n", payload);
        String content = (String) payload.get("content");
        return new Greeting(counter.incrementAndGet(), content);
    }
测试效果:
终端输出效果:
注:
另外把代码
// @PostMapping(path = "/greeting", consumes = "application/json", produces = "application/json")
优化成:
import org.springframework.http.MediaType;

@PostMapping(path = "/greeting", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
即可。

转载请注明:在路上 » 【已解决】Spring Boot中添加支持POST方法

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
91 queries in 0.182 seconds, using 23.40MB memory