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接口写法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Java Collections.shuffle()方法案例详解
这篇文章主要介绍了Java Collections.shuffle()方法案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下2021-08-08
SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法
在开发Spring Boot RESTful API时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON解析错误(如400 Bad Request)是常见的开发问题之一,本文将通过一个实际案例,详细分析如何排查和解决JSON解析错误,并总结最佳实践,需要的朋友可以参考下2025-06-06
Spring Boot中RabbitMQ自动配置的介绍、原理和使用方法
本文介绍了Spring Boot中RabbitMQ自动配置的介绍、原理和使用方法,通过本文的介绍,我们希望读者能够更好地理解Spring Boot中RabbitMQ的使用方法,并在项目中更加灵活地应用,感兴趣的朋友跟随小编一起看看吧2023-07-07


最新评论