隶属文章: Java高级 | (二十二)Java常用类库-CSDN博客
系列文章: Java高级 | 【实验一】Spring Boot安装及测试 最新-CSDN博客
目录
一、MVC模式
二、SpringBoot基础——控制层Controller详解
(一)主要工作
(二)重要注解
1、@Controller
2、@RequestMapping
(1)注解在方法上
(2)注解在类和方法上
(3)处理 HTTP 的各种方法
(4)处理多个 URI
(5)带 @RequestParam
(6) header属性处理消息头
(7)params属性处理请求参数
(8) 处理动态 URI
3、@ResponseBody
4、@RestController
5、@RequestMapping
6、@PostMapping
7、@GetMapping注解
一、MVC模式
MVC(Model View Controller)是软件开发的一种思想,他把软件系统分为 以下三部分:
- Model(模型):用来处理程序中数据逻辑的部分
- View(视图):在应用程序中,专门和浏览器进行交互,展示数据的资源
- Contreller(控制器):负责协调视图和模型之间的交互,主要功能是处理视图发来的请求。即,根据请求决定使用用哪一个模型来处理,以及处理完后需要跳回到哪一个视图,也就是用来连接视图和模型的。
SpringBoot 是实现 SpringMVC 的一种方式,SpringMVC 将MVC思想进行了实现
二、SpringBoot基础——控制层Controller详解
测试 :localhost:8080/hello
(一)主要工作
从HTTP请求中获取信息,提取参数,并将其分发给不同的处理服务(service层),并向前端返回service层处理后的数据(JSON数据或者ModelAndView对象)。
(二)重要注解
Controller层主要包含了以下6个注解。
- @Controller
- @RequestMapping
- @ResponseBody
- @RestController
- @GetMapping
- @PostMapping
1、@Controller
标识一个Java 类是一个控制器。
2、@RequestMapping
告知Spring的控制器类或者函数映射到哪个URL,通常@RequestMapping参数有:
(1)注解在方法上
package controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class UserController {// 映射到方法上// localhost:8080/user/login@RequestMapping("/user/login")public String login() {return "user login";}// localhost:8080/user/register@RequestMapping("/user/register")public String register() {return "user register";}
}
(2)注解在类和方法上
package controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;@Controller
//@RestController
@ResponseBody
@RequestMapping("/user")
public class UserController {@RequestMapping("/login")public String login() {return "user login";}@RequestMapping("/register")public String register() {return "user register";}
}
(3)处理 HTTP 的各种方法
声明HTTP请求所使用的方法类型。
package controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/home")
public class IndexController {@RequestMapping(method = RequestMethod.GET)public String get() {return "Hello from get";}@RequestMapping(method = RequestMethod.DELETE)public String delete() {return "Hello from delete";}@RequestMapping(method = RequestMethod.POST)public String post() {return "Hello from post";}@RequestMapping(method = RequestMethod.PUT)public String put() {return "Hello from put";}@RequestMapping(method = RequestMethod.PATCH)public String patch() {return "Hello from patch";}
}
(4)处理多个 URI
package controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/home")
public class MultipleMapping {@RequestMapping(value = {"","/page","page*","view/*,**/msg"})String indexMultipleMapping() {return "Hello from index multiple mapping.";}
}
(5)带 @RequestParam
@RequestParam 注解配合 @RequestMapping 一起使用,可以将请求的参数同处理方法的参数绑定在一起。
package controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/home/getvalue")
public class ParamRequestMapping {@RequestMapping(value = "/id")//http://localhost:8080/home/getvalue/id?id=1234// 实现请求参数 id 与 处理方法参数 personId 的绑定。String getIdByValue(@RequestParam("id") String personId) {System.out.println("ID is " + personId);return "Get ID from query string of URL with value element"+personId;}@RequestMapping(value = "/personId")//http://localhost:8080/home/getvalue/personId?personId=7894String getId(@RequestParam String personId) {System.out.println("ID is " + personId);return "Get ID from query string of URL without value element";}@RequestMapping(value = "/name")//http://localhost:8080/home/getvalue/name?person=tomString getName(@RequestParam(value = "person", required = true) String personName) {return "Required element of request param"+personName;}/*下面方法可以处理下列URL/home/name?person=xyz/home/name*/@RequestMapping(value = "/getname")//http://localhost:8080/home/getvalue/getname?person=tomString getNameOfrequiredIsFalse(@RequestParam(value = "person", required = true) String personName) {return "Required element of request param"+personName;}/*下面方法是当用户没有传入person参数时,系统默认person=Tom/home/name?person=xyz/home/name*/@RequestMapping(value = "/getnametwo")String getNameByDefaultValue(@RequestParam(value = "person", defaultValue = "John") String personName) {return "Required element of request param"+personName;}
}
(6) header属性处理消息头
post() 方法能同时接受 text/plain 还有 text/html 的请求
package controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/home")
public class ControllHeader {@RequestMapping(value = "/head", headers = {"content-type=text/plain","content-type=text/html"})public String post() {return "Mapping applied along with headers";}
}
(7)params属性处理请求参数
package controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/switch")
public class ControllSwitch {@RequestMapping(value = "/fetch", params = {"personId=10"})String getParams(@RequestParam("personId") String id) {return "Fetched parameter using params attribute = " + id;}@RequestMapping(value = "/fetch", params = {"personId=20"})String getParamsDifferent(@RequestParam("personId") String id) {return "Fetched parameter using params attribute = " + id;}
}
(8) 处理动态 URI
package controller;import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/dynamic")
public class ControllerDynamicUriValue {//http://localhost:8080/dynamic/fetch/10@RequestMapping(value = "/fetch/{id}", method = RequestMethod.GET)String getDynamicUriValue(@PathVariable String id) {System.out.println("ID is " + id);return "Dynamic URI parameter fetched";}//http://localhost:8080/dynamic/fetch/tye/tom@RequestMapping(value = "/fetch/{id:[a-z]+}/{name}", method = RequestMethod.GET)String getDynamicUriValueRegex(@PathVariable("name") String name) {System.out.println("Name is " + name);return "Dynamic URI parameter fetched using regex";}
}
3、@ResponseBody
@ResponseBody 注解表示方法的返回值应该直接写入 HTTP 响应体中,而不是被解析为视图。正常情况下,Controller类中函数返回是一个模板对象(页面),但是有时候我们希望返回值数值型(字符串或者Json格式数据),这时就需要添加@ResponseBody注解。@ResponseBody注解可以添加到类或者函数上。
@ResponseBody返回的是数据
4、@RestController
@RestController是一个组合注解,它结合了 @Controller 和 @ResponseBody 注解的功能(就相当于把两个注解组合在一起)。在使用 @RestController 注解标记的类中,每个方法的返回值都会以 JSON 或 XML 的形式直接写入 HTTP 响应体中,相当于在每个方法上都添加了 @ResponseBody 注解。
@RestController 适用于构建 RESTful 风格的 API,其中每个方法的返回值会直接序列化为 JSON 或 XML 数据并发送给客户端。而 @Controller 适用于传统的 MVC 架构,它负责处理请求并返回相应的视图。
@RestController下的方法默认返回的是数据格式,@Controller注解标注的类下面的方法默认返回的就是以视图为格式。
什么时候需要返回的是视图,什么时候需要返回数据?
当设计 RESTful API 时,一般的原则是:
如果客户端希望获取数据(例如 JSON、XML),则返回数据。
如果客户端希望展示数据(例如 HTML 页面),则返回视图。
5、@RequestMapping
@GetMapping注解可以用于类和方法上,用于定义HTTP GET请求的URL路径。当客户端发送HTTP GET请求时,Spring Boot会自动将请求映射到具有相应URL路径的控制器方法上。
6、@PostMapping
在 Spring Boot 中,我们经常需要编写 RESTful Web 服务,以便于客户端与服务器之间的通信。为了简化 RESTful Web 服务的开发,Spring Boot 提供了 @PostMapping 注解,它可以让我们更方便地编写 POST 请求处理方法。
@PostMapping是一个组合注解,它是@RequestMapping(method = RequestMethod.POST)的缩写。它用于处理HTTP POST请求的方法,只能标注在方法上。使用@PostMapping注解的方法将仅响应POST请求。
7、@GetMapping注解
@GetMapping也是一个组合注解,它是@RequestMapping(method = RequestMethod.GET)的缩写。它用于处理HTTP GET请求的方法,也只能标注在方法上。使用@GetMapping注解的方法将仅响应GET请求。