太久没写SpringBoot的代码了,最近一直在刷题和复习基础【IO,集合,反射,MySQL等】。但是,前两天突发奇想,想写点东西,然后就在我今天进行Swagger测试的时候意外发现前端调用的Uri死活传不到后端,一直返回400,于是在我的一通百度后,陷入了沉思……就在即将放弃的时候【主要是( ̄o ̄) . z Z】,我发现了规律,下面就有我来讲解一下我的解决方案吧
一、问题出现原因
首先分析下我的歌曲Uri
https://kg3.qq.com/node/WEaBGH7Vk0/play_v2?s=yw01gByXE9ICzyb7&shareuid=639b9c8221283588&topsource=a0_pn201001004_z11_u1617
我想有经验的人应该一看就能看出问题吧,没错就是有很多的 " / " ,然后我当时定义的后端接收类型是 String
所以个人感觉应该是 " / " 的问题,将请求地址定义到了一个不存在的接口
二、解决方案
将后端接收的参数类型改为Json
三、SpringBoot接收前端参数json格式的五种方式
不啰嗦,直接上代码
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
@RestController
public class HelloController2 {
/*
* 第一种:以RequestParam接收
* http://localhost:8080/test1?id=1
* */
@RequestMapping(value = "/test1",method=RequestMethod.GET)
public void test1(@RequestParam("id") String id){
System.out.println("id:"+id);
}
/*
* 第二种:以实体类接收
* {"username": "zhangsan","id":"2"}
* */
@RequestMapping(value = "/test2",method=RequestMethod.POST)
public void test1(@RequestBody User user) throws Exception{
System.out.println("username:"+user.getUsername());
}
/*
* 第三种:以Map接收
* {"username": "zhangsan","id":"2"}
* */
@RequestMapping(value = "/test3",method=RequestMethod.POST)
public void test3(@RequestBody Map<String, String> map) throws Exception{
System.out.println("username:"+map.get("username"));
}
/*
* 第四种:以List接收
* [{"username": "zhangsan","id":"2"},{"username": "lisi","id":"1"}]
* */
@RequestMapping(value = "/test4",method=RequestMethod.POST)
public void test4(@RequestBody List<User> list) throws Exception{
for(User user:list){
System.out.println("username:"+user.getUsername());
}
}
/*
* 第五种:以JSON对象接收
* {"username": "zhangsan","id":"2","role":{"rolename":"admin"}}
* */
@RequestMapping(value = "/test5",method=RequestMethod.POST)
public void test5(@RequestBody JSONObject json) throws Exception{
System.out.println("username:"+json.getString("username"));
System.out.println("rolename:"+json.getJSONObject("role").getString("rolename"));
}
}
总结
通过这件事,我发现开发经验真的需要平时积累【有事没事上来水一篇贴】,对于基础知识的掌握一定要牢固,总之,多练就对了,要相信1W小时定律!!!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)