在写jsp form表单时,我们可以发现只有post和get请求,但是在发送请求的时候有不同的请求方式,能不能通过请求方式来做一次转换,将不一样的请求作为不一样的数据处理。
POST 新增 /user
GET 获取 /user
PUT 更新 /user/1
DELETE 删除 /user/1
1、Controller中,通过注解@RequestMapping在method属性添加请求方式
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String save(){
System.out.println(this.getClass().getName()+"save");
userDao.save(new User());
return "success";
}
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String update(Integer id){
System.out.println(this.getClass().getName()+"update");
userDao.update(id);
return "success";
}
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
public String delete(Integer id){
System.out.println(this.getClass().getName()+"delete");
userDao.delete(id);
return "success";
}
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String query(){
System.out.println(this.getClass().getName()+"query");
userDao.query();
return "success";
}
2、通过请求方式method可以看到请求有许多中,但是如何将他们用post或get请求来表示呢。
HiddenHttpMethodFilter
类可以实现将post转化为put、delete请求
在web.xml中添加
<!--此过滤器完成请求方式的转换,将post请求方式转换为delete或put的转换-->
<filter>
<filter-name>hidden</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hidden</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
进入HiddenHttpMethodFilter
源码,可以看到他的默认方法参数时_method
请求是post时才能进入doFilterInternal()方法
3、在jsp中添加请求
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/3/5
Time: 16:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
pageContext.setAttribute("ctp",request.getContextPath());
%>
<html>
<head>
<title>Rest规范测试</title>
</head>
<body>
<form action="${ctp}/user/" method="post">
<input type="submit" value="增加">
</form>
<form action="${ctp}/user/" method="post">
<input name="_method" value="delete" type="hidden">
<input type="submit" value="删除">
</form>
<form action="${ctp}/user/" method="post">
<input name="_method" value="put" type="hidden">
<input type="submit" value="修改">
</form>
<a href="${ctp}/user/">查询</a><br/>
</body>
</html>