带有可选参数的Spring @RequestMapping [英] Spring @RequestMapping with optional parameters

查看:560
本文介绍了带有可选参数的Spring @RequestMapping的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器在请求映射中具有可选参数时出现问题,请在下面的控制器上查看:

I have problem in my controller with optional params in requestmapping, look on my controller below:

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Books>> getBooks() {
    return ResponseEntity.ok().body(booksService.getBooks());
}

@GetMapping(
    produces = MediaType.APPLICATION_JSON_VALUE,
    params = {"from", "to"}
)
public ResponseEntity<List<Books>>getBooksByFromToDate(
    @RequestParam(value = "from", required = false) String fromDate,
    @RequestParam(value = "to", required = false) String toDate) 
{
    return ResponseEntity.ok().body(bookService.getBooksByFromToDate(fromDate, toDate));
}

现在,当我发送如下请求时:

Now, when I send request like:

/getBooks?from=123&to=123

可以,请求转到"getBooksByFromToDate"方法 但是当我使用发送类似:

it's ok, request goes to "getBooksByFromToDate" method but when I use send something like:

/getBooks?from=123

/getBooks?to=123

转到"getAlerts"方法

it goes to "getAlerts" method

是否可以在@RequestMapping中使可选参数= {"from","to"}?有提示吗?

Is it possible to make optional params = {"from", "to"} in @RequestMapping ? Any hints?

推荐答案

使用默认值.示例:-

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Books>> getBooksByFromToDate(@RequestParam(value = "from", required = false, defaultValue="01/03/2018") String fromDate, @RequestParam(value = "to", required = false, defaultValue="21/03/2018") String toDate) { 
.... 
}

这篇关于带有可选参数的Spring @RequestMapping的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆