Validate path parameters with @RequestMapping

Overview

--The path parameter (placeholder) of the URI defined by @RequestMapping can be validated in the form of{parameter name: regular expression}. --For example, if the URI is defined like @RequestMapping (path =" / hello / {name} ") and you want to prevent only half-width alphabetic characters from being accepted in name,@RequestMapping ( Write path = "/ hello / {name: [a-zA-Z] +}"). --To be precise, the syntax of URI placeholders is agreed.

Premise

--Assuming REST API created with Spring Boot. --The syntax is determined by the path attribute (or value attribute) of @RequestMapping used in the controller class with @RestContoller.

environment

Example of writing

API that inputs half-width alphabetic characters in the URI placeholder and returns " hello, {entered half-width alphabetic characters} ".

HelloController.java


@RestController
public class HelloController {

  @RequestMapping(path = "/hello/{name:[a-zA-Z]+}", method = RequestMethod.GET)
  public String hello(@PathVariable String name) {
    return "hello, " + name;
  }
}

Execution example.

bash-3.2$ curl -X GET http://localhost:8080/hello/Freddie
hello, Freddie

If there is an incorrect syntax input, it will be treated as 404 resource undetected. The default error response is:

bash-3.2$ curl -X GET http://localhost:8080/hello/0123
{"timestamp":"2018-11-20T16:02:56.401+0000","status":404,"error":"Not Found","message":"No message available","path":"/hello/0123"}

In addition, if you want to use a 3-digit half-width number syntax, use a regular expression that expresses the desired syntax, such as @RequestMapping (path =" / hello / {id: \\ d {3}} "). Just do it.

reference

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-requestmapping-uri-templates

Recommended Posts

Validate path parameters with @RequestMapping
Validate arguments using ArgumentCaptor with mockito
Passing parameters from JSP with Servlet
Don't set JAVA_HOME with full path