よわよわエンジニアの学習記録

エンジニアになってからの学びを残しておきます。間違い等ございましたら、指摘していただけると泣いて喜びます!笑

@ResponseStatusでHTTPレスポンスのステータスを指定する方法 Spring

HTTPレスポンスの番号を指定したいなーと思ったので、@ResponseStatesを使って

指定してみました。

 

@ResponseStatesとは?

メソッドにつけることでレスポンスのステータスを指定できるアノテーションです。

()の中に指定したHTTPステータスを返すことができます。

()内にはHttpStatus.〇〇〇という形で記載します。(HttpStatusはenumです。)

 

使用例

今回はDLETEメソッドで204番を返せすようにします。

①コントローラー(ResponseStatesに関してはここのみ確認でOKです!)

package com.hourse.example.hourselist;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RaceController {
    @Autowired
    private RaceRepository raceRepository;
  
    
    @DeleteMapping("/hourse/{order_of_arrival}")
    @ResponseStatus(HttpStatus.NO_CONTENT)

 //今回は204に指定したかったのでNO_CONTENTにしています
    public void hourseDelete(@PathVariable int order_of_arrival) {
        raceRepository.deleteById(order_of_arrival);
    }
}

リポジトリ

package com.hourse.example.hourselist;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface RaceRepository extends JpaRepository<Tennosho, Integer>{

}

➂Bean

package com.hourse.example.hourselist;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Tennosho {
    @Id
    int order_of_arrival;
    String hourse_name;
    
    
    public int getOrder_of_arrival() {
        return order_of_arrival;
    }
    public void setOrder_of_arrival(int order_of_arrival) {
        this.order_of_arrival = order_of_arrival;
    }
    public String getHourse_name() {
        return hourse_name;
    }
    public void setHourse_name(String hourse_name) {
        this.hourse_name = hourse_name;
    }
    
    
}

④application.properties

spring.jpa.show-sql = true
spring.h2.console.enabled = true
spring.datasource.url = jdbc:h2:mem:testdb
spring.jpa.defer-datasource-initialization = true

 

・指定前の実行画面

・指定後の実行画面

ちゃんと変わってます!やったー

 

所感

使い方は難しくないですが、初めてだと戸惑ってしまうと思うのでぜひ参考にしてみてください!