SpringMVC下,提交表单报400错:
description The request sent by the client was syntactically incorrect.
根据网上的总结,可能是因为如下几个问题引起的
1.参数指定问题
如果Controller中定义了参数,而表单内却没有定义该字段
1 2 3 4 5 6 7 8 | @SuppressWarnings ( "deprecation" ) @RequestMapping ( "/hello.do" ) public String hello(HttpServletRequest request,HttpServletResponse response, @RequestParam (value= "userName" ) String user ){ request.setAttribute( "user" , user); return "hello" ; } |
这里,表单内必须提供一个userName的属性!
不想指定的话,你也可以定义这个属性的默认值defaultValue="":
1 2 3 4 5 6 7 8 | @SuppressWarnings ( "deprecation" ) @RequestMapping ( "/hello.do" ) public String hello(HttpServletRequest request,HttpServletResponse response, @RequestParam (value= "userName" ,defaultValue= "佚名" ) String user ){ request.setAttribute( "user" , user); return "hello" ; } |
也可以指定该参数是非必须的required=false:
1 2 3 4 5 6 7 8 | @SuppressWarnings ( "deprecation" ) @RequestMapping ( "/hello.do" ) public String hello(HttpServletRequest request,HttpServletResponse response, @RequestParam (value= "userName" ,required= false ) String user ){ request.setAttribute( "user" , user); return "hello" ; } |
2.上传问题
上传文件大小超出了Spring上传的限制
1 2 3 4 5 6 7 8 9 | < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!-- 设置上传文件的最大尺寸1024字节=1K,这里是10K --> < property name = "maxUploadSize" > < value >10240</ value > </ property > < property name = "defaultEncoding" > < value >UTF-8</ value > </ property > </ bean > |
我们工程里面是这个问题引起的,但是我实际示例中发现超过大小是直接报错的。
3.时间转换问题
也有网友说是因为时间转换引起的,而我实际操作中发现报错是:
The server encountered an internal error that prevented it from fulfilling this request
这里也顺便提一下,假如你的Controller要一个时间对象,代码如下:
1 2 3 4 5 6 7 8 9 10 | @SuppressWarnings ( "deprecation" ) @RequestMapping ( "/hello.do" ) public String hello(HttpServletRequest request,HttpServletResponse response, @RequestParam (value= "userName" ,defaultValue= "佚名" ) String user, Date dateTest ){ request.setAttribute( "user" , user); System.out.println(dateTest.toLocaleString()); return "hello" ; } |
而网页上实际给的是
<input type="text" name="dateTest" value="2015-06-07">
这里需要在Controller增加一个转换器
1 2 3 4 5 6 | @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" ); dateFormat.setLenient( false ); binder.registerCustomEditor(Date. class , new CustomDateEditor(dateFormat, false )); } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。
- 本文固定链接: https://zxbcw.cn/post/197892/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)