Spring引导路径变量,下划线不调用控制器

时间:2016-08-29 21:49:29

标签: spring-mvc spring-boot

您好我使用的是弹簧靴1.3.4。在我的控制器中,我有以下请求映射,

@RequestMapping(value = "name/{name}",method = RequestMethod.GET)
public ResponseEntity<Book> getBooksByName(@Valid @PathVariable("name") String name) {
    final Book h = mongoService.findByBookName(name);

Application.yml

server:
port: 8170
contextPath: /book-repository
spring:
    application:
        name: book-repository
    devtools:
        restart:
            exclude: META-INF/maven/**
            additional-paths: src/main/resources/
bookRepository:
    mongodb:
        connectionStrings:
            bookRepository: mongodb://localhost:27017/contentdb
springfox.documentation.swagger.v2.path: /api/v1
management.add-application-context-header: false

BookRepositoryMain.java

@SpringBootApplication
public class BookRepositoryMain {

public static final Logger LOG = LoggerFactory.getLogger(BookRepositoryMain.class);

public static void main(String[] args) {
    LOG.info("Initialising ...");
    SpringApplication.run(BookRepositoryMain.class, args);
}

}

BookController.java

@Api(value = "books", description = "books endpoint", tags = {"books"}, produces = MediaType.APPLICATION_JSON_VALUE)
@RestController
@RequestMapping(value = PATH, produces = MediaType.APPLICATION_JSON_VALUE)
public class BooksController {
public static final Logger LOG = LoggerFactory.getLogger(BooksController.class);
public static final String PATH = "/books";

@RequestMapping(
        value = "name/{name}",
        method = RequestMethod.GET)
@ApiOperation(
        response = Book.class,
        notes = "",
        value = "Finds Book by its name.")
@ApiResponses({
    @ApiResponse(code = 404, response = ErrorMessage.class, message = "Book not found.")
})
public ResponseEntity<Book> getBookByName(@PathVariable("name") String uid) throws ContentNotFoundException {
    final Book h = deviceMongoService.findByBookName(name);
    if (h == null) {
        throw new BookNotFoundException(String.format("Could not find book with name %s", name));
    }
    final ResponseEntity<Book> response = ResponseEntity.ok().body(h);
    return response;
}

}

如果网址为&#34; api / v1 / books / name / sherlock_homes&#34; ,则上述方法无效,但网址为&#34; api / v1 / books / name / sherlockHomes&#34; 然后正常工作

可能是什么问题?为什么spring不允许在路径变量中使用下划线?

你的帮助应该是值得的。

1 个答案:

答案 0 :(得分:1)

您可以在@RequestMapping值中使用正则表达式。例如,您可以尝试:

@RequestMapping(value = "name/{name:.+}",method = RequestMethod.GET)

这在spring docs中有记录,也可在此similar question

中找到