标签:tty 浏览器 导致 .com delete rest 区分 var mapping
1、需要在web.xml中开启put,和delete的支持
<!-- 浏览器不支持put,delete等method,由该filter将/xxx?_method=delete转换为标准的http delete方法 -->
<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>
2、务必导入jackson的jar包

3、jqery发送AJax到springmvc,需要的是json标准格式的字符串,而非json对象,所以得先转成字符串,涉及的发送AJax的几处坑如下:
|
SpringMVC发送ajax 一般采用$.ajax()方法进行数据发送,主要是因为$.post()方法发送数据的形式得是json对象格式,而$.ajax()方法可以发送字符串形式json,,另外使用springmvc的ajax功能千万记得导入jackson的2.4版本以上的包,不然报406的错误,采用$.ajax()方法需要注意的几个坑是:
|
其中,发送AJax的contentType 为发送过去的格式,dataType为接收时让jqery转换的格式,一定得指定让其可以正常转换的格式才行,不然不会报错,但是也没有成功的回调响应
4、代码实现:
①、服务端,默认可以不写produces={"application/json;charset=utf-8"},produces是指定响应回客户端的json格式编码,除非返回格式解析乱码:
@RequestMapping(value="/submit",method=RequestMethod.DELETE,produces={"application/json;charset=utf-8"}) public @ResponseBody User submit1(@RequestBody User u) { System.out.println(u); return new User("004","jerry"); } @RequestMapping(value="/submit",method=RequestMethod.POST) public @ResponseBody User submit2( @RequestBody User u) { System.out.println(u); return new User("003","jerry"); }
②、客户端:
<script type="text/javascript">
$(function() {
$("#btn1").click(function() {
var obj = {
uid : 1,
name : ‘jerry1‘
};
$.ajax({
url : ‘${pageContext.request.contextPath}/submit?_method=delete‘,
type : ‘post‘,
data : JSON.stringify(obj),
contentType : ‘application/json;charset=utf-8‘,
dataType : ‘json‘,
success : function(data) {
alert(data.uid);
}
});
});
$("#btn2").click(function() {
var obj = {
uid : 2,
name : ‘jerry2‘
};
$.ajax({
url : ‘${pageContext.request.contextPath}/submit‘,
type : ‘post‘,
data : JSON.stringify(obj),
contentType : ‘application/json;charset=utf-8‘,
dataType : ‘json‘,
success : function(data) {
alert(data.uid);
}
});
});
});
</script>
客户端通过url参数区分RestFull方法,服务端通过RequestMethod来进行限制
标签:tty 浏览器 导致 .com delete rest 区分 var mapping
原文地址:http://www.cnblogs.com/javabg/p/7277387.html