掘金日新计划 · 8 月更文挑战第37天--RESTful简单请求和复杂请求

79 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第37天,点击查看活动详情

简单请求和非简单请求是什么
基本逻辑:Spring mvc原来只能接受POST和GET方法,后来新增了PUT和DELETE方法 为了能够处理PUT和DELETE这种非简单请求,Spring MVC可以通过FormContentFilter过滤器,来解决这个需求

1.简单请求 GET POST

创建entity包并且创建实体类Person

package com.imooc.restful.controller.entity;

public class Person {
    private Integer age;
    private  String name;

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

代码说明: Person实体类有两个私有变量,name和age,创建getter和setter方法 控制器方法

//简单请求
@PostMapping("/post")
//@ResponseBody
public String doPost(Person person){
    System.out.println(person.getName());
    return person.getName();
}

代码说明: @PostMapping("/post") 表示该请求为post方法 静态文件请求

<input type="button" id="btnPost" value="简单请求">
<h1 id="btnPostText"></h1>
$(function () {
    $("#btnPost").click(function () {
        $.ajax({
            url:"/restfull/post",
            type:"post",
            dataType:"json",
            data:"name=lily&age=10",
            success:function (res) {
                $("#btnPostText").text(res.message)
            }
        })
    })
})

代码说明:

  • $("#btnPost").click(function ())表示btnPost按钮绑定点击事件
  • data:表示post请求的参数
  • $("#btnPostText").text(res.message):表示把成功之后的返回值追加到tnPostText image.png 获取返回参数 image.png

2.复杂请求 PUT

html代码

<input type="button" id="btnPut" value="复杂请求">
<h1 id="btnPutText"></h1>

js方法

$(function () {
    $("#btnPut").click(function () {
        $.ajax({
            url:"/restfull/put",
            type:"put",
            data: "name=lily&id=85",
            dataType:"json",
            success:function (res) {
                $("#btnPutText").text(res.message)
            }
        })
    })
})

控制器

//复杂请求
@PutMapping("/put")
//@ResponseBody
public String doPut(Person person){
    System.out.println(person.getName());
    return person.getName();
}

image.png 发现打印为null image.png 如何解决呢:
我们在restfull\src\main\webapp\WEB-INF\web.xml新增配置

<filter>
    <filter-name>formContentFilter</filter-name>
    <filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>formContentFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

重启服务 image.png