程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-06(4)

SpringBoot下的SpringMVC

发布于2020-12-29 08:01     阅读(1087)     评论(0)     点赞(29)     收藏(3)


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



所属网站分类: 技术文章 > 博客

作者:javajava我最强

链接:http://www.javaheidong.com/blog/article/45647/a64b50983f3732407111/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

29 0
收藏该文
已收藏

评论内容:(最多支持255个字符)