springboot注解及GET、POST接口写法
更新时间:2024年04月02日 11:41:30 作者:牛右刀薛面
springboot提供了@Contrller和@RestController注解,@Controller返回页面和数据而@RestController返回数据,本文重点介绍springboot注解及GET、POST接口写法,感兴趣的朋友一起看看吧
一、注解
springboot提供了@Contrller和@RestController。
@Controller:返回页面和数据
@RestController:返回数据
@RestMapping注解:主要做路径映射url
value:请求URL的路径。
method:HTTP请求方法。
@RestMapping(value="user", method= RequestMethod.GET)
1.1 GET
无参数
@RequestMapping (value="/hello", method= RequestMethod.GET) public String hello(String name){ return "123"+name; }
参数传递
@RequestMapping (value="/hello", method= RequestMethod.GET) public String hello(String name){ return "123"+name; }
参数映射
@RequestParam注解代表参数映射,将传入进来的nickname映射到name
@RequestMapping (value="/hello2", method= RequestMethod.GET) public String hello2(@RequestParam(value ="nickname",required = false) String name){ return "123"+name; }
1.2 POST
无参数
@RequestMapping(value = "/post1", method = RequestMethod.POST) public String post1(){ return "hello post"; }
带参数
@RequestMapping(value = "/post2", method = RequestMethod.POST) public String post2(String username, String password){ return username+"-"+password; }
Bean封装
@RequestMapping(value = "/post3",method = RequestMethod.POST) public String post3(User user){ System.out.println(user); return "post"; }
json
要在参数前面加一个注解@RequestBody,传入进来的参数名和类的私有变量要保持一致
@RequestMapping(value = "/post34",method = RequestMethod.POST) public String post4(@RequestBody User user){ System.out.println(user); return "post"; }
1.3错误
- 404 :路劲不对
- 405:方法不被允许
到此这篇关于springboot注解及GET、POST接口写法的文章就介绍到这了,更多相关springboot get post接口写法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
-
如何解决Spring in action @valid验证不生效的问题
这篇文章主要介绍了如何解决Spring in action @valid验证不生效的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06 -
springMvc注解之@ResponseBody和@RequestBody详解
本篇文章主要介绍了springMvc注解之@ResponseBody和@RequestBody详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-05-05
最新评论