REST风格的URI——Ajax的PUT请求

本文探讨了在使用Ajax发送PUT请求时遇到的数据传输问题,详细分析了为什么TOMCAT默认不封装PUT请求体中的数据为map,以及如何通过配置HttpPutFormContentFilter解决这一问题,确保数据正确传递至SpringMVC控制器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置

<!-- 使用Rest风格的URI ,将页面普通的post请求转为指定的delete或者put请求-->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

PUT

controller

	@RequestMapping(value="/emp/{empId}",method=RequestMethod.PUT)
	@ResponseBody
	public Msg saveEmp(Employee employee) {
		System.out.println(employee);
		service.updateEmp(employee);
		return Msg.success();
	}
	

ajax

			$.ajax({
				url:"${APP_PATH}/emp/"+$(this).attr("edit-id"),
				type:"POST",
				data:$("#empUpdateModal form").serialize()+"&_method=PUT",
				success:function(result){
					alert(result.msg);
				}
			});

当我们在ajax中直接使用PUT时

			$.ajax({
				url:"${APP_PATH}/emp/"+$(this).attr("edit-id"),
				type:"PUT",
				data:$("#empUpdateModal form").serialize(),
				success:function(result){
					alert(result.msg);
				}
			});

controller中接受不到数据

Employee [empId=1005, empName=null, gender=null, email=null, dId=null, department=null]

但是在浏览器中查看请求的时候,请求体中已经带上了对应的数据

controller并没有将这些数据封装到POJO中,就算使用原生的request.getParameter()方法获取到的也是null


正常的情况下tomcat会把请求体中的数据封装成一个map,request.getParameter("empName")可以从map中取值,

而SpringMVC在封装POJO对象时,会自动把POJO中每个属性的值都调用request.getParameter()来获取

当ajax直接发送PUT请求,request.getParameter都拿不到数据是因为:

TOMCAT一看是PUT请求就不会封装请求体中的数据为map,只有POST形式的请求才封装请求体为map

具体的源代码在tomcat的org.apache.catalina.connector.Request下的parseParameters()方法中,并没有去详细了解

 

----------------------------------------------------------------------人工分割线------------------------------------------------------------------------------------

解决Ajax直接发送PUT请求出现的问题

在web.xml中添加Filter,HttpPutFormContentFilter好像是SpringMVC自带的

	<filter>
		<filter-name>HttpPutFormContentFilter</filter-name>
		<filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HttpPutFormContentFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

HttpPutFormContentFilter的作用就是将请求体中的数据解析包装成一个map,重新包装request,重写request.getParameter()

 

--------------------------------------------------------------------------------------------------------------------------------------------------------------------

URI
• /emp/{id} GET 查询员工
• /emp       POST 保存员工
• /emp/{id} PUT 修改员工
• /emp/{id} DELETE 删除员工
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值