|
16 | 16 |
|
17 | 17 | package org.springframework.web.bind.annotation;
|
18 | 18 |
|
| 19 | +import org.springframework.http.HttpMethod; |
| 20 | +import org.springframework.lang.Nullable; |
| 21 | +import org.springframework.util.Assert; |
| 22 | + |
19 | 23 | /**
|
20 | 24 | * Enumeration of HTTP request methods. Intended for use with the
|
21 | 25 | * {@link RequestMapping#method()} attribute of the {@link RequestMapping} annotation.
|
|
34 | 38 | */
|
35 | 39 | public enum RequestMethod {
|
36 | 40 |
|
37 |
| - GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE |
| 41 | + GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; |
| 42 | + |
| 43 | + |
| 44 | + /** |
| 45 | + * Resolve the given method value to an {@code RequestMethod} enum value. |
| 46 | + * Returns {@code null} if {@code method} has no corresponding value. |
| 47 | + * @param method the method value as a String |
| 48 | + * @return the corresponding {@code RequestMethod}, or {@code null} if not found |
| 49 | + * @since 6.0.6 |
| 50 | + */ |
| 51 | + @Nullable |
| 52 | + public static RequestMethod resolve(String method) { |
| 53 | + Assert.notNull(method, "Method must not be null"); |
| 54 | + return switch (method) { |
| 55 | + case "GET" -> GET; |
| 56 | + case "HEAD" -> HEAD; |
| 57 | + case "POST" -> POST; |
| 58 | + case "PUT" -> PUT; |
| 59 | + case "PATCH" -> PATCH; |
| 60 | + case "DELETE" -> DELETE; |
| 61 | + case "OPTIONS" -> OPTIONS; |
| 62 | + case "TRACE" -> TRACE; |
| 63 | + default -> null; |
| 64 | + }; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Resolve the given {@link HttpMethod} to a {@code RequestMethod} enum value. |
| 69 | + * Returns {@code null} if {@code httpMethod} has no corresponding value. |
| 70 | + * @param httpMethod the http method object |
| 71 | + * @return the corresponding {@code RequestMethod}, or {@code null} if not found |
| 72 | + * @since 6.0.6 |
| 73 | + */ |
| 74 | + @Nullable |
| 75 | + public static RequestMethod resolve(HttpMethod httpMethod) { |
| 76 | + Assert.notNull(httpMethod, "HttpMethod must not be null"); |
| 77 | + return resolve(httpMethod.name()); |
| 78 | + } |
| 79 | + |
| 80 | + |
| 81 | + /** |
| 82 | + * Return the {@link HttpMethod} corresponding to this {@code RequestMethod}. |
| 83 | + * @return the http method for this request method |
| 84 | + * @since 6.0.6 |
| 85 | + */ |
| 86 | + public HttpMethod asHttpMethod() { |
| 87 | + return switch (this) { |
| 88 | + case GET -> HttpMethod.GET; |
| 89 | + case HEAD -> HttpMethod.HEAD; |
| 90 | + case POST -> HttpMethod.POST; |
| 91 | + case PUT -> HttpMethod.PUT; |
| 92 | + case PATCH -> HttpMethod.PATCH; |
| 93 | + case DELETE -> HttpMethod.DELETE; |
| 94 | + case OPTIONS -> HttpMethod.OPTIONS; |
| 95 | + case TRACE -> HttpMethod.TRACE; |
| 96 | + }; |
| 97 | + } |
38 | 98 |
|
39 | 99 | }
|
0 commit comments