controller層常用注解:@RequestMapping、@PostMapping、@GetMapping總結 以及 Spring MVC @GetMapping和@PostMapping注解的使用


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


    
    
    
            
  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注解】

原文地址1:https://blog.csdn.net/qq_44837912/article/details/103476053

原文地址2:https://blog.csdn.net/dwenxue/article/details/81586709

原文地址3:https://blog.csdn.net/magi1201/article/details/82226289


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM