SpringMVC的RequestMapping注解
一、@RequestMapping注解的功能
从注解名称上我们可以看到,@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系。
SpringMVC接收到指定的请求,就会来找到在映射关系中对应的控制器方法来处理这个请求。
二、@RequestMapping注解的位置
@RequestMapping标识一个类:设置映射请求的请求路径的初始信息。
@RequestMapping标识一个方法:设置映射请求请求路径的具体信息。
1 2 3 4 5 6 7 8 9 | @Controller @RequestMapping( "/test" ) public class RequestMappingController { //此时请求映射所映射的请求的请求路径为:/test/testRequestMapping @RequestMapping( "/testRequestMapping" ) public String testRequestMapping(){ return "success" ; } } |
三、@RequestMapping注解的Value属性
@RequestMapping注解的Value属性可以通过请求的请求地址匹配请求映射
@RequestMapping注解的Value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求
index.html
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE html> <html lang= "en" xmlns:th= "http://www.thymeleaf.org" > <head> <meta charset= "UTF-8" > <title>Title</title> </head> <body> <a th:href= "@{/hello/testRequestMapping}" >测试@RequestMapping的value属性-- >/testRequestMapping</a><br> <a th:href= "@{/hello/test}" >测试@RequestMapping的value属性-->/test</a><br> </body> </html> |
hello.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | package com.zk.hello; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping( value = { "/hello" , "/test1" }, method = {RequestMethod.GET,RequestMethod.POST} ) public class hello { @RequestMapping( value = { "/testRequestMapping" , "/test" } ) public String testRequestMapping(){ return "success" ; } } |
四、@RequestMapping注解的method属性
@RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射
@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配
多种请求方式的请求
若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错
405:Request method 'POST' not supported
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)