第一步:在 web.xml 中配置该过滤器。
web.xml配置
<!-- rest 请求方式 PUT GET POST 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>
第二步:请求方式必须使用 post 请求。
按照要求提供_method 请求参数,该参数的取值就是我们需要的请求方式
<h2>rest风格 </h2>
<h6>注册添加 Post</h6>
<form action="${pageContext.request.contextPath}/users" method="post">
name:<input type="text" name="name" value="tom"><br/>
password:<input type="password" name="password" value="123"><br/>
birthday : <input type="date" name="birthday" value="1999-02-12"><br/>
<input type="submit" value="注册用户">
</form>
<h6>获取 get</h6>
<form action="${pageContext.request.contextPath}/users/1" method="get">
<input type="submit" value="查询"/>
</form>
<h6>修改 PUT</h6>
<form action="${pageContext.request.contextPath}/users/1" method="post">
<input type="hidden" name="_method" value="PUT"> <!-- 修改 -->
name:<input type="text" name="name" value="tom1"><br/>
password:<input type="password" name="password" value="12311"><br/>
birthday : <input type="date" name="birthday" value="1999-02-22"><br/>
<input type="submit" value="修改"/>
</form>
<h6>删除 DELETE</h6>
<form action="${pageContext.request.contextPath}/users/1" method="post">
<input type="hidden" name="_method" value="DELETE"> <!-- 修改 -->
<input type="submit" value="删除"/>
</form>
第三步:
@Controller("restController")
public class restController {
@RequestMapping(value = "/users",method = RequestMethod.POST)
public String add(User user){
System.out.println(user);
System.out.println("POST 添加 ");
return "success" ;
}
//PathVariable 参数占位
@RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
public String get(@PathVariable("id") Integer uid) {
System.out.println(uid);
User user = new User();
user.setName("tomcat");
user.setUid(2);
user.setPassword("456");
user.setBirthday(new Date());
System.out.println(user);
System.out.println("GET 获取");
return "success" ;
}
@RequestMapping(value = "/users/{id}",method = RequestMethod.PUT) //修改
public String put(@PathVariable("id") Integer uid,User user) {
System.out.println(uid);
System.out.println(user);
System.out.println("PUT修改");
return "success" ;
}
@RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE) //删除
public String delete(@PathVariable("id") Integer uid) {
System.out.println(uid);
System.out.println("DELETE删除");
return "success" ;
}
}