RESTFull风格的springmvc遇到的问题

最近在学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()注解 问题得到解决





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值