Springboot中的Controller

(37条消息) 详解Spring boot中Controller用法_呆小呆啊的博客-CSDN博客_springboot中controller

(37条消息) spring mvc注解@RequestMapping的作用及属性_骑着蜗牛@you的博客-CSDN博客_@requestmapping注解的作用及用法

Controller

1、作用

Controller是SpringBoot的基本组件,也是MVC结构的组成部分,其作用是将用户提交来的请求通过URL匹配分发给不同的接收器(具体的Controller),该接收器会对其进行相应处理,然后返回处理结果

2、基本样式

一个经典的Controller类似下边这样:

 

package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/api/user")
public class IndexController {
  @RequestMapping(value = {"index", "/"})
  public String index(Model model) {
    return "index";
  }
}

 

3、说明

@Controller

写于Controller类之前;

告知Spring容器这是一个Controller。

@RequestMapping

写于Controller类或Controller类中的某个方法之前;

表示这个类/方法负责处理哪个URL

Model model

处理URL的方法需要传入Model参数;

该参数的作用是向Model传递数据;

Model将来会传递给View显示出来。

return "index"

return "/registerResult"

函数返回值,表示要访问的文件名。

具体后缀取决于模板引擎,比如对于jsp就需要访问"index.jsp"文件

   
   
   
   

 

4、@RequestMapping

作用

告诉Spring该方法或类是用于映射到哪个URL的,通常情况下可以添加如下信息:

@RequestMapping(
    value = "/test",
    params = {"name","userId"},
    method = {RequestMethod.GET},
    consumes = {"text/plain", "application/*"},
    produces = "text/plain",
    headers = "content-type=text/*"
)

分别表示

  • value:路径,类似"/action/info"这种;
  • params:参数;
  • method:请求方法——GET、POST、PUT……;
  • consumes:request请求提交的内容类型(Content-Type);
  • produces:返回内容的类型;
  • headers:Header等。

通常只需要value,有时可能会用到method表示请求方法,默认是RequestMethod.GET,有时可能是RequestMethod.POST

 

当注解作用于类时,类中所有方法都会在这个基础上再进行过滤。例如:

 

@Controller
@RequestMapping("/path1")
public class TestController {
  @RequestMapping("/path2")
  @ResponseBody
  public String index() {
    return "ok";
  }
}

 

这个函数就会匹配"/path1/path2"这个地址

 

posted @ 2022-06-30 15:42  ShineLe  阅读(5666)  评论(0编辑  收藏  举报