先让我们看一下错误信息
代码语言:javascript复制HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.47
@PathVariable 导致400的错误代码
代码语言:javascript复制/**
* @author lvgo
* @version 1.0
* @Description: 调试400错误
* @date 2018/1/17 14:44
*/
@Controller
public class ItemController {
Logger log = Logger.getLogger(ItemController.class);
@Autowired
private ItemService itemService;
@RequestMapping("/item/{itemId}")
@ResponseBody
public TbItem getItemById(@PathVariable Long id) {
TbItem tbItem = itemService.findById(id);
return tbItem;
}
}
简单看一下上面代码觉得似乎没有什么不对的地方,但是启动之后访问 /item/param 就会报 400 错误
修改后代码
代码语言:javascript复制/**
* @author lvgo
* @version 1.0
* @Description: 调试400错误
* @date 2018/1/17 14:44
*/
@Controller
public class ItemController {
Logger log = Logger.getLogger(ItemController.class);
@Autowired
private ItemService itemService;
//错误写法
@RequestMapping("/item/{itemId}")
@ResponseBody
public TbItem getItemById(@PathVariable Long id) {
TbItem tbItem = itemService.findById(id);
return tbItem;
}
// 如果使用了@PathVariable注解就一定要遵守注解规则
// 方法参数要么与路径参数相同,要么自定义value值为路径的对应值
// 正确写法1
@RequestMapping("/item/{itemId}")
@ResponseBody
public TbItem getItemById(@PathVariable(value="itemId") Long id) {
TbItem tbItem = itemService.findById(id);
return tbItem;
}
// 正确写法2
@RequestMapping("/item/{itemId}")
@ResponseBody
public TbItem getItemById(@PathVariable Long itemId) {
TbItem tbItem = itemService.findById(itemId);
return tbItem;
}
}
@RequestParam 导致400的正确写法
代码语言:javascript复制 /**
* @author lvgo
* @version 1.0
* @Description: 调试400错误
* @date 2018/1/17 14:44
*/
@Controller
public class ItemController {
Logger log = Logger.getLogger(ItemController.class);
@Autowired
private ItemService itemService;
// 1.参数必须要传入 name = id
@RequestMapping("/item")
@ResponseBody
public TbItem getItemById(@RequestParam Long id) {
TbItem tbItem = itemService.findById(id);
return tbItem;
}
// 2.这样参数就必须要是 name = itId
@RequestMapping("/item")
@ResponseBody
public TbItem getItemById(@RequestParam(value = "itId") Long id) {
TbItem tbItem = itemService.findById(id);
return tbItem;
}
// 3.这样是给了参数的默认值
@RequestMapping("/item")
@ResponseBody
public TbItem getItemById(@RequestParam(value = "itId",default = "0") Long id) {
TbItem tbItem = itemService.findById(itemId);
return tbItem;
}
}