我们应该将矩阵变量与弹簧靴中的路径参数相关联吗?

问题描述 投票:0回答:1
当我将矩阵变量与路径参数关联时,我能够访问矩阵变量的值,但是当我将其与固定路径段关联时,我不能。为什么这样?

@RestController @RequestMapping("/books") public class BookController { @Autowired private BookService bookService; @GetMapping(path = "") public List<Book> getBooks() { System.out.println("Fetching all books ..."); return bookService.findAll(); } @GetMapping(path = "/search") public List<Book> filterBooks( @MatrixVariable(name = "genre", required = false) String genre, @MatrixVariable(name = "author", required = false) String author ) { System.out.println("Fetching books by filter ..."); System.out.println("genre: |" + genre + "| author: |" + author + "|"); return null; } @GetMapping(path = "/{id}") public Book getBooksById(@PathVariable int id) { System.out.println("Fetching book by id ..."); return bookService.findById(id); } @PostMapping(path = "") public Book saveBook(@RequestBody Book book) { System.out.println("Fetching all books ..."); return bookService.save(book); } }

当我命中:http:// localhost:8080/books/search; genre =小说我得到:

org.springframework.web.method.annotation.methodargumenttypemismatchexception:方法参数'id':无法将'java.lang.lang.string'类型的值转换为必需的'int';对于输入字符串:“搜索” atorg.springframework.web.method.annotation.

我认为春季靴子正在尝试将其映射到 /books/ {id}。

但如果我有:

@GetMapping(path = "/search/{filter}") public List<Book> filterBooks( @MatrixVariable(name = "genre", required = false) String genre, @MatrixVariable(name = "author", required = false) String author ) { System.out.println("Fetching books by filter ..."); System.out.println("genre: |" + genre + "| author: |" + author + "|"); return null; }

并击中http:// localhost:8080/books/search/genre =小说,然后我能够访问矩阵变量。

在这种情况下,当我们在URL中没有任何路径参数时,为什么要有一个路径参数“滤波”?
	
在文档中,它列出以下内容:

Https://docs.spring.io/spring-framework/reference/web/web/webmvc/mvc-controller/ann-methods/ann-methods/matrix-variables.html

spring-boot rest spring-mvc spring-data-jpa spring-data-rest
1个回答
0
投票

因此,对于矩阵变量映射要工作,您必须具有一个可变量的蒙版,在这种情况下,它是您的{filter}变量。 必须配置urlPathhelper,但我相信您已经做到了,否则您将获得null的值。

注意,您需要启用矩阵变量。在MVC Java配置中,您需要使用
UrlPathHelper

通过

Path匹配
设置一个

removeSemicolonContent=false。在MVC XML名称空间中,您可以设置<mvc:annotation-driven enable-matrix-variables="true"/>

配置示例:

@Configuration public class DemoConfiguration implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { UrlPathHelper urlPathHelper = new UrlPathHelper(); urlPathHelper.setRemoveSemicolonContent(false); configurer.setUrlPathHelper(urlPathHelper); } }

控制器示例:

// GET /pets/42;q=11;r=22

@GetMapping("/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {

    // petId == 42
    // q == 11
}
    
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.