给定以下 Spring 代码:
@Controller
@RequestMapping("/somepath")
public class SomeService {
@RequestMapping(headers = "Accept=application/json")
public ReturnType methodOne() {
// stuff
}
@RequestMapping(headers = "Accept=text/html")
public ReturnType methodTwo() {
// stuff
}
}
我注意到,当客户端根本不包含“Accept”标头时,总是优先调用“application/json”方法而不是 text/html 方法。我的问题是——为什么?它们之间没有什么可以选择的,那么为什么更喜欢其中一个呢?我本来希望收到一条错误消息...
一个具体的例子:
@RequestMapping("/somepath")
@Controller
public class SomeService {
@ResponseBody
@RequestMapping(headers = "Accept=application/json")
public ResponseEntity<String> methodOne() {
return new ResponseEntity<String>("Method One", HttpStatus.OK);
}
@ResponseBody
@RequestMapping(headers = "Accept=text/html")
public ResponseEntity<String> methodTwo() {
return new ResponseEntity<String>("Method Two", HttpStatus.OK);
}
@ResponseBody
@RequestMapping(headers = "Accept=application/xml")
public ResponseEntity<String> methodThree() {
return new ResponseEntity<String>("Method Three", HttpStatus.OK);
}
}
如果没有接受标头,则始终输出“方法一”。