Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Springboot学习笔记:@Controller、@RestController以及@RequestBody #87

Open
QiYongchuan opened this issue Mar 18, 2024 · 1 comment
Labels
notes notes

Comments

@QiYongchuan
Copy link
Owner

1.@controller@RestController

涉及MVC模型:

MVC模型
  • M:model,模型层,和数据库打交道。《==MyBatis
  • V:view,视图层。用户看到的页面结果。 《== Thymeleafs模板语言/前后端分离项目中返回的数据(多是JSON)
  • C:controller,控制层。实现业务逻辑:数据的处理和页面的跳转。《==Spring MVC

image

控制器中两种注解:

@controller@RestController

image

在前后端分离的项目中,后端主要往前端返回的是数据,所以用RestController,
而在前后端不分离的项目时,多用Controller返回的是页面,结合Thymeleaf使用的,此时是返回页面,寻找的是页面。

@controller 是返回页面和数据的,当我们只用Controller的时候,默认是找的页面,比如下面是找hello页面了(前后端 不分离的项目)
image

如果想返回数据,而不是页面呢?
需要加上@RequestBody

image

@RestController=@controller@responsebody的结合

当你使用@RestController注解时,Spring会自动处理你的类中的所有方法,使其返回的数据直接作为HTTP响应的正文返回给客户端,而不需要你在每个方法上单独标注@responsebody

@RestController注解是@controller@responsebody的结合,这意味着它既将类标记为控制器,又表明类中的所有方法都会自动以@responsebody的方式处理。这使得@RestController非常适合用于构建RESTful API,其中所有的响应都是数据(如JSON或XML),而不是视图或模板页面。

这种方式简化了开发过程,因为你不需要在每个方法上重复使用@responsebody注解,从而让代码更加简洁和直观。总的来说,如果你的应用主要是服务于HTTP API的,使用@RestController会更方便。

前后端分离项目中,主要使用的就是:@RestController

@QiYongchuan
Copy link
Owner Author

@requestbody 的另一处作用:前端传递JSON数据时的解析

前面讲到,@requestbody 结合@controller 一起使用,使控制器返回数据,而不是页面;但更多的时候,我们直接使用@RestController,就省掉了用@requestbody。似乎我们在前后端分离的项目中之后就再也不用@requestbody了,但@requestbody还有别的作用。

一句话总结:当通过请求体body来传值时,就需要用@requestbody

@RequestMapping("/Entiy2")   
    // 如果前端传递的参数是json格式的,
    // 使用@RequestBody来解析
    public String entity2(@RequestBody User user){
        System.out.println(user);
        return "实体类接收参数Json";
    }

前端传值JSON形式
image

image
image

@QiYongchuan QiYongchuan changed the title Springboot学习笔记:@Controller、@RestController以及@RequestMapping Springboot学习笔记:@Controller、@RestController以及@RequestBody Mar 18, 2024
@QiYongchuan QiYongchuan added the notes notes label Mar 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
notes notes
Projects
None yet
Development

No branches or pull requests

1 participant