iT邦幫忙

2024 iThome 鐵人賽

0
Software Development

從Servlet到Spring MVC系列 第 35

Day34 Spring MVC - RESTful

  • 分享至 

  • xImage
  •  

創建module

(1) 請參考Day27 module
(2) 使用JSON相關設置請參考Day29

一、RESTful

(1) 何謂RESTful

RESTful(Representational State Transfer)指的是一種軟體架構風格,透過HTTP的請求方法與狀態碼進行交互溝通

(2) RESTful特點

透過請求方式對應操作
Action Method
Create POST
Read GET
Update PUT
Delete DELETE
回應狀態碼
Response code Status
200 OK
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not found
REST Style URL
Action traditional Style REST Style
Create /api/saveEmp POST /api/emp POST
Read /api/QueryEmp?empId=2 GET /api/emp/2 GET
Update /api/updateEmp POST /api/emp/ PUT
Delete /api/deleteEmp?empId=2 GET /api/emp/2 DELETE

二、RESTful實戰

(1) 創建範例

創建DemoController

@RestController
@RequestMapping("api/emp")
public class DemoController {

    @PostMapping
    public String createEmp(@RequestBody Employee emp){
        System.out.println(emp.toString());
        return "createEmp success";
    }


    @GetMapping(path = "/{empId}")
    public String readEmp( @PathVariable("empId") String empId){
        System.out.println("query empId: " + empId);
        return "readEmp success";
    }

    @PutMapping
    public String updateEmp(){
        return "updateEmp success";
    }

    @DeleteMapping(path = "/{empId}")
    public String deleteEmp(@PathVariable("empId") String empId){
        System.out.println("delete empId: " + empId);
        return "deleteEmp success";
    }
}

創建Employee

public class Employee {

    private String empId;
    private String name;
    private String email;
    private int age;
    private String gender;
    private LocalDate entryDate;
    //getter and setter略
}

(2) Demo

Create
https://ithelp.ithome.com.tw/upload/images/20241019/20128084Dqva4rMmZ8.png
Read
https://ithelp.ithome.com.tw/upload/images/20241019/20128084CPsL9EYJiJ.png
Update
https://ithelp.ithome.com.tw/upload/images/20241019/20128084mlnqEjgwjo.png
Delete
https://ithelp.ithome.com.tw/upload/images/20241019/20128084v4Uy7mfTFg.png

三、Swagger

在現今前後端分離架構會透過Swagger產生API文件來降低前後端溝通的成本也能透過API文件頁面執行API的操作。原先最常使用的SpringFox已不再維護,這個部份我們將使用Springdoc-openapi來進行演示。

(1) 配置

maven

<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.6.0</version>
</dependency>

springmvc-servlet.xml,在原有的Converter中加入ByteArrayHttpMessageConverter

<mvc:message-converters>
    <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="objectMapper" ref="objectMapper"/>
    </bean>
</mvc:message-converters>

創建OpenApiConfig

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"org.springdoc"})
public class OpenApiConfig implements WebMvcConfigurer {
    @Bean
    public OpenAPI customOpenAPI() {
        return new OpenAPI()
                .info(new Info()
                        .title("Day34 Demo API")
                        .version("1.0")
                        .description("API Documentation"));
    }
}

(2) 常用Annotation

註解 標註位置 作用
@Tag controller 描述controller作用
@Schema model層java bean 描述模型的每個屬性
@Operation 方法 描述方法作用
@ApiResponse 方法 描述回應狀態碼

(3) 範例建置

@Tag(name = "DemoController" ,description = "Employee的CRUD")
@RestController
@RequestMapping("api/emp")
public class DemoController {
  @Operation(summary = "Gets employee by empId",
            description= "employee must exist")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "400", description = "Invalid ID supplied"),
            @ApiResponse(responseCode = "404", description = "Customer not found")})
    @GetMapping(path = "/{empId}")
    public String readEmp( @PathVariable("empId") String empId){
        System.out.println("query empId: " + empId);
        return "readEmp success";
    }
  //其他略
}

Demo

https://ithelp.ithome.com.tw/upload/images/20241019/20128084shYK2l5S2a.png

Reference


上一篇
Day34 Spring MVC - Validation
下一篇
Day35 Spring MVC - Project
系列文
從Servlet到Spring MVC36
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言