发表于: 2017-05-13 23:25:20

3 1112


Task2的第四天


在Spring中实现REST

在《Spring实战(第四版)》中,作者推荐使用消息转换器(message converter)来实现REST的资源表述。它一种更直接的方式,能够 将控制器产生的数据转换为服务于客户端的表述形式。

一般我习惯将JSON作为数据的表述方式,JSON主要用到了MappingJacksonHttpMessageConverterMappingJackson2HttpMessageConverter,它们分别对应了Jackson JSONJackson2 JSON

注意:HTTP信息转换器,除了个别几个外,常用的都是自动注册的,也就意味着你不需要在Spring配置文件中显式配置。但是,你应该将项目用到的转换器的库添加到类路径下。否则,系统会提示你:某某类未找到。

今日完成

添加依赖

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
<dependency>
 <groupId>com.fasterxml.jackson.jaxrs</groupId>
 <artifactId>jackson-jaxrs-json-provider</artifactId>
 <version>2.8.8</version>
</dependency>

添加错误信息模型:

package com.semonx.jnshu.web;

public class Error {
   private int code;
   private String message;

   public Error(int code, String message) {
       this.code = code;
       this.message = message;
   }

   public int getCode() {
       return code;
   }

   public String getMessage() {
       return message;
   }
}

添加自定义异常:

未找到异常:

package com.semonx.jnshu.web.exception;

public class StudentNotFoundException extends RuntimeException {
   private long id;

   public StudentNotFoundException(long id) {
       this.id = id;
   }

   public long getId() {
       return id;
   }
}

非法参数异常:

package com.semonx.jnshu.web.exception;

public class InvalidParameterException extends RuntimeException {

}

PUT和POST的控制器:

@RequestMapping(value = "/{id}", method = PUT, consumes = "application/json")
public Student updateStudent(@PathVariable long id, @RequestBody Student student) {
   Student s = service.findStudentById(id);
   if (s == null) {
       throw new StudentNotFoundException(id);
   }
   student.setId(id);
   service.updateStudent(student);
   return student;
}

@RequestMapping(value = "", method = POST, consumes = "application/json")
public ResponseEntity<Student> createStudent(@RequestBody Student student, UriComponentsBuilder ucb) {
   try {
       service.addStudent(student);
   } catch (DataIntegrityViolationException e) {
       throw new InvalidParameterException();
   }

   HttpHeaders headers = new HttpHeaders();
   URI locationUri = ucb.path("/student/").path(String.valueOf(student.getId())).build().toUri();
   headers.setLocation(locationUri);

   ResponseEntity<Student> responseEntity = new ResponseEntity<Student>(student, headers, HttpStatus.CREATED);
   return responseEntity;
}

异常处理控制器:

@ExceptionHandler(StudentNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public Error studentNotFound(StudentNotFoundException exception) {
   long id = exception.getId();
   return new Error(4, "未找到编号 [" + id + "] 的学员。");
}

@ExceptionHandler(InvalidParameterException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Error invalidParameter(InvalidParameterException exception) {
   return new Error(4, "提交的参数有误。");
}

接口使用PostMan测试完成。



返回列表 返回列表
评论

    分享到