@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value ={"","/page","page*","view/*,**/msg"})
String indexMultipleMapping(){return"Hello from index multiple mapping.";}}
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value ="/id")// 实现请求参数 id 与 处理方法参数 personId 的绑定。
String getIdByValue(@RequestParam("id") String personId){
System.out.println("ID is "+ personId);return"Get ID from query string of URL with value element";}
@RequestMapping(value ="/personId")
String getId(@RequestParam String personId){
System.out.println("ID is "+ personId);return"Get ID from query string of URL without value element";}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
getIdByValue()方法实现了请求参数 id 与 处理方法参数 personId 的绑定。
getId()方法实现了请求参数 personId 与 处理方法参数 personId 的绑定。
如果请求参数和处理方法参数的名称一样的话,@RequestParam 注解的 value 这个参数就可省掉了。
2、@RequestParam 的 required 属性
@RequestParam 注解的 required 这个参数定义了参数值是否是必须要传的。
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value ="/name")
String getName(@RequestParam(value ="person", required = true) String personName){return"Required element of request param";}}
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value ="/name")
String getName(@RequestParam(value ="person", required = false) String personName){return"Required element of request param";}}
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value ="/name")
String getName(@RequestParam(value ="person", defaultValue ="John") String personName){return"Required element of request param";}}
1
2
3
4
5
6
7
8
9
在这段代码中,如果 person 这个请求参数为空,那么 getName() 处理方法就会接收 John 这个默认值作为其参数。
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value ="/head", headers ={"content-type=text/plain"})
String post(){return"Mapping applied along with headers";}}
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value ="/head", headers ={"content-type=text/plain","content-type=text/html"}) String post(){return"Mapping applied along with headers";}}
@PathVariable 同 @RequestParam的运行方式不同。你使用 @PathVariable 是为了从 URI 里取到查询参数值。换言之,你使用 @RequestParam 是为了从 URI 模板中获取参数值。
九、设置 @RequestMapping 默认的处理方法
在控制器类中,你可以有一个默认的处理方法,它可以在有一个向默认 URI 发起的请求时被执行。
下面是默认处理方法的示例:
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping()
String
default(){return"This is a default method for the class";}}