| TIPS |
| JAX-RS(Jersey) を使ってREST APIの実装 |
Spring-MVC(@Controller)の代わりに以下でリクエストを受け付ける
@Path("/users") // RequestMapping相当
public class UserResource {
@POST // PostMapping相当
@Consumes(MediaType.APPLICATION_JSON) // requestのContent-Type = "application/json"
@Produces(MediaType.APPLICATION_JSON) // responseのContent-Type = "application/json"
public UserResponse create(UserRequest req) {
...
}
}
|
| アノテーション |
| アノテーション |
用途 |
Spring MVC相当 |
| @Path |
URLパスを定義 |
@RequestMapping |
| @GET |
HTTP GET要求を処理 |
@GetMapping |
| @POST |
HTTP POST要求を処理 |
@PostMapping |
| @PUT |
HTTP PUT要求を処理 |
@PutMapping |
| @DELETE |
HTTP DELETE要求を処理 |
@DeleteMapping |
| @Consumes |
受信データ形式を指定(requestのContent-Type) |
consumes属性 |
| @Produces |
応答データ形式を指定(responseのContent-Type) |
produces属性 |
| @PathParam |
URLパスパラメータ取得 |
@PathVariable |
| @QueryParam |
クエリパラメータ取得 |
@RequestParam |
| @HeaderParam |
HTTPヘッダ取得 |
@RequestHeader |
| @CookieParam |
Cookie取得 |
@CookieValue |
| @FormParam |
Formパラメータ取得 |
@RequestParam |
| @Context |
Request/Responseなどのコンテキスト取得 |
HttpServletRequestのDI |
| @DefaultValue |
デフォルト値指定 |
defaultValue属性 |
|
| @PathParam |
// URLの一部を取得
// 以下の例では{id}
// URL = /member/123
// id = 123
@GET
@Path("/{id}")
public Member get(
@PathParam("id") String id) {
}
|
| @QueryParam |
// クエリパラメータを取得
// 以下の例ではname
// /member?name=sato
// name = sato
@GET
public MemberDto search(
@QueryParam("name") String name) {
}
|
| @HeaderParam |
// HTTPヘッダを取得
// 以下の例ではAuthorizationの内容
// Authorization: Bearer xxxxx
@GET
public String get(
@HeaderParam("Authorization")
String token) {
}
|
| @CookieParam |
// Cookieを取得
// 以下の例ではSESSIONIDの内容
// Cookie: SESSIONID=abc123
@GET
public String get(
@CookieParam("SESSIONID")
String sessionId) {
}
|
| @FormParam |
// Formデータを取得
// 以下の例ではuserIdとpasswordの内容
@POST
@Consumes("application/x-www-form-urlencoded")
public void login(
@FormParam("userId") String userId,
@FormParam("password") String password) {
}
|
| @Consumes |
// リクエストのContent-Typeを指定する
// 以下の例ではJSONで受信する
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void create(MemberRequest req) {
}
|
| @Produces |
// レスポンスのContent-Typeを指定する
// 以下の例ではJSONで返す(応答する)
@GET
@Produces(MediaType.APPLICATION_JSON)
public Member get() {
}
|
| @Context |
public Response get(
@Context HttpHeaders headers) {
}
------
[@Contextで取得できる主なオブジェクト]
HttpServletRequest リクエスト情報
HttpServletResponse レスポンス情報
UriInfo URI情報
HttpHeaders HTTPヘッダ
SecurityContext 認証情報
|