三、Spring Boot构建RESTful API
2017-04-11 22:04
441 查看
定义实体类
package com.lf.entity; /** * Created by LF on 2017/4/11. */ public class User { private Long id; private String name; private Integer age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
RestfulController
package com.lf.web; import com.lf.entity.User; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * Created by LF on 2017/4/11. */ @RestController public class RestfulController { @RequestMapping(value = "/user/{code}", method = RequestMethod.GET) public User getUser(@PathVariable String code) { //根据code查询 return new User(); } @RequestMapping(value = "/user", method = RequestMethod.POST) public void createUser(User user) { //数据库添加 } @RequestMapping(value = "/user/{code}", method = RequestMethod.PUT) public void updateUser(@PathVariable String code, User user) { //根据code更新用户 } @RequestMapping(value = "/user/{code}", method = RequestMethod.DELETE) public void deletUser(@PathVariable String code) { //根据code删除一个用户 } }
package com.lf; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
@RestController
Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代.至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注
相关文章推荐
- Spring Boot构建RESTful API与单元测试
- Spring Boot构建RESTful API与单元测试
- Spring Boot - 构建RESTful API与单元测试
- Spring Boot中使用Swagger2构建RESTful API文档
- Spring Boot构建RESTful API与单元测试
- Spring Boot(4)— Spring Boot构建RESTful API与单元测试
- Spring Boot构建RESTful API与单元测试
- Spring Boot中使用Swagger2构建RESTful API文档
- Spring Boot中使用Swagger2构建API文档
- javascript +.net 构建restful API 应用
- Spring Boot系列之三 RESTful风格API
- Spring Boot 构建一个较为复杂的RESTful API以及单元测试
- SwaggerUI+SpringMVC-构建RestFul API的可视化界面
- Spring Cloud Spring Boot mybatis分布式微服务云架构(五)构建RESTful API
- 使用Swagger2构建RESTful API文档遇到的坑
- 使用C#开发HTTP服务器系列之构建RESTful API
- 使用Go构建RESTful的JSON API
- 用 Flask 来写个轻博客 (32) — 使用 Flask-RESTful 来构建 RESTful API 之一
- SwaggerUI+SpringMVC——构建RestFulAPI的可视化界面
- Spring Boot构建RESTful API与单元测试