我正在將一些路由從基于 jax-rs 的應用程式遷移到 SpringBoot。在 jax-rs 中,我可以使用 @Path 定義一個包含多個 URL 路徑元素的正則運算式:
@Path("{id:[^/] /y[\d]{4}/m[\d]{1,2}/d[\d]{1,2}/h[\d]{1,2}}/")
方法主體中的 id 變數將成為 URL 的匹配段,我可以繼續我的一天。
在 Spring 中使用 @RequestMapping 這不起作用。一旦你在正則運算式中加入一個正斜杠,你就會得到一個 PatternParseException。
PathContainer pathContainingSlash = PathContainer.parsePath("/api/test/y1978/m07/d15");
PathPatternParser parser = new PathPatternParser();
assertThrows(PatternParseException.class, () ->
parser.parse("/api/test/{ticketId:y[\\d]{4}/m[\\d]{1,2}/d[\\d]{1,2}}"));
AntPathMatcher 似乎也出現了同樣的問題。
AntPathMatcher antPathMatcher = new AntPathMatcher();
assertThrows(IllegalStateException.class, () ->
antPathMatcher.extractUriTemplateVariables(
"/api/test/{ticketId:y[\\d]{4}/m[\\d]{1,2}/d[\\d]{1,2}}",
"/api/test/y1978/m07/d15"));
這是一個問題,因為我有大約 78 個這些 URL 模式。我將不得不單獨定義每個模式,每個路徑元素都是一個單獨的變數。然后我將不得不使用字串連接將它們以路徑的格式重新組合在一起。
@GetMapping("/{year:y[\\d]{4}}/{month:m[\\d]1,2}/{day:d[\\d]{1,2}")
public ResponseEntity<Void> foo(@PathVariable String year,
@PathVariable String month,
@PathVariable String day) {
String date = year "/" month "/" day;
}
除了在我的 SpringBoot 應用程式中使用 Jax-rs 之外,還有沒有做到這一點?可以像這樣寫它們,但它似乎不是最理想的。
為了清楚起見,我真的想要一種將多個路徑元素從 URL 提取到 @PathVariable 的方法。我想要這樣的東西:
@GetMapping("/api/test/{date:y[\\d]{4}/m[\\d]{1,2}/d[\\d]{1,2}}")
public ResponseEntity<Void> foo(@PathVariable String date) {}
所以那個日期現在等于 y1978/m07/d15
此外,這只是一個示例模式。有 78 種獨特的模式,它們具有不同數量的路徑元素和元素的內容。在使用 @Path 的 Jax-RS 中,我可以將這些正則運算式 OR 在一起并創建一個路由,并且可以在方法內部訪問路徑變數。
uj5u.com熱心網友回復:
添加spring-boot-starter-validation驗證怎么樣
需要添加以下 jar
org.springframework.boot:spring-boot-starter-validation添加
@org.springframework.validation.annotation.Validated在控制器類之上添加
@javax.validation.constraints.Pattern與regex屬性添加到@PathVariable方法PARAMS
@GetMapping("{year}/{month}/{day}")
public ResponseEntity<Void> foo(
@PathVariable @Pattern(regexp = "[\\d]{4}", message = "year must be ..") String year,
@PathVariable @Pattern(regexp = "[\\d]{1,2}", message = "month must ..") String month,
@PathVariable @Pattern(regexp = "[\\d]{1,2}", message= "day must be ..") String day) {
String date = year "/" month "/" day;
- 要回傳 http 400 狀態,請添加處理 ConstraintViolationException 的方法
@ExceptionHandler(value = { ConstraintViolationException.class })
protected ResponseEntity<List<String>> handleConstraintViolations(ConstraintViolationException ex, WebRequest request) {
List<String> errorMessages = ex.getConstraintViolations().stream()
.map(violation -> violation.getMessage()).collect(Collectors.toList());
return new ResponseEntity<List<String>>(errorMessages, HttpStatus.BAD_REQUEST);
}
更多驗證示例:https : //reflectoring.io/bean-validation-with-spring-boot/
更多例外處理選項:https : //www.baeldung.com/exception-handling-for-rest-with-spring
uj5u.com熱心網友回復:
使用此執行緒中的路徑重寫的可能選項 Spring MVC Getting PathVariables contains dots and slashes
添加
<dependency>
<groupId>org.tuckey</groupId>
<artifactId>urlrewritefilter</artifactId>
<version>4.0.3</version>
</dependency>
添加重寫規則到 src/main/webapp/WEB-INF/urlrewrite.xml
<urlrewrite>
<rule>
<from>^/api/test/(y[\d]{4})/(m[\d]{2})/(d[\d]{2})$</from>
<to>/api/test?date=$1/$2/$3</to>
</rule>
</urlrewrite>
to使用查詢引數創建匹配重寫規則路徑的控制器方法
@GetMapping("/api/test")
public ResponseEntity<Void> foo(@RequestParam String date) {
System.out.println(date);
return new ResponseEntity<Void>(HttpStatus.OK);
}
添加配置類以使用 urlPatterns 注冊重寫過濾器進行過濾
@Configuration
public class FiltersConfig {
@Bean
public FilterRegistrationBean<Filter> someFilterRegistration() {
FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<Filter>();
registration.setFilter(rewriteFilter());
// add paths to filter
registration.addUrlPatterns("/api/*");
registration.setName("urlRewriteFilter");
registration.setOrder(1);
return registration;
}
public Filter rewriteFilter() {
return new UrlRewriteFilter();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/407589.html
標籤:
上一篇:Spring-Boot升級到2.6.2在運行時出錯-BeanCreationException
下一篇:全部允許不授權匿名訪問
