@GetMapping和@PostMapping 和@RequestMapping區別
@GetMapping 用於將HTTP GET
請求映射到特定處理程序方法的注釋。
具體來說,@GetMapping
是一個作為快捷方式的組合注釋 @RequestMapping(method = RequestMethod.GET)
。
@PostMapping 用於將HTTP POST
請求映射到特定處理程序方法的注釋。
具體來說,@PostMapping
是一個作為快捷方式的組合注釋 @RequestMapping(method = RequestMethod.POST)
。
此外還有@PutMapping,@PatchMapping,@DeleteMapping同上
所以一般情況下都是用@RequestMapping(method=RequestMethod.
)即可
具體如果想了解更多,可前往spring 官網https://spring.io/查詢
Spring MVC @GetMapping和@PostMapping注解的使用
創建HelloWorldController
1 package com.controller; 2 import org.springframework.stereotype.Controller; 3 import org.springframework.ui.Model; 4 import org.springframework.web.bind.annotation.GetMapping; 5 import org.springframework.web.bind.annotation.PostMapping; 6 @Controller 7 public class HelloWorldController { 8 //只接受get方式的請求 9 @GetMapping("/testGetMapping") 10 public String testGetMapping(Model model) { 11 model.addAttribute("msg","測試@GetMapping注解"); 12 return "success"; 13 } 14 //只接受post方式的請求 15 @PostMapping("/testPostMapping") 16 public String testPostMapping(Model model) { 17 model.addAttribute("msg","測試@PostMapping注解"); 18 return "success"; 19 } 20 }
創建index.jsp
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="utf-8"> 7 <title>index</title> 8 </head> 9 <body> 10 <form action="testGetMapping" method="get"> 11 <button>測試@GetMapping注解</button> 12 </form> 13 <br> 14 <form action="testPostMapping" method="post"> 15 <button>測試@PostMapping注解</button> 16 </form> 17 </body> 18 </html>
創建success.jsp
1 <%@ page language="java" contentType="text/html; charset=utf-8" 2 pageEncoding="utf-8"%> 3 <%@taglib prefix="c" uri="http://java.sun.com/jstl/core" %> 4 <!DOCTYPE html> 5 <html> 6 <head> 7 <meta charset="utf-8"> 8 <title>success</title> 9 </head> 10 <body> 11 ${requestScope.msg } 12 </body> 13 </html>
啟動Tomcat訪問index.jsp
點擊【測試@GetMapping注解】
點擊【測試@PostMapping注解】