SpringMVCRestfulapi接口实现的代码-创新互联

【前言】

天心ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

面向资源的 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项目

这里的搭建步骤不再赘述,如有需要参考:https://www.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\"}";
 }
}


网页名称:SpringMVCRestfulapi接口实现的代码-创新互联
链接地址:http://myzitong.com/article/ccpego.html