概述
简单理解:对一个资源的增删改查用请求方式来区分:
- /book/1 GET:查询1号图书
- /book/1 DELETE:删除1号图书
- /book/1 PUT:修改1号图书
- /book POST:新增图书
实验步骤
编写 jsp页面
<%--发起图书的增删改查--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%-- /book/1 get:查询图书--%>
<%-- /book/1 delete:删除图书--%>
<%-- /book/1 put:修改图书--%>
<%-- /book get:添加图书--%>
<a href="book/1">查询图书</a><br>
<form action="book" method="post">
<input type="submit" value="添加图书">
</form><br>
<form action="book/1" method="post">
<input type="hidden" name="_method" value="delete">
<input type="submit" value="删除图书">
</form><br>
<form action="book/1" method="post">
<input type="hidden" name="_method" value="put">
<input type="submit" value="修改图书">
</form><br>
</body>
</html>
在web.xml中配置一个filter:HiddenHttpMethodFilter过滤器
<!-- 配置rest风格的过滤器-->
<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>
servlet层的代码
package com.yicurtain.servlet;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class bookController {
@RequestMapping(value = "/book/{bid}",method = RequestMethod.GET)
public String getBook(@PathVariable("bid")Integer id){
System.out.println("查询到了"+id+"号图书");
return "success";
}
@RequestMapping(value = "/book",method = RequestMethod.POST)
public String addBook(){
System.out.println("添加到了图书");
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.DELETE)
public String deleteBook(@PathVariable("bid") Integer id){
System.out.println("删除到了"+id+"号图书");
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.PUT)
public String updateBook(@PathVariable("bid") Integer id){
System.out.println("更新到了"+id+"号图书");
return "success";
}
}
注意事项
高版本Tomcat会出现问题:JSPs only permit GET POST or HEAD,在在跳转之后的(success.jsp)页面上加上异常处理即可.
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>