【SpringBoot】Rest映射及自定义_method

161 阅读1分钟

本文已参与[新人创作礼]活动,一起开启掘金创作之路。

 【Rest映射】 

​编辑

HelloController.java

package com.you.boot.boot.Controller;

import com.you.boot.boot.bean.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Autowired
    Person person;

    @RequestMapping("/person")
    public Person person()
    {
        return  person;
    }

    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String getUser()
    {
        return "GET-张三";
    }
    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String saveUser()
    {
        return "POST-张三";
    }
    @RequestMapping(value = "/user",method = RequestMethod.PUT)
    public String putUser(){
        return "PUT-张三";
    }
    @RequestMapping(value = "/user",method = RequestMethod.DELETE)
    public String deleteUser()
    {
        return "DELETE-张三";
    }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>在下济北公游坦之</h1>
    <form action="/user" method="get">
        <input value="REST-GET 提交" type="submit">
    </form>
    <form action="/user" method="post">
        <input value="REST-POST 提交" type="submit">
    </form>
    <form action="/user" method="put">
        <input value="REST-PUT 提交" type="submit">
    </form>
    <form action="/user" method="delete">
        <input value="REST-DELETE 提交" type="submit">
    </form>
</body>
</html>

效果

​编辑

​编辑

分析:PUT和DELETE显示的全是Get,原因是下面这两个都会默认当成Get方式

​编辑

 处理Put和Delete

开启hiddenmethod功能

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true

​编辑

修改上面代码如下(此处delete、put可以用大写或者小写,最终会在底层转化成大写)

<form action="/user" method="post">
   <input name="_method" type="hidden" value="put">
   <input value="REST-PUT 提交" type="submit">
</form>
<form action="/user" method="post">
   <input name="_method" type="hidden" value="delete">
   <input value="REST-DELETE 提交" type="submit">
</form>

【效果】

​编辑

 RestMapping简写

@RequestMapping(value = "/user",method = RequestMethod.GET) === @GetMapping("/user")

红色的那一行就等于蓝色的那一行

​编辑

​编辑 其他同理

****​编辑

 自定义_method

​编辑

methodFilter.setMethodParam("_ytz");括号里面写自己想改的
package com.you.boot.boot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;

@Configuration(proxyBeanMethods = false)
public class WebConfig {
    @Bean
    public HiddenHttpMethodFilter hiddenHttpMethodFilter()
    {
        HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
        methodFilter.setMethodParam("_ytz");
        return methodFilter;
    }
}

​编辑