首页 > 其他分享> > controller层常用注解:@RequestMapping、@PostMapping、@GetMapping总结 以及 Spring MVC @GetMapping和@PostMapping注解
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
- 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注解】
原文地址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
标签:RequestMapping,PostMapping,GetMapping,test,注解,hello 来源: https://www.cnblogs.com/y1536894890/p/15984837.html