我正在尝试发布jquery Ajax请求,但它没有到达我的MVC控制器。
$.ajax({
url : contextPath + "/check/panelnumber",
type : "POST",
contentType : "application/json",
data :{
"execution" : execution,
"panelNumber" : panelNumber
},
});
Spring MVC控制器
@Controller
@RequestMapping("/check")
public class ValidateFieldValueController extends FlowEnabledBaseController {
@RequestMapping(value = "/panelnumber", method = RequestMethod.POST)
public ResponseEntity<String> checkPanelNumber(HttpServletRequest request,
HttpServletResponse response,
@RequestParam("panelNumber") String panelNumber,
@RequestParam("execution") String execution) {
......
Gson gson = new Gson();
return new ResponseEntity<String>(gson.toJson(details), HttpStatus.OK);
}
然而,它对GET方法来说非常好!尝试添加dataType:"json",但使用此方法后,GET调用也停止工作。浏览器控制台将错误显示为HTTP 400错误请求,但当通过firefox插件进行检查时,POST参数会正常运行。有什么帮助吗?
Spring在@RequestParam、POST主体和JSON内容类型方面有点敏感:它根本不会解析它们。你可以用三种方法之一来解决这个问题:
- 将内容类型更改为
application/x-www-form-urlencoded
- 将两个
@RequestParam
更改为单个@RequestBody Map<String, Object> body
,然后使用该Map
手动解析出参数 - 设置一个自定义参数解析程序,它可以解析JSON以获得所需的值
第二种方法可能是最容易更改的,但它会失去Spring为您所做的一些自动魔术验证。