2019/4/10
问题描述
在web.xml中配置好过滤器,代码如下:
<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>
然后再jsp页面写好提交表单的代码:
form action="SpringMVCHandler/testDelete/1234" method="post">
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="删">
</form>
<form action="SpringMVCHandler/testPut/1234" method="post">
<input type="hidden" name="_method" value="PUT"/>
<input type="submit" value="改">
</form>
<form action="SpringMVCHandler/testPost/1234" method="post">
<input type="submit" value="增">
</form>
<form action="SpringMVCHandler/testGet/1234" method="get">
<input type="submit" value="查">
</form>
之后在springMVCHandler类中:
@RequestMapping(value="testPost/{id}")
public String testPost(@PathVariable("id") Integer id)
{
System.out.println("post:增" + id);
return "success";
}
@RequestMapping(value="testGet/{id}")
public String testGet(@PathVariable("id") Integer id)
{
System.out.println("get:查" + id);
return "success";
}
@RequestMapping(value="testDelete/{id}")
public String testDelete(@PathVariable("id") Integer id)
{
System.out.println("delete:删" + id);
return "success";
}
@RequestMapping(value="testPut/{id}")
public String testPut(@PathVariable("id") Integer id)
{
System.out.println("put:改" + id);
return "success";
}
结果报错在提交DELETE方法和PUT方法时报错:JSPs only permit GET POST or HEAD
并且控制台能够正确输出id。
解决思路
经过反复核对,可以确定web.xml配置,jsp页面以及springMVCHandler类都没错误,并且控制台能够正确输出,说明已经接收到了DELETE或者PUT,并且能够执行对应的test()方法,但是在跳转页面到“success.jsp”这一步出现了问题,所以我们应该修改success.jsp中的错误代码。
解决方法
1.如果在springMVCHandler类中对应方法需要跳转到一个jsp页面(本例中是success.jsp),需要在该jsp页面"isErrorPage"设置为"true",修改后代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isErrorPage="true"%>
2。如果在springMVCHandler类中对应方法需要返回一个字符串,则只需在接收DELETE和PUT方法的@RequestMapping之前添加@ResponseBody,修改后代码如下
@ResponseBody
@RequestMapping(value="testDelete/{id}")
public String testDelete(@PathVariable("id") Integer id)
{
System.out.println("delete:删" + id);
return "XXXX";
}
@ResponseBody
@RequestMapping(value="testPut/{id}")
public String testPut(@PathVariable("id") Integer id)
{
System.out.println("put:改" + id);
return "XXXX";
}