SpringBoot下的SpringMVC

Spring Boot 下的 Spring MVC 和之前的 Spring MVC 使用是完全一样的,主要有以下注解

一、@Controller

Spring MVC 的注解,处理 http 请求

二、@RestController

Spring 4 后新增注解,是@Controller 注解功能的增强
是 @Controller 与@ResponseBody 的组合注解
如果一个 Controller 类添加了@RestController,那么该 Controller 类下的所有方法都相当
于添加了@ResponseBody 注解
用于返回字符串或 json 数据

三、@RequestMapping

支持 Get 请求,也支持 Post 请求

四、@GetMapping

RequestMapping 和 Get 请求方法的组合
只支持 Get 请求
Get 请求主要用于查询操作

五、@PostMapping

RequestMapping 和 Post 请求方法的组合
只支持 Post 请求
Post 请求主要用户新增数据

六、@PutMapping

RequestMapping 和 Put 请求方法的组合
只支持 Put 请求
Put 通常用于修改数据

七、@DeleteMapping

RequestMapping 和 Delete 请求方法的组合
只支持 Delete 请求
通常用于删除数据

八、综合案例

创建一个新项目10-springboot-springmvc,创建方式还是和之前一样

1. 先创建一个model包,里面有Student

package com.md.springboot.model;

/**
 * @author MD
 * @create 2020-08-21 14:46
 */
public class Student {

    private Integer id;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

2. 创建一个web包

package com.md.springboot.web;

import com.md.springboot.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * @author MD
 * @create 2020-08-21 14:47
 */


//@Controller
@RestController //相当于控制层类上加@Controller和方法上加 @ResponseBody,相当于控制层中所有方法返回的都是json对象
public class StudentController {



    @RequestMapping(value = "/student")
//    @ResponseBody
    public Object student(){
        Student student = new Student();
        student.setId(1001);
        student.setName("张三");

        return student;
    }


//  只接受get请求,若是post请求会报405错
//    @RequestMapping(value = "/query" , method = RequestMethod.GET)
    @GetMapping(value = "/query")
    public String get(){
        return "@GetMapping注解,通常查询时使用";
    }



    @PostMapping(value = "/add")
    public String add(){
        return "@PostMapping注解,通常新增时用";
    }


    @PutMapping(value = "/modify")
    public String modify() {
        return "@PutMapping 注解,通常更新数据时使用";
    }


//    @RequestMapping(value = "/remove" , method = RequestMethod.DELETE)
    @DeleteMapping(value = "/remove")
    public String remove() {
        return "@DeleteMapping 注解,通常删除数据时使用";
    }



}

测试

Http 接口请求工具 Postman 介绍

因为通过浏览器输入地址,默认发送的只能是 get 请求,通过 Postman 工具,可以模拟
发送不同类型的请求,并查询结果

原文地址:https://www.cnblogs.com/mengd/p/14181929.html