最近在学springmvc 刚好把遇到的问题总结一下
首先在web.xml中配置HiddenHttpMethodFilter(用于将POST请求转换为DELETE请求或PUT请求):
<span style="white-space:pre"> </span><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>
下面在index.jsp页面中添加如下测试代码:
<form action="rest/user/1" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="submit" value="PUT">
</form>
<br><br>
<form action="rest/user" method="post">
<input type="submit" value="POST">
</form>
<br><br>
<a href="rest/user/1">GET</a>
<br><br>
<form action="rest/user/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="DELETE">
</form>
下面编写控制器代码RestController.java:
@Controller
@RequestMapping("/rest")
public class RestController {
@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
public String get(@PathVariable("id") Integer id){
System.out.println("get"+id);
return "hello";
}
@RequestMapping(value="/user",method=RequestMethod.POST)
public String post(){
System.out.println("post");
return "hello";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
public String put(@PathVariable Integer id){
System.out.println("put"+id);
return "hello";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
public String delete(@PathVariable Integer id){
System.out.println("delete"+id);
return "hello";
}
这里点击GET或者POST链接都能正常跳转
但是点击PUT或者DELETE链接会出现以下错误:
因为所有的步骤我都是按照例子来的 出现这样的错误很让人费解 google了很久 有人说是tomcat8的原因,网上很多人是通过转发解决这个问题,下面给出第二种解决方法:
@RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
@ResponseBody()
public String put(@PathVariable Integer id){
System.out.println("put"+id);
return "hello";
}
@RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
@ResponseBody()
public String delete(@PathVariable Integer id){
System.out.println("delete"+id);
return "hello";
}
将RestController.java中处理put和delete请求的代码改为以上所示,即加上@ResponseBody()注解 问题得到解决