1. 三者的關系圖 
2. 作用
@RequestMapping、@PostMapping、@GetMapping均為映射請求路徑,可作用於類或方法上。當作用於類時,是該類中所有響應請求方法地址的父路徑。
3. 示例
點擊查看代碼
@RequestMapping("/test") //test即父路徑
public class test {
@RequestMapping(value = "/hello", method = RequestMethod.GET)
// @GetMapping("/hello")
@ResponseBody // 將返回的java對象轉為json格式的數據
public String hello() {
return "hello world !";
}
}
訪問路徑:http://localhost:8080/test/hello (切記不要忘記“test”哦!)
溫馨提示:讀者可自行去了解POST請求和GET請求的區別
可參考:https://www.cnblogs.com/logsharing/p/8448446.html
@GetMapping用於將HTTP get請求映射到特定處理程序的方法注解 具體來說,@GetMapping是一個組合注解,是@RequestMapping(method = RequestMethod.GET)的縮寫。
@PostMapping用於將HTTP post請求映射到特定處理程序的方法注解 具體來說,@PostMapping是一個組合注解,是@RequestMapping(method = RequestMethod.POST)的縮寫。
Spring MVC @GetMapping和@PostMapping注解的使用
創建HelloWorldController
-
package com.controller;
-
import org.springframework.stereotype.Controller;
-
import org.springframework.ui.Model;
-
import org.springframework.web.bind.annotation.GetMapping;
-
import org.springframework.web.bind.annotation.PostMapping;
-
@Controller
-
public
class
HelloWorldController {
-
//只接受get方式的請求
-
@GetMapping("/testGetMapping")
-
public String
testGetMapping
(Model model) {
-
model.addAttribute(
"msg",
"測試@GetMapping注解");
-
return
"success";
-
}
-
//只接受post方式的請求
-
@PostMapping("/testPostMapping")
-
public String
testPostMapping
(Model model) {
-
model.addAttribute(
"msg",
"測試@PostMapping注解");
-
return
"success";
-
}
-
}
創建index.jsp
-
<%@ page language="java" contentType="text/html; charset=utf-8"
-
pageEncoding="utf-8"%>
-
<!DOCTYPE html>
-
<html>
-
<head>
-
<meta charset="utf-8">
-
<title>index
</title>
-
</head>
-
<body>
-
<form action="testGetMapping" method="get">
-
<button>測試@GetMapping注解
</button>
-
</form>
-
<br>
-
<form action="testPostMapping" method="post">
-
<button>測試@PostMapping注解
</button>
-
</form>
-
</body>
-
</html>
創建success.jsp
-
<%@ page language="java" contentType="text/html; charset=utf-8"
-
pageEncoding="utf-8"%>
-
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
-
<!DOCTYPE html>
-
<html>
-
<head>
-
<meta charset="utf-8">
-
<title>success
</title>
-
</head>
-
<body>
-
${requestScope.msg }
-
</body>
-
</html>
啟動Tomcat訪問index.jsp
點擊【測試@GetMapping注解】
點擊【測試@PostMapping注解】