Fork me on GitHub

SpringMVC---RESTful中put和delete实现

SpringMVC———RESTful中put和delete实现

HiddenHttpMethodFilter:浏览器form表单只支持GET和POST请求,不支持DELETE、PUT请求,Spring添加了一个过滤器,可以将这些请求转换为标准的http方法,支持GET、POST、PUT和DELETE请求。

实现过程:

配置过滤器
1
2
3
4
5
6
7
8
<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>
实现list页面
1
2
3
4
5
6
//Controller代码
@RequestMapping(value="/list",method=RequestMethod.GET)
public String list()
{
return "user/list";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
//list.jsp代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>用户列表</h1>
</body>
</html>
实现删除功能
1
2
3
4
5
6
7
8
//Controller代码
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public String delete(HttpServletRequest request )
{
System.out.println("delete");
//执行删除
return "redirect:/user/list";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
//jsp代码
<!-- 删除操作 -->
<a href="javascript:void(0)" onclick="deleteById()">删除</a>
<form action="1" method="post" id="deleteForm">
<input type="text" name="_method" value="DELETE" />
<button>DELETE提交</button>
</form>
<script>
function deleteById()
{
document.getElementById('deleteForm').submit();
}
</script>
实现更新功能
1
2
3
4
5
6
7
8
//Controller代码
@RequestMapping(value="/{id}",method=RequestMethod.PUT)
public String update(HttpServletRequest request )
{
System.out.println("update");
//执行更新
return "redirect:/user/list";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
//jsp代码
<!-- 更新操作 -->
<a href="javascript:void(0)" onclick="updateById()">修改</a>
<form action="1" method="post" id="updateForm">
<input type="text" name="_method" value="PUT" />
<button>PUT提交</button>
</form>
<script>
function updateById()
{
document.getElementById('updateForm').submit();
}
</script>