您的位置:首页 > 编程语言 > Java开发

SpringMVC 表单提交参数不匹配报错

2015-08-21 15:59 405 查看
SpringMVC下,提交表单报400错:

Java代码  

description The request sent by the client was syntactically incorrect.  

 

根据网上的总结,可能是因为如下几个问题引起的

 

1.参数指定问题

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

Java代码  


@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="":

Java代码  

@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:

Java代码  

@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上传的限制

Java代码  

<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.时间转换问题

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

Java代码  

The server encountered an internal error that prevented it from fulfilling this request  

 

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

Java代码  

@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";  

}  

 

而网页上实际给的是

Java代码  

<input type="text" name="dateTest" value="2015-06-07">  

 

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

Java代码  

@InitBinder    

public void initBinder(WebDataBinder binder) {    

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");    

    dateFormat.setLenient(false);    

    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));    

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: