restful风格即请求路径相同,但请求方法不同,从而做出不同响应的处理方式。 增、删、改、查分别对应方法:post、delete、put、get,由于浏览器可以支持post、get却不支持delete和put,所以需要进行如下处理。 1、利用HiddenHttpMethodFilter过滤器,对所有请求进行操作,欺骗浏览器。
<!--put、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>2、如下,在前端页面中,对浏览器不支持的删除和修改指令中,加入隐藏域,内部设置“_method”和对应值“delete/put”,程序运行后,上面的过滤器会直接寻找下面的“_method”内对应的请求方法。
<form action="${pageContext.servletContext.contextPath}/anime/ai" method="post"> <input type="hidden" name="_method" value="delete"> <button>删</button> </form> <form action="${pageContext.servletContext.contextPath}/anime/ai" method="post"> <input type="hidden" name="_method" value="PUT"> <button>改</button> </form>3、controller中加入对应方法
@RequestMapping(path = "/ai",method = RequestMethod.DELETE) public String aiDelete(){ System.out.println("删除"); return "delete"; } @RequestMapping(path = "/ai",method = RequestMethod.PUT) public String aiPut(){ System.out.println("修改"); return "put"; }4、需要在tomcat7开启本项目,则在pom文件中加入下面信息,强制tomcat7开启
<build> <!--maven插件--> <plugins> <!--jdk编译插件--> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>utf-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <!-- 指定端口 --> <port>8081</port> <!-- 请求路径 --> <path>/</path> </configuration> </plugin> </plugins> </build>在maven项目插件中,启动tomcat7,tomcat8是不支持delete和put这两种请求方法的。
