编写的SpringMVC服务器端来获取通过html表单提交的参数时候时候,如果是GET方式服务端能够接收到参数的值,如果是POST方式,则接收不到参数的值,代码如下
jsp:
- <form id="itemForm" action="${pageContext.request.contextPath }/items/editItemsSubmit.action" method="post" enctype="multipart/form-data">
- <input type="hidden" name="id" value="${itemsCustom.id }"/>
- 修改商品信息:
- <table width="100%" border=1>
- <tr>
- <td>商品名称</td>
- <td><input type="text" name="name" value="${itemsCustom.name }"/></td>
- </tr>
- <tr>
- <td>商品价格</td>
- <td><input type="text" name="price" value="${itemsCustom.price }"/></td>
- </tr>
- <%-- <tr>
- <td>商品生产日期</td>
- <td><input type="text" name="createtime" value="<fmt:formatDate value="${items.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
- </tr>
- --%>
- <tr>
- <td>商品图片</td>
- <td>
- <c:if test="${items.pic !=null}">
- <img src="/pic/${items.pic}" width=100 height=100/>
- <br/>
- </c:if>
- <input type="file" name="items_pic"/>
- </td>
- </tr>
- <tr>
- <td>商品简介</td>
- <td>
- <textarea rows="3" cols="30" name="detail">${itemsCustom.detail }</textarea>
- </td>
- </tr>
- <tr>
- <td colspan="2" align="center"><input type="submit" value="提交"/>
- </td>
- </tr>
- </table>
- </form>
SpringMVC:
- @RequestMapping("/items/editItemsSubmit")
- public String editItesmSubmit(HttpServletRequest request,Integer id,ItemsCustom itemsCustom) throws Exception
最后发现,这是form表单的enctype编码方式不同导致的
enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。
默认地,表单数据会编码为 "application/x-www-form-urlencoded"。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。如果使用GET,则强制使用application/x-www-form-urlencoded"方式。我代码里强制使用了multipart/form-data方式,所以SpringMVC中获取不到POST形式的参数
spring mvc如果要接收 multipart/form-data 传输的数据,应该在spring上下文配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
并将commons-fileupload-1.2.1.jar和commons-io-2.5.jar包引入到项目中
这样服务端就既可以接收multipart/form-data 传输的数据,也可以接收application/x-www-form-urlencoded传输的文本数据了。