发表于: 2017-05-21 17:19:11

2 1423


今日计划

理解rest接口,springmvc设计完成rest接口并用PostMan测试

今日完成

昨天刚刚接触Rest说实话一脸懵逼。今天搜了些博客和资料,大概理解了一些。

今天尝试用Spring MVC 实现CRUD Restful WebService,然后通过PostMan测试这些服务

REST表示Representational State Transfer(表示性状态转换)

它时可以用来设计web services的框架,可以被不同的客户端调用。

核心思想是:使用简单的HTTP协议来实现调用,而不是CORBA,RPC或者SOAP等负责的机制


在Rest基础设计中,资源使用以下动词进行操作。

创建资源:使用HTTP POST

获取资源:使用HTTP GET

更新资源:使用HTTP PUT

删除资源 :使用HTTP DELETE


根据接口定义格式示例,定义Rest接口

我们的REST API

GET方式请求/api/student/返回学生列表

GET方式请求/api/student/1返回id为1的用户

POST方式请求/api/student/通过student对象的JSON参数创建新的student对象

PUT方式请求/api/student/3更新id为3的发送json格式的用户对象

DELETE方式请求/api/user/4删除ID为4的student对象

DELETE方式请求/api/student/删除所有student


package com.websystique.springmvc.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.MediaType;

import org.springframework.http.ResponseEntity;

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

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

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

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

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

import org.springframework.web.util.UriComponentsBuilder;

import com.jnshu.springmvc.model.Student;

import com.jnshu.springmvc.service.StudentService;

@RestController

public class RestController {

@Autowired

StudentService studentService;  //Service which will do all data retrieval/manipulation work

//-------------------Retrieve All Users--------------------------------------------------------

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

public ResponseEntity<List<User>> listAllStudents() {

List<Student> students = studentService.findAllStudents();

if(students.isEmpty()){

return new ResponseEntity<List<Student>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND

}

return new ResponseEntity<List<Student>>(students, HttpStatus.OK);

}

//-------------------Retrieve Single Student--------------------------------------------------------

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

public ResponseEntity<Student> getStudent(@PathVariable("id") long id) {

System.out.println("Fetching Student with id " + id);

Student student = studentService.findById(id);

if (student == null) {

System.out.println("User with id " + id + " not found");

return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);

}

return new ResponseEntity<Student>(user, HttpStatus.OK);

}

//-------------------Create a Student--------------------------------------------------------

@RequestMapping(value = "/student/", method = RequestMethod.POST)

public ResponseEntity<Void> createStudent(@RequestBody Student student, UriComponentsBuilder ucBuilder) {

System.out.println("Creating Student " + student.getName());

if (studentService.isStudentExist(student)) {

System.out.println("A Student with name " + student.getName() + " already exist");

return new ResponseEntity<Void>(HttpStatus.CONFLICT);

}

userService.saveStudent(student);

HttpHeaders headers = new HttpHeaders();

headers.setLocation(ucBuilder.path("/student/{id}").buildAndExpand(student.getId()).toUri());

return new ResponseEntity<Void>(headers, HttpStatus.CREATED);

}

//------------------- Update a Student --------------------------------------------------------

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

public ResponseEntity<Student> updateStudent(@PathVariable("id") long id, @RequestBody Student student) {

System.out.println("Updating Student " + id);

User currentStudent = userService.findById(id);

if (currentStudent==null) {

System.out.println("Student with id " + id + " not found");

return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);

}

currentStudent.setName(student.getName());

currentStudent.setQq(user.getQq());

currentStudent.setProfession(user.getProfession());

userService.updateStudent(currentStudent);

return new ResponseEntity<Student>(currentStudent, HttpStatus.OK);

}

//------------------- Delete a Student --------------------------------------------------------

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

public ResponseEntity<Student> deleteStudent(@PathVariable("id") long id) {

System.out.println("Fetching & Deleting Student with id " + id);

Student student = studentService.findById(id);

if (student == null) {

System.out.println("Unable to delete. Student with id " + id + " not found");

return new ResponseEntity<Student>(HttpStatus.NOT_FOUND);

}

studentService.deleteStudentById(id);

return new ResponseEntity<Student>(HttpStatus.NO_CONTENT);

}

//------------------- Delete All Student --------------------------------------------------------

@RequestMapping(value = "/student/", method = RequestMethod.DELETE)

public ResponseEntity<Student> deleteAllStudents() {

System.out.println("Deleting All Students");

studentService.deleteAllStudents();

return new ResponseEntity<Student>(HttpStatus.NO_CONTENT);

}

}


@RestController :首先我们使用的是Spring 4的新注解 @RestController注解. 

此注解避免了每个方法都要加上@ResponseBody注解。也就是说@RestController 自己戴上了 @ResponseBody注解,看以看作是@Controller 和 @ResponseBody的结合体。

@RequestBody : 如果方法参数被 @RequestBody注解,Spring将绑定HTTP请求体到那个参数上。如果那样做,Spring将根据请求中的ACCEPT或者 Content-Type header(私下)使用 HTTP Message converters 来将http请求体转化为domain对象。

@ResponseBody : 如果方法加上了@ResponseBody注解,Spring返回值到响应体。如果这样做的话,Spring将根据请求中的 Content-Type header(私下)使用 HTTP Message converters 来将domain对象转换为响应体。

ResponseEntity 是一个真实数据.它代表了整个 HTTP 响应(response). 它的好处是你可以控制任何对象放到它内部。

你可以指定状态码、头信息和响应体。它包含你想要构建HTTP Response 的信息。

@PathVariable 此注解意味着一个方法参数应该绑定到一个url模板变量[在'{}'里的一个]中

一般来说你,要实现REST API in Spring 4 需要了解@RestController , @RequestBody, ResponseEntity 和 @PathVariable 这些注解 .另外, spring 也提供了一些支持类帮助你实现一些可定制化的东西

MediaType : 带着 @RequestMapping 注解,通过特殊的控制器方法你可以额外指定,MediaType来生产或者消耗。


打包成war,传到tomcat上

下载并安装POSTMAN,测试接口

打开POSTMAN 工具中,选择请求类型[GET这个用例],指定操作URI。访问:

http://localhost:8080/Spring4MVCCRUDRestService/user/

点击发送,将收到所有用户的列表。


Jetty还没来得及弄。


困难

收获

springmvc完成REST接口设计

PostMan测试接口


明日计划

JsonTagLib

Jetty


返回列表 返回列表
评论

    分享到