都是Restful 风格的错
Rest风格的URL
以CRUD为例
新增:/order POST
修改:/order/1 PUT update?id=1
获取:/order/1 GET get?id=1
删除:/order/1 DELETE delete?id=1
Form表单
配置HiddenHttpMethodFilter
,表单才支持把POST
请求转为 DELETE
和 PUT
配置HttpPutFormContentFilterb
则是支持put
请求,我在测试ajax
传递参数时,Controller
获取不到参数,就是缺少这个过滤器。
<!-- 配置 HiddenHttpMethodFilter 可以把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>
<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>
html
测试4种请求
<a href="springmvc/testRest/1">Test Rest GET</a><br>
<form action="springmvc/testRest" method="post">
<input type="submit"value="Test Rest POST"/>
</form><br>
<form action="/springmvc/testRest/2" method="post">
<input type="hidden" name="_method" value="delete"/>
<input type="submit" value="Test Rest DELETE"/>
</form> <br>
<form action="/springmvc/testRest/3" method="post">
<input type="hidden" name="_method" value="put"/>
<input type="submit"value="Test Rest PUT"/>
</form>
注意:Tomcat8.0 或者 web.xml 3.1 好像不支持put和 delete,我不确定,你找资料看一下
Controller
...
@RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
public String testRest(@PathVariable Integer id){
System.out.println("testRest GET"+id);
return SUCCESS;
}
@RequestMapping(value="/testRest",method=RequestMethod.POST)
public String testRestPOST(){
System.out.println("testRest POST");
return SUCCESS;
}
@RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
public String testRestDELETE(@PathVariable Integer id){
System.out.println("testRest DELETE"+id);
return SUCCESS;
}
@RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
public String tesPUTt(@PathVariable Integer id){
System.out.println("testRest PUT"+id);
return SUCCESS;
}
Ajax 请求
web.xml
同上,需要配置HiddenHttpMethodFilter
和HttpPutFormContentFilterb
jsp
var form = $('#updateform');
//发送ajax请求
$.ajax({
url:'你的请求',
async:false,//同步,会阻塞操作
type:'put',
timeout:1000,
data:form.serialize(),//这里的数据为表单数据
success:function (result) {
console.log(result);//输出返回结果
if(result['success']){
//请求成功
window.location.reload();
}else{
//请求失败
}
},error:function () {
//请求失败
}
})
Controller
@RequestMapping(value = "/映射的请求民", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
@ResponseBody
public Map updatemsg( User user) {
Map map = new HashMap();
boolean result = true;
int count = xxx逻辑;
if (count == 0) {
//更新失败
result = false;
}
map.put("success", result);
return map;
}
完整的 Ajax 表单例子>>