Spring Web MVC 是基于Servlet API 构建的原始 Web 框架,从一开始就包含在Spring 框架中。它的正式名称 “Spring Web MVC” 来自其源模块的名称(Spring-webmvc),但它通常被称为“Spring MVC”。
从上述定义我们可以得出两个关键信息:
Spring MVC 是⼀个 Web 框架。
Spring MVC 是基于 Servlet API 构建的。
MVC 是 Model View Controller 的缩写,它是软件工程中的一种软件架构模式,它把软件系统分为模型、视图和控制器三个基本部分。
执行流程:
MVC 是一种思想,而 Spring MVC 是对 MVC 思想的具体实现。
总结来说,Spring MVC 是⼀个实现了 MVC 模式,并继承了 Servlet API 的 Web 框架。既然是 Web框架,那么当用户在浏览器中输入了 url 之后,我们的 Spring MVC 项⽬就可以感知到用户的请求。
学习 Spring MVC 我们只需要掌握以下 3 个功能:
对于 Spring MVC 来说,掌握了以上 3 个功能就相当于掌握了 Spring MVC。
Spring MVC 项目创建和 Spring Boot 创建项目相同(Spring MVC 使用 Spring Boot 的方式创建),在创建的时候选择 Spring Web 就相当于创建了 Spring MVC 的项目。
在 Spring MVC 中使用 @RequestMapping 来实现 URL 路由映射,也就是浏览器连接程序的作用。
接下来要实现的功能是访问地址:http://localhost:8080/user/hi,能打印“hello,spring mvc”信息。
package com.example.project.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:15
* @version: 1.0
*/
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping("/sayhi")
public String sayHi() {
return "Hello Spring MVC";
}
}
@RequestMapping 还可以指定 GET/POST 方法类型
实现 HTTP 链接,但只支持 GET 类型的请求
package com.example.project.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:15
* @version: 1.0
*/
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping(path = "/sayhi",method = RequestMethod.GET)
public String sayHi() {
return "Hello Spring MVC !!!";
}
@GetMapping("/sayhi2")
public String sayHi2() {
return "Hello Spring MVC2 !!!";
}
}
get 请求的 3 种写法:
// 写法1
@RequestMapping("/index")
// 写法2
@RequestMapping(value = "/index",method = RequestMethod.GET)
// 写法3
@GetMapping("/index")
实现 HTTP 链接,但只支持 POST 类型的请求
package com.example.project.controller;
import org.springframework.web.bind.annotation.*;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:15
* @version: 1.0
*/
@RestController
@RequestMapping("/test")
public class TestController {
@RequestMapping(path = "/sayhi",method = RequestMethod.GET)
public String sayHi() {
return "Hello Spring MVC !!!";
}
@GetMapping("/sayhi2")
public String sayHi2() {
return "Hello Spring MVC2 !!!";
}
@PostMapping("/sayhi3")
public String sayHi3() {
return "Hello Spring MVC3 !!!";
}
}
post 请求的 3 种写法:
// 写法1
@RequestMapping("/index")
// 写法2
@RequestMapping(value = "/index",method = RequestMethod.POST)
// 写法3
@PostMapping("/index")
package com.example.project.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController2
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:44
* @version: 1.0
*/
@RestController
@RequestMapping("/test2")
public class TestController2 {
@RequestMapping("/getname")
public String getName(HttpServletRequest request) {
return "Name: " + request.getParameter("name");
}
}
package com.example.project.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController2
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:44
* @version: 1.0
*/
@RestController
@RequestMapping("/test2")
public class TestController2 {
@RequestMapping("/getname")
public String getName(HttpServletRequest request) {
return "Name: " + request.getParameter("name");
}
@RequestMapping("/getname2")
public String getName2(String name) {
return "Name: " + name;
}
}
package com.example.project.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController2
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:44
* @version: 1.0
*/
@RestController
@RequestMapping("/test2")
public class TestController2 {
@RequestMapping("/getname")
public String getName(HttpServletRequest request) {
return "Name: " + request.getParameter("name");
}
@RequestMapping("/getname2")
public String getName2(String name) {
return "Name: " + name;
}
@RequestMapping("/getname3")
public String getName3(String name,Integer age) {
return "Name: " + name + " age: " + age;
}
}
package com.example.project.controller;
import com.example.project.model.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: UserController
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:59
* @version: 1.0
*/
@RestController
@RequestMapping("/user")
public class UserController {
@RequestMapping("/add")
public User add(User user) {
return user;
}
}
package com.example.project.model;
import lombok.Data;
/**
* @projectName: Project
* @package: com.example.project.model
* @className: User
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:58
* @version: 1.0
*/
@Data
public class User {
private int id;
private String name;
private String password;
private int age;
}
如果我们的实际业务前端的参数是⼀个非必传的参数,我们可以通过设置 @RequestParam 中的 required=false 来避免不传递时报错
@RequestMapping("/detail/{aid}")
public Integer detail(@PathVariable("aid") Integer aid) {
return aid;
}
@RequestMapping("/upload")
public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
String path = "E:\\study\\Gitee\\test_c\\test-2023-12-23\\Project\\file\\img.jpg";
//保存文件
file.transferTo(new File(path));
return path;
}
@RequestMapping("/upload")
public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
//1.生成一个唯一的id | UUID = 全球唯一ID -> MAC + 随机种子 + 加密算法
String name = UUID.randomUUID().toString().replace("-","");
//2.得到源文件后缀名
name += file.getOriginalFilename().
substring(file.getOriginalFilename().lastIndexOf("."));
String path = "E:\\study\\Gitee\\test_c\\test-2023-12-23\\Project\\file\\" + name;
//保存文件
file.transferTo(new File(path));
return path;
}
保证不被覆盖
获取 Request 和 Response 对象
@RequestMapping("/param10")
public String param10(HttpServletResponse response, HttpServletRequest requ
est) {
String name = request.getParameter("name");
// 获取所有 cookie 信息
Cookie[] cookies = request.getCookies();
return name + " 你好.";
}
传统获取 header/cookie
@RequestMapping("/param10")
@ResponseBody
public String param10(HttpServletResponse response, HttpServletRequest requ
est) {
String name = request.getParameter("name");
// 获取所有 cookie 信息
Cookie[] cookies = request.getCookies();
String userAgent = request.getHeader("User-Agent");
return name + ":"+userAgent;
}
简洁的获取 Cookie—@CookieValue
@RequestMapping("/cookie")
public String cookie(@CookieValue(value = "java",required = false) String ck) {
return "cookie:" + ck;
}
简洁获取 Header—@RequestHeader
@RequestMapping("/header")
@ResponseBody
public String header(@RequestHeader("User-Agent") String userAgent) {
return "userAgent:" + userAgent;
}
session 存储和获取
package com.example.project.controller;
import com.example.project.model.User;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: UserController
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 18:59
* @version: 1.0
*/
@RestController
@RequestMapping("/user")
public class UserController {
private static String _SESSION_KEY = "SESSION_KEY";
@RequestMapping("/add")
public User add(User user) {
return user;
}
@RequestMapping("/name")
public String name(@RequestParam(value = "n",required = false)
String name) {
return name;
}
@RequestMapping("/add_json")
public User addByJson(@RequestBody User user) {
return user;
}
@RequestMapping("/detail/{aid}")
public Integer detail(@PathVariable("aid") Integer aid) {
return aid;
}
@RequestMapping("/upload")
public String upload(@RequestPart("myfile")MultipartFile file) throws IOException {
//1.生成一个唯一的id | UUID = 全球唯一ID -> MAC + 随机种子 + 加密算法
String name = UUID.randomUUID().toString().replace("-","");
//2.得到源文件后缀名
name += file.getOriginalFilename().
substring(file.getOriginalFilename().lastIndexOf("."));
String path = "E:\\study\\Gitee\\test_c\\test-2023-12-23\\Project\\file\\" + name;
//保存文件
file.transferTo(new File(path));
return path;
}
@RequestMapping("/cookie")
public String Cookie(@CookieValue(value = "java",required = false) String ck) {
return "cookie:" + ck;
}
@RequestMapping("/set_sess")
public String setSess(HttpServletRequest request) {
HttpSession session = request.getSession();
if(session != null) {
session.setAttribute(_SESSION_KEY,"张三");
return "session set success";
}else {
return "session set fail";
}
}
@RequestMapping("/get_sess")
public String getSess(@SessionAttribute(required = false,value = "SESSION_KEY") String name) {
return name;
}
}
通过上面的学习我们知道,默认请求下无论是 Spring MVC 或者是 Spring Boot 返回的是视图(xxx.html),而现在都是前后端分离的,后端只需要返给给前端数据即可,这个时候我们就需要使用@ResponseBody 注解了。
package com.example.project.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController3
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 22:04
* @version: 1.0
*/
@Controller
public class TestController3 {
@RequestMapping("/index")
public String index() {
return "hello.html";
}
}
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Documenttitle>
head>
<body>
<h1>hello,i am helloh1>
body>
html>
package com.example.project.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @projectName: Project
* @package: com.example.project.controller
* @className: TestController3
* @author: 王嘉辉
* @description:
* @date: 2023/12/23 22:04
* @version: 1.0
*/
@Controller
@ResponseBody
public class TestController3 {
@RequestMapping("/index")
public String index() {
return "hello.html";
}
}
return 不但可以返回一个视图,还可以实现跳转,跳转的方式有两种:
forward: 是请求转发;
redirect:请求重定向。
// 请求重定向
@RequestMapping("/index")
public String index(){
return "redirect:/index.html";
}
// 请求转发
@RequestMapping("/index2")
public String index2(){
return "forward:/index.html";
}
forward(请求转发)和 redirect(请求重定向)的区别,举例来说,例如,你告诉你妈妈,你想吃辣条,如果你妈妈,说好,我帮你去买,这就是 forward 请求转发;如果你妈妈让你自己去买,那么就是请求 redirect 重定向。
forward 和 redirect 具体区别如下: