代码改变世界

Spring Boot入门(四):开发Web Api接口常用注解总结

2019-04-24 15:21 by 申城异乡人, ... 阅读, ... 评论, 收藏, 编辑

本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正!

在程序员的日常工作中,Web开发应该是占比很重的一部分,至少我工作以来,开发的系统基本都是Web端访问的系统,Web开发在这几年也是经历了很快的发展,前端也显得越来越重要,现在很多大一点的公司都实行前后端分离,让后端和前端只专注于自己的事,所谓术业有专攻,我个人也非常建议前后端分离。

既然前后端分离了,那么后端肯定需要提供Web Api接口给到前端,并返回前端需要的数据。

在Spring Boot中,开发Web Api接口主要使用以下几个注解:

  • @Controller
  • @ResponseBody
  • @RestController
  • @RequestMapping
  • @PathVariable

其实,这些注解在Spring MVC里都有了,所以Spring Boot里的用法也和Spring MVC里基本一样。

在Spring Boot之所以能使用,是因为在spring-boot-starter-web 这个starter pom中,已经引用了spring-web和spring-webmvc。

接下来,我们通过具体例子来讲解下各个注解的使用方法。

1.@Controller

新建控制器HelloController,添加@Controller注解,添加1个方法sayHello,添加@RequestMapping注解,代码如下:

package com.zwwhnly.springbootdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello() {
        return "hello";
    }
}

运行项目,在浏览器输入http://localhost:8080/hello访问,发现报如下错误:

报错的原因是未找到对应的模板,那么如何解决呢?

我们先讲解下第一种解决方法,添加下thymeleaf模板,首先修改pom文件,添加如下配置:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

如果没有设置自动导入maven包的话,IDEA右下角会提示你导入,点击“Import Changes”。

然后在resources/templates目录下,新建hello.html文件(内容先随便写),再次运行项目,访问http://localhost:8080/hello,发现访问正常:

2.@ResponseBody

还有一种更简单的方法是在控制器上添加@ResponseBody注解:

package com.zwwhnly.springbootdemo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello() {
        return "hello";
    }
}

此时的运行结果(直接返回字符串):

hello

3.@RestController

@RestController是Spring4.0推出的组合注解,相当于@Controller+@ResponseBody,我们看下它的源码,也能看出:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    @AliasFor(
        annotation = Controller.class
    )
    String value() default "";
}

此时我们就可以将代码简化为:

@RestController
public class HelloController {
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello() {
        return "hello";
    }
}

4.@RequestMapping

@RequestMapping注解主要用来配置url映射,既可以添加到控制器上,也可以添加到控制器下的方法上,添加到方法上是对添加到控制器上的补充,举例说明:

新建图书类Book:

package com.zwwhnly.springbootdemo.model;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Book {
    private Integer bookId;
    private String bookName;
    private String bookAuthor;
    private Date purchaseDate;

    public Book(Integer bookId, String bookName, String bookAuthor, String purchaseDate) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        this.bookId = bookId;
        this.bookName = bookName;
        this.bookAuthor = bookAuthor;
        this.purchaseDate = simpleDateFormat.parse(purchaseDate);
    }

    public Integer getBookId() {
        return bookId;
    }

    public void setBookId(Integer bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getBookAuthor() {
        return bookAuthor;
    }

    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }

    public Date getPurchaseDate() {
        return purchaseDate;
    }

    public void setPurchaseDate(Date purchaseDate) {
        this.purchaseDate = purchaseDate;
    }
}

在HelloController中添加方法getBookList:

@RequestMapping(value = "/getBookList", method = RequestMethod.GET)
public List<Book> getBookList() {
    List<Book> books = new ArrayList<>();
    try {
         Book book1 = new Book(1, "平凡的世界", "路遥", "2010-01-01");
         Book book2 = new Book(2, "人生", "路遥", "2011-01-01");

         books.add(book1);
         books.add(book2);
    } catch (ParseException e) {
         e.printStackTrace();
    }

    return books;
}

运行项目在浏览器输入http://localhost:8080/getBookList,结果为:

[
  {
    "bookId": 1,
    "bookName": "平凡的世界",
    "bookAuthor": "路遥",
    "purchaseDate": "2009-12-31 16:00:00"
  },
  {
    "bookId": 2,
    "bookName": "人生",
    "bookAuthor": "路遥",
    "purchaseDate": "2010-12-31 16:00:00"
  }
]

然后我们在HelloController上也加上@RequestMapping注解:

package com.zwwhnly.springbootdemo.controller;

import com.zwwhnly.springbootdemo.model.Book;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "hello")
public class HelloController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String sayHello() {
        return "hello";
    }

    @RequestMapping(value = "/getBookList", method = RequestMethod.GET)
    public List<Book> getBookList() {
        List<Book> books = new ArrayList<>();
        try {
            Book book1 = new Book(1, "平凡的世界", "路遥", "2010-01-01");
            Book book2 = new Book(2, "人生", "路遥", "2011-01-01");

            books.add(book1);
            books.add(book2);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return books;
    }
}

此时两个方法的访问地址就分别变为了:http://localhost:8080/hello/hello,http://localhost:8080/hello/getBookList。

5.@PathVariable

@PathVariable注解用来获取url中的数据,以下为具体的使用方法,

在HelloController控制器中添加方法getBook,通过占位符传递bookId:

@RequestMapping(value = "/getBook/{bookId}", method = RequestMethod.GET)
public Book getBook(@PathVariable Integer bookId) {
     Book book = null;
     List<Book> books = new ArrayList<>();
     try {
            Book book1 = new Book(1, "平凡的世界", "路遥", "2010-01-01");
            Book book2 = new Book(2, "人生", "路遥", "2011-01-01");

            books.add(book1);
            books.add(book2);

            book = books.get(bookId - 1);
        } catch (ParseException e) {
            e.printStackTrace();
    }

    return book;
}

运行项目,在浏览器中访问http://localhost:8080/hello/getBook/1,结果如下:

{
  "bookId": 1,
  "bookName": "平凡的世界",
  "bookAuthor": "路遥",
  "purchaseDate": "2009-12-31 16:00:00"
}

注意:占位符里的名称必须和参数名完全一致,区分大小写,否则访问会报500错误。

如果想不一致,可以写成如下方式:

@RequestMapping(value = "/getBook/{bookId}", method = RequestMethod.GET)
public Book getBook(@PathVariable("bookId") Integer bookIndex) {
      ......
}

这种方式也要求,PathVariable的value属性值必须与占位符里的名称完全一致。

这里的bookId,如果我们正常输入数字的话,接口是没有问题的,但如果不小心输入成了字符串,则会报如下错误:

为了避免因为用户输错参数而使接口报错的问题,我们可以使用正则表达式限制参数bookId必须为数字

@RequestMapping(value = "/getBook/{bookId:\\d+}", method = RequestMethod.GET)
public Book getBook(@PathVariable Integer bookId) {
     ......
}

此时再次访问错误的url,则返回404(接口未找到):

好了,本篇文章就先讲解这么多,其它注解后续再单独发布文章讲解。

6.源码地址

原文地址:Spring Boot入门(四):开发Web Api接口常用注解总结

博客地址:http://www.zwwhnly.com

源码地址:https://github.com/zwwhnly/springbootdemo.git

欢迎大家下载,有问题可以多多交流。

7.参考链接

用Spring Boot开发一个web API 接口返回数据

SpringBoot 中常用注解@Controller/@RestController/@RequestMapping介绍