zoukankan      html  css  js  c++  java
  • spring mvc-REST

    https://www.cnblogs.com/caoyc/p/5635354.html

    REST风格:

    /user/1  get请求  获取用户

    /user/1  post请求  新增用户

    /user/1  put请求  更新用户

    /user/1  delete请求  删除用户

    在Spring mvc中如何提交put和delete请求呢?

    需要在web.xml中配置一个HiddenHttpMethodFilter过滤器。该过滤器过滤post请求,如果在post请求中有一个_method参数,那么_method参数值就是请求方式。所以在jsp页面可以这样写:

    <a href="user/1">GET请求</a> <!-- 默认调用user中第一个方法,即为get??? -->
    
    <form action="user/1" method="post">
        <input type="submit" value="POST请求"/>
    </form>
    
    <form action="user/1" method="post">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="PUT请求"/>
    </form>
    
    <form action="user/1" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="DELET请求"/>
    </form>

    web.xml配置过滤器:

    <filter>
        <filter-name>methodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>methodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    控制器:

    package com.proc;
    
    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 User {
    
        @RequestMapping(value="user/{id}",method=RequestMethod.GET)
        public String get(@PathVariable("id") Integer id){
            System.out.println("获取用户:"+id);
            return "hello";
        }
        
        @RequestMapping(value="user/{id}",method=RequestMethod.POST)
        public String post(@PathVariable("id") Integer id){
            System.out.println("添加用户:"+id);
            return "hello";
        }
        
        @RequestMapping(value="user/{id}",method=RequestMethod.PUT)
        public String put(@PathVariable("id") Integer id){
            System.out.println("更新用户:"+id);
            return "hello";
        }
        
        @RequestMapping(value="user/{id}",method=RequestMethod.DELETE)
        public String delete(@PathVariable("id") Integer id){
            System.out.println("删除用户:"+id);
            return "hello";
        }
    }

    我们一次点击GET请求、POST请求、PUT请求和DELETE请求:

    获取用户:1
    添加用户:1
    更新用户:1
    删除用户:1

    总结:发出PUT请求和DELETE请求的步骤:

    1、在发出请求时必须是POST请求;

    2、在POST请求中添加一个名为_method的参数,其值用来指定是PUT请求还是DELETE请求;

    3、配置HiddenHttpMethodFilter过滤器。该过滤器的作用是POST请求可以转换成PUT或DELETE请求。

  • 相关阅读:
    你笑的时候真的很美
    我不会倒下
    创业靠的是“脑子”,教你如何运用谋略事半功倍~
    其实我真的很在乎你
    让你克服低效率的困扰:从实质上迅速提升你生活的方法
    沈科(帮别人名字作诗)
    Secrets of the NetBeans Window System
    PropertyUtils.copyProperties的性能
    Swing Threading的限制
    SwingSet2
  • 原文地址:https://www.cnblogs.com/arrows/p/10523037.html
Copyright © 2011-2022 走看看