SpringMVC 表单提交参数不匹配报错 提交表单报400错:description The request sent by the client was syntactically incorrect.

1.参数指定问题
如果Controller中定义了参数,而表单内却没有定义该字段

Java代码  收藏代码
  1. @SuppressWarnings("deprecation")  
  2. @RequestMapping("/hello.do")  
  3. public String hello(HttpServletRequest request,HttpServletResponse response,  
  4.         @RequestParam(value="userName") String user  
  5. ){  
  6.     request.setAttribute("user", user);  
  7.     return "hello";  
  8. }  

 

这里,表单内必须提供一个userName的属性!
不想指定的话,你也可以定义这个属性的默认值defaultValue="":

Java代码  收藏代码
  1. @SuppressWarnings("deprecation")  
  2. @RequestMapping("/hello.do")  
  3. public String hello(HttpServletRequest request,HttpServletResponse response,  
  4.         @RequestParam(value="userName",defaultValue="佚名") String user  
  5. ){  
  6.     request.setAttribute("user", user);  
  7.     return "hello";  
  8. }  

 

也可以指定该参数是非必须的required=false:

Java代码  收藏代码
  1. @SuppressWarnings("deprecation")  
  2. @RequestMapping("/hello.do")  
  3. public String hello(HttpServletRequest request,HttpServletResponse response,  
  4.         @RequestParam(value="userName",required=false) String user  
  5. ){  
  6.     request.setAttribute("user", user);  
  7.     return "hello";  
  8. }  

 

2.上传问题

上传文件大小超出了Spring上传的限制

Java代码  收藏代码
  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
  2.     <!-- 设置上传文件的最大尺寸1024字节=1K,这里是10K -->    
  3.     <property name="maxUploadSize">    
  4.         <value>10240</value>    
  5.     </property>  
  6.     <property name="defaultEncoding">    
  7.            <value>UTF-8</value>    
  8.     </property>    
  9. </bean>  

 

我们工程里面是这个问题引起的,但是我实际示例中发现超过大小是直接报错的。

 

3.时间转换问题

也有网友说是因为时间转换引起的,而我实际操作中发现报错是:

Java代码  收藏代码
  1. The server encountered an internal error that prevented it from fulfilling this request  

 

这里也顺便提一下,假如你的Controller要一个时间对象,代码如下:

Java代码  收藏代码
  1. @SuppressWarnings("deprecation")  
  2. @RequestMapping("/hello.do")  
  3. public String hello(HttpServletRequest request,HttpServletResponse response,  
  4.         @RequestParam(value="userName",defaultValue="佚名") String user,  
  5.         Date dateTest  
  6. ){  
  7.     request.setAttribute("user", user);  
  8.     System.out.println(dateTest.toLocaleString());  
  9.     return "hello";  
  10. }  

 

而网页上实际给的是

Java代码  收藏代码
  1. <input type="text" name="dateTest" value="2015-06-07">  

 

这里需要在Controller增加一个转换器

Java代码  收藏代码
    1. @InitBinder    
    2. public void initBinder(WebDataBinder binder) {    
    3.     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    
    4.     dateFormat.setLenient(false);    
    5.     binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));    
posted @ 2015-03-24 11:29  心潮澎湃  阅读(681)  评论(0编辑  收藏  举报