Spring MVC REST

本文介绍了代表性状态转移(REST)体系结构样式,它通过HTTP公开Web服务。Spring MVC提供REST支持,包括RequestMapping等注解的使用,还介绍了HTTP请求方法及相关注解,如@GetMapping等。此外,还提及了对响应的控制、创建URI的方法,以及Spring REST客户端和Spring HATEOAS生成链接的API。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代表性状态转移(REST)是一种体系结构样式,它描述了通过HTTP公开Web服务的最佳实践,强调了性能,可伸缩性,简单性,可修改性,可见性,可移植性和可靠性。

REST通过使用名词(而非动词)的URI公开资源,支持一组有限的操作(GET,PUT,POST,DELETE)。 客户端可以请求可以链接到其他资源的特定表示形式(HTML,XML,JSON等),并将超媒体用作应用程序状态引擎(HATEOAS)。 它使用无状态架构,标头和状态代码与客户端进行通信。

Spring MVC提供REST支持。 RequestMapping批注用于映射Web请求。 RequestMethod枚举数是:GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS和TRACE。

@RequestMapping(path="/accounts", method=RequestMethod.GET)

从Spring 4.3开始,您可以使用以下注释来代替RequestMapping:

  • @GetMapping:获取资源
  • @PostMapping:创建新资源
  • @PutMapping:完全更新资源
  • @DeleteMapping:删除现有资源
  • @PatchMapping:部分更新资源

对于HEAD,OPTIONS和TRACE,请使用RequestMethod枚举器。

@GetMapping(value = "/accounts")
    public @ResponseBody List<Account> accountSummary() {
        return accountManager.getAllAccounts();
    }

    @GetMapping(value = "/accounts/{id}")
    public @ResponseBody Account accountDetails(@PathVariable int id) {
        return retrieveAccount(id);
    }

HTTP GET在响应正文中返回数据。 @ResponseBody批注允许我们返回序列化的对象。 如果该类被注释为@RestController,则GET方法上不需要@ResponseBody。

要对响应进行更多控制(例如,设置标题和控件内容),可以使用ResponseEntity:

@GetMapping(value = "/accounts/{id}")
    public ResponseEntity<Account> accountDetails(@PathVariable long id) {
        Account account = accountService.getAccount(id);
        return ResponseEntity
                .ok()
                .header("Last-Modified", account.getLastUpdate())
                .body(account);
    }

在上面的示例中,构建了ResponseEntity,调用ok方法,该方法返回200状态代码(成功)。 请参阅HttpStatus文档。 您也可以在方法上添加@ResponseStatus批注。

与@ResponseBody相似,@ RequestBody批注允许我们根据请求的内容类型自动转换传入的数据。

@PostMapping(value = "/accounts")
    @ResponseStatus(HttpStatus.CREATED)
    public ResponseEntity<Void> createAccount(@RequestBody Account newAccount) {
        Account account = accountManager.save(newAccount);
        URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().path("/{childId}")
                .buildAndExpand(account.getEntityId()).toUri();
        return ResponseEntity.created(location).build();
    }

在前面的示例中,我们正在构建URI。 要创建URI,可以使用ServletUriComponentsBuilder或UriComponentsBuilder(用于硬编码的URL)。

Spring MVC提供了一个称为RestTemplate的Spring REST客户端(Spring Framework 5引入了一个名为WebClient的新HTTP客户端。请参见Reactive Spring Applications )。 RestTemplate提供对RESTful服务的访问,并支持所有HTTP方法。 请参阅RestTemplate文档

  • 删除:删除方法
  • GET:getForObject和getForEntity(用于ResponseEntity)方法
  • HEAD:headForHeaders方法
  • 选项:optionsForAllow方法
  • POST:postForLocation,postForObject和交换(对于RequestEntity)方法
  • PUT:放置方法
@Test
    public void listAccounts() {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/accounts";
        Account[] accounts = restTemplate.getForObject(url, Account[].class);
        assertNotNull(accounts);
    }

最后, Spring HATEOAS提供了一个用于在MVC Controller响应中生成链接的API。 使用Link类和@EnableHypermediaSupport批注。

@Controller
@EnableHypermediaSupport(type = { HypermediaType.HAL })
public class EmployeeController {

    @GetMapping(value = "/{employeeId}")
    public Employee getEmployeeById(@PathVariable long employeeId) {
        Employee employeeById = ControllerLinkBuilder.methodOn(EmployeeController.class).getEmployeeById(employeeId);
        Link selfLink = ControllerLinkBuilder.linkTo(employeeById).withSelfRel();
        Employee employee = employeeService.getEmployee(employeeId);
        employee.add(selfLink);
        return employee;
    }
}

翻译自: https://www.javacodegeeks.com/2020/12/spring-mvc-rest.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值