SpringMVC Restful api接口实现的代码

网友投稿 264 2023-04-01


SpringMVC Restful api接口实现的代码

【前言】

面向资源的 Restful 风格的 api 接口本着简洁,资源,便于扩展,便于理解等等各项优势,在如今的系统服务中越来越受欢迎。

.net平台有WebAPi项目是专门用来实现Restful api的,其良好的系统封装,简洁优雅的代码实现,深受.net平台开发人员所青睐,在后台服务api接口中,已经逐步取代了辉煌一时MVC Controller,更准确地说,合适的项目使用更加合适的工具,开发效率将会更加高效。

python平台有tornado框架,也是原生支持了Restful api,在使用上有了很大的便利。

java平台的SpringMVC主键在Web开发中取代了Struts2而占据了更加有力的地位,我们今天着重讲解如何在Java SpringMVC项目中实现Restful api。

【实现思路】

Restful api的实现脱离不了路由,这里我们的Restful api路由由spring mvc 的 controller来实现。

【开发及部署环境】

开发环境:Windows 7 64 英文版

Intellij IDEA 2017.2

部署环境:JDK 1.8.0

Tomcat 8.5.5

测试环境:chrome

fiddler

【实现过程】

1、搭建spring mvc maven项目

这里的搭建步骤不再赘述,如有需要参考://jb51.net/article/117670.htm

2、新建控制器 StudentController

为了体现Restful api 我们采用注解,RequestMapping("/api/Student")

具体的代码如下:

package Controllers;

import org.springframework.web.bind.annotation.*;

@RestController

@RequestMapping("/api/Student")

public class StudentController {

@RequestMapping(method = RequestMethod.GET)

public String Get() {

return "{\"id\":\"1\",\"name\":\"1111111111\"}";

}

@RequestMapping(method = RequestMethod.POST)

public String Post() {

return "{\"id\":\"2\",\"name\":\"2222222222\"}";

}

@RequestMapping(method = RequestMethod.PUT)

public String Put() {

return "{\"id\":\"3\",\"name\":\"3333333333\"}";

}

@RequestMapping(method = RequestMethod.DELETE)

public String DELETE() {

return "{\"id\":\"4\",\"name\":\"4444444444\"}";

}

@RequestMapping(value = "/{id}",method = RequestMethod.GET)

public String Get(@PathVariable("id") Integer id) {

return "{\"id\":\""+id+"\",\"name\":\"get path variable id\"}";

}

}

这里有Get,Post,Put,Delete分别对应 查询,添加,修改,删除四种对资源的操作,即通常所说的CRUD。

spring mvc可实现restful的方式有@Controller和@RestController两种方式,两种方式的区别如下:

@Controller的方式实现如果要返回json,xml等文本,需要额外添加@ResponseBody注解,例如:

@ResponseBody //用于返回json数据或者text格式文本

@RequestMapping(value = "/TestJson", method = RequestMethod.GET)

public String TestJson() {

return "{\"id\":\"1001\",\"name\":\"zhangsan\"}";

}rLmiDegcL

@RestController方式不需要写@ResponseBody,但是不能返回模型绑定数据和jsp视图,只能返回json,xml文本,仅仅是为了更加方便返回json资源而已。

上述的Rest方法中多写了个Get方法:

@RequestMapping(value = "/{id}",method = RequestMethod.GET)

public String Get(@PathVariable("id") Integer id) {

return "{\"id\":\""+id+"\",\"name\":\"get path variable id\"}";

}

该方法可以直接在url拼接一个参数,更加方便对资源的定向访问,例如查一个student list 可以默认空参数,而查询对应的某一个student详情信息,可以id=studentId 定向查询单条,使得我们对资源的访问更加快捷方便。

【系统测试】

运行系统,使用fiddler调用restful api接口:

1.Get方式

2.Post方式

3.Put方式

4.Delete方式

5.Get/id方式

至此,可见我们的spring mvc Restful api接口已经全部通过测试!


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:api接口管理平台有哪些(api接口应用)
下一篇:Java设计模式之建造者模式实例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~