SpringMVC之@RequestMapping注解

news2024/9/28 7:49:05

文章目录

  • 前言
  • 一、@RequestMapping介绍
  • 二、详解(末尾附源码,自行测试)
    • 1.@RequestMapping注解的位置
    • 2.@RequestMapping注解的value属性
    • 3.@RequestMapping注解的method属性
    • 4.@RequestMapping注解的params属性(了解)
    • 5.@RequestMapping注解的headers属性(了解)
    • 6.SpringMVC支持ant风格的路径
    • 7.SpringMVC支持路径中的占位符(重点)
    • 三、源码
  • 总结


前言

@RequestMapping注解


一、@RequestMapping介绍

(1)@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系。
(2)SpringMVC 接收到指定的请求,就会来找到在映射关系中对应的控制器方法来处理这个请求。
(3)在SpringMVC中如何被使用:浏览器发送请求,若请求地址符合前端控制器的url-pattern,该请求就会被前端控制器DispatcherServlet处理。前端控制器会读取SpringMVC的核心配置文件,通过扫描组件找到控制器,将请求地址和控制器中@RequestMapping注解的value属性值进行匹配,若匹配成功,该注解所标识的控制器方法就是处理请求的方法。处理请求的方法需要返回一个字符串类型的视图名称,该视图名称会被视图解析器解析,加上前缀和后缀组成视图的路径,通过Thymeleaf对视图进行渲染,最终转发到视图所对应页面。

二、详解(末尾附源码,自行测试)

1.@RequestMapping注解的位置

@RequestMapping标识一个类:设置映射请求的请求路径的初始信息
@RequestMapping标识一个方法:设置映射请求请求路径的具体信息

@Controller
@RequestMapping("/test")
public class RequestMappingController {
//此时请求映射所映射的请求的请求路径为:/test/testRequestMapping
@RequestMapping("/testRequestMapping")
public String testRequestMapping(){
return "success";
}
}

2.@RequestMapping注解的value属性

@RequestMapping注解的value属性通过请求的请求地址匹配请求映射
@RequestMapping注解的value属性是一个字符串类型的数组,表示该请求映射能够匹配多个请求地址所对应的请求
@RequestMapping注解的value属性必须设置,至少通过请求地址匹配请求映射

<a th:href="@{/testRequestMapping}">测试@RequestMapping的value属性--
>/testRequestMapping</a><br>
<a th:href="@{/test}">测试@RequestMapping的value属性-->/test</a><br>
@RequestMapping(
value = {"/testRequestMapping", "/test"}
)
public String testRequestMapping(){
return "success";
}

这两个请求映射路径都能访问到success页面。

3.@RequestMapping注解的method属性

@RequestMapping注解的method属性通过请求的请求方式(get或post)匹配请求映射。
@RequestMapping注解的method属性是一个RequestMethod类型的数组,表示该请求映射能够匹配多种请求方式的请求。
若当前请求的请求地址满足请求映射的value属性,但是请求方式不满足method属性,则浏览器报错405:Request method ‘POST’ not supported。

<a th:href="@{/test}">测试@RequestMapping的value属性-->/test</a><br>
<form th:action="@{/test}" method="post">
<input type="submit">
</form>
@RequestMapping(
value = {"/testRequestMapping", "/test"},
method = {RequestMethod.GET, RequestMethod.POST}
)
public String testRequestMapping(){
return "success";
}
@GetMapping("/testGetMapping")
public String testGetMapping(){
return "success";
 }

注:对于处理指定请求方式的控制器方法,SpringMVC中提供了@RequestMapping的派生注解:
1.处理get请求的映射–>@GetMapping
2.处理post请求的映射–>@PostMapping
3.处理put请求的映射–>@PutMapping
4.处理delete请求的映射–>@DeleteMapping
5.常用的请求方式有get,post,put,delete。
但是目前浏览器只支持get和post,若在form表单提交时,为method设置了其他请求方式的字符串(put或delete),则按照默认的请求方式get处理。若要发送put和delete请求,则需要通过spring提供的过滤器HiddenHttpMethodFilter,在RESTFUL部分会讲到。

4.@RequestMapping注解的params属性(了解)

@RequestMapping注解的params属性通过请求的请求参数匹配请求映射。
@RequestMapping注解的params属性是一个字符串类型的数组,可以通过四种表达式设置请求参数和请求映射的匹配关系:
“param”:要求请求映射所匹配的请求必须携带param请求参数
“!param”:要求请求映射所匹配的请求必须不能携带param请求参数
“param=value”:要求请求映射所匹配的请求必须携带param请求参数且param=value
“param!=value”:要求请求映射所匹配的请求必须携带param请求参数但是param!=value

<a th:href="@{/test(username='admin',password=123456)">测试@RequestMapping的
params属性-->/test</a><br>
@RequestMapping(
value = {"/testRequestMapping", "/test"}
,method = {RequestMethod.GET, RequestMethod.POST}
,params = {"username","password!=123456"}
)
public String testRequestMapping(){
return "success";
}

注:
若当前请求满足@RequestMapping注解的value和method属性,但是不满足params属性,此时
页面会报错400:Parameter conditions “username, password!=123456” not met for actual
request parameters: username={admin}, password={123456}

5.@RequestMapping注解的headers属性(了解)

@RequestMapping注解的headers属性通过请求的请求头信息匹配请求映射。
@RequestMapping注解的headers属性是一个字符串类型的数组,可以通过四种表达式设置请求头信息和请求映射的匹配关系:
“header”:要求请求映射所匹配的请求必须携带header请求头信息。
“!header”:要求请求映射所匹配的请求必须不能携带header请求头信息。
“header=value”:要求请求映射所匹配的请求必须携带header请求头信息且header=value。
“header!=value”:要求请求映射所匹配的请求必须携带header请求头信息且header!=value。
若当前请求满足@RequestMapping注解的value和method属性,但是不满足headers属性,此时页面显示404错误,即资源未找到。

<a th:href="@{/hello/testHeaders}">目标testHeaders</a><br>
    @RequestMapping(
            value = {"/testHeaders"},
            headers = {"localhost=8081"}
    )
    public String testHeaders(){
        return "success";
    }

tomcat默认端口是8080,这里8081访问不到,报错。

6.SpringMVC支持ant风格的路径

?:表示任意的单个字符
*:表示任意的0个或多个字符
** :表示任意的一层或多层目录
注意 :在使用 ** 时,只能使用/**/xxx的方式

<a th:href="@{/hello/a1a/testAnt}">目标testAnt</a><br>
    @RequestMapping(
            value = {"/a*a/testAnt"}// /**/testAnt
    )
    public String testAnt(){
        return "success";
    }

7.SpringMVC支持路径中的占位符(重点)

原始方式:/deleteUser?id=1
rest方式:/deleteUser/1
SpringMVC路径中的占位符常用于RESTful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参。

<a th:href="@{/testRest/1/admin}">测试路径中的占位符-->/testRest</a><br>
@RequestMapping("/testRest/{id}/{username}")
public String testRest(@PathVariable("id") String id, @PathVariable("username")
String username){
System.out.println("id:"+id+",username:"+username);
return "success";
}
//最终输出的内容为-->id:1,username:admin

三、源码

工程目录:
在这里插入图片描述
maven依赖:

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- SpringMVC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>

        <!-- 日志 -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>

        <!-- ServletAPI -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- Spring5和Thymeleaf整合包 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
    </dependencies>

index.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>首页</h1>
<a th:href="@{/target}">目标target</a><br>
<a th:href="@{/hello/testRequestMapping}">目标testRequestMapping</a><br>
<a th:href="@{/hello/test}">目标test</a><br>
<a th:href="@{/hello/test}">目标test-->get方法</a><br>
<a th:href="@{/hello/testGetMapping}">目标testGetMapping-->get方法</a><br>
<form th:action="@{/hello/test}" method="post">
    <input type="submit" value="post">
</form>
<form th:action="@{/hello/testPut}" method="put">
    <input type="submit" value="put">
</form>
<a th:href="@{/hello/testParams(username='admin',password=123)}">目标testParams</a><br>
<a th:href="@{/hello/testHeaders}">目标testHeaders</a><br>
<a th:href="@{/hello/a1a/testAnt}">目标testAnt</a><br>
<a th:href="@{/hello/testPath/1/admin}">目标testPath</a><br>
</body>
</html>

target.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
hello,我是target
</body>
</html>

success.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
我是success
</body>
</html>

RequestMappingController类:

package com.dragon.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@RequestMapping("/hello")
@Controller
public class RequestMappingController {
    @RequestMapping(
            value = {"/testRequestMapping","/test"},
            method = {RequestMethod.GET}
    )
    public String success(){
        return "success";
    }
    @GetMapping("/testGetMapping")
    public String testGetMapping(){
        return "success";
    }
    @RequestMapping(
            value = {"/testPut"},
            method = {RequestMethod.PUT}
    )
    public String testPut(){
        return "success";
    }
    @RequestMapping(
            value = {"/testParams"},
            params = {"username","password!=123456"}
    )
    public String testParams(){
        return "success";
    }
    @RequestMapping(
            value = {"/testHeaders"},
            headers = {"localhost=8081"}
    )
    public String testHeaders(){
        return "success";
    }
    @RequestMapping(
            value = {"/a*a/testAnt"}// /**/testAnt
    )
    public String testAnt(){
        return "success";
    }
    @RequestMapping("/testPath/{id}/{username}")
    public String testPath(@PathVariable("id")Integer id,@PathVariable("username")String username){
        System.out.println("id:"+id);
        System.out.println("username:"+username);
        return "success";
    }
}

HelloController类:

package com.dragon.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
    @RequestMapping("/")
    public String index(){
        return "index";
    }
    @RequestMapping("/target")
    public String toTarget(){
        return "target";
    }
}

如果不会搭建框架,或者需要看springMVC.xml等文件,可以看我springmvc专栏里的搭建框架的文章。


总结

以上就是SpringMVC的讲解。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/903512.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

课程项目设计--项目建立--宿舍管理系统--springboot后端

前要 项目设计–宿舍管理系统 文章目录 项目建立导入依赖配置文件配置目录结构config配置mybatis-plusswagger 生成实体、mapper和servicebaseEntity统一响应实例响应码接口响应码接口实现统一响应result统一分页响应 项目建立 太长了&#xff0c;修改一下 导入依赖 暂时先加…

Java 项目日志实例:Log4j2

点击下方关注我&#xff0c;然后右上角点击...“设为星标”&#xff0c;就能第一时间收到更新推送啦~~~ Apache Log4j 2 是对 Log4j 的升级&#xff0c;与其前身 Log4j 1.x 相比有了显着的改进&#xff0c;并提供了许多 Logback 可用的改进&#xff0c;同时支持 JCL 以及 SLF4J…

Word中对象方法(Methods)的理解及示例(上)

【分享成果&#xff0c;随喜正能量】奋斗没有终点,任何时候都是一个起点&#xff0c;沉潜是为了蓄势待发&#xff0c;沉潜是为了等待因缘。鲸豚沉潜于大海&#xff0c;幽兰深藏于山谷&#xff0c;能够经得起沉潜的人&#xff0c;才会有更高的成就。正如一年的树木只能当柴烧&am…

C++入门:函数缺省参数与函数重载

目录 1.函数缺省参数 1.1 缺省参数概念 1.2 缺省参数分类 2.函数重载 2.1 函数重载概念 2.2 C支持函数重载的原理 1.函数缺省参数 1.1 缺省参数概念 缺省参数是声明或定义函数时为函数的参数指定一个缺省值。在调用该函数时&#xff0c;如果没有指定实 参则采用该形参的…

Unity 之 RaycastHit(存储射线投射操作)

文章目录 总述具体使用场景 总述 RaycastHit 类是 Unity 中的一个结构&#xff0c;用于存储射线投射操作的结果。射线投射是一种常用的技术&#xff0c;用于检测场景中的碰撞、获取碰撞点、获取碰撞对象的信息等。RaycastHit 提供了关于射线与场景中对象的交互信息&#xff0c…

新型Windows内核池风水利用工具研究

引用 这篇文章的目的是介绍一种新型基于内核态分页内存和非分页内存的越界写入通用利用技术和相关工具复现. 文章目录 引用简介分页模式利用分析分页模式利用调试分析非分页模式利用分析非分页模式利用调试分析工具使用方法工具使用效果相关引用参与贡献 简介 笔者的在原作者利…

硕士研究生小论文写作方法

本人985硕博毕业-曾多次辅导本硕同学完成成毕设&#xff0c;下面分享一些经验 图为当年大论文外审结果&#xff01;&#xff01;&#xff01; 当撰写一篇硕士研究生的小论文时&#xff0c;以下是每个部分的写作方法的详细描述&#xff0c;&#xff1a; 摘要&#xff08;Abst…

零基础在家就可以做的副业,3个兼职项目推荐

做副业最需要注重的是什么&#xff1f;我觉得有收益&#xff0c;稳定&#xff0c;上手快&#xff0c;可以学到东西&#xff0c;下面3个副业适合新手快速变现的副业&#xff0c;大可以随便挑一两个尝试一下 第一个&#xff1a;在小红书的发手记 满5000粉丝们就可以申请品牌合作…

OMT画图的五种结构表达方式

实例化&#xff1a;A类依赖于B类。 class B {doSth () {} }class A {constructor () {}run () {const b new B()b.doSth()} }new A().run()委托&#xff1a;A对象依赖于B对象。 class B {doSth () {} } const b new B()class A {constructor () {}run () {b.doSth()} } new A…

为什么 Lemon8 是今年值得关注的社交媒体应用?

社交媒体应用逐渐成为了用户联系亲朋好友的一种方式,也成为了营销推广有利的平台。近期,Lemon8也快速崛起,一度荣登美国APP下载排行榜前十名,在社交和电子商务市场中,也占据了很大的份额,在日本以及泰国多地更为流行。为什么Lemon8会成为最值得关注的社交媒体应用呢? 什么原因…

基于springboot+vue的博物馆藏品平台(前后端分离)

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战 主要内容&#xff1a;毕业设计(Javaweb项目|小程序等)、简历模板、学习资料、面试题库、技术咨询 文末联系获取 项目介绍…

TouchGFX之安装

1.安装X-CUBE-TOUCHGFX​ 帮助 ->管理嵌入式软件包 转到“STMicroelectronics”选项卡。 滚动直至找到“X-CUBE-TOUCHGFX”&#xff0c;然后展开节点。 点击“TouchGFX Generator”复选框&#xff0c;然后点击“立即安装”。 将下载软件包并显示许可协议。 找到TouchGFX Gen…

(成功踩坑)electron-builder打包过程中报错

目录 注意&#xff1a;文中的解决方法2&#xff0c;一定全部看完&#xff0c;再进行操作&#xff0c;有坑 背景 报错1&#xff1a; 报错2&#xff1a; 1.原因&#xff1a;网络连接失败 2.解决方法1&#xff1a; 3.解决方法2&#xff1a; 3.1查看缺少什么资源文件 3.2去淘…

PostgreSQL基本操作总结

安装按PostgreSQL数据库后&#xff0c;会默认创建用户postgres和数据库postgres&#xff0c;这个用户是超级用户&#xff0c;权限最高&#xff0c;可以创建其他用户和权限&#xff0c;在实际开发过程中&#xff0c;会新创建用户和业务数据库&#xff0c;本文主要介绍用户权限和…

Vue中DOM的更新为什么是异步的?

在 Vue 中&#xff0c;DOM 的更新是异步的机制是为了优化性能和提升用户体验。这个机制被称为“异步更新队列”。 Vue的异步更新队列机制是其实现高效渲染的关键。它通过将多次数据变化合并到一个批处理中&#xff0c;从而减少了不必要的DOM操作&#xff0c;提高了性能。下面是…

[推荐] MyBatis框架初学笔记-为之后拾遗

目录 1. mybatis的简介 2.MyBatis的环境搭建 2.1 导入pom依赖 2.2 数据库文件导入连接 2.3 修改web.xml文件 2.4 安装插件 &#xff08;1&#xff09;Free mybatis plugin &#xff08;2&#xff09;Mybatis generator &#xff08;3&#xff09; mybatis tools &#x…

Excel/PowerPoint条形图改变顺序

条形图是从下往上排的&#xff0c;很多时候不是我们想要的效果 解决方案 选择坐标轴&#xff0c;双击&#xff0c;按下图顺序点击 效果

函数栈帧理解

本文是从汇编角度来展示的函数调用&#xff0c;而且是在vs2013下根据调试展开的探究&#xff0c;其它平台在一些指令上会有点不同&#xff0c;指令不多&#xff0c;简单记忆一下即可&#xff0c;在我前些年的学习中&#xff0c;学的这几句汇编指令对我调试找错误起了不小的作用…

Python爬虫实战案例——第一例

X卢小说登录(包括验证码处理) 地址&#xff1a;aHR0cHM6Ly91LmZhbG9vLmNvbS9yZWdpc3QvbG9naW4uYXNweA 打开页面直接进行分析 任意输入用户名密码及验证码之后可以看到抓到的包中传输的数据明显需要的是txtPwd进行加密分析。按ctrlshiftf进行搜索。 定位来到源代码中断点进行调…

Qt应用开发(基础篇)——纯文本编辑窗口 QPlainTextEdit

一、前言 QPlainTextEdit类继承于QAbstractScrollArea&#xff0c;QAbstractScrollArea继承于QFrame&#xff0c;是Qt用来显示和编辑纯文本的窗口。 滚屏区域基类https://blog.csdn.net/u014491932/article/details/132245486?spm1001.2014.3001.5501框架类QFramehttps://blo…