SpringMVC之@RequestMapping注解

这篇具有很好参考价值的文章主要介绍了SpringMVC之@RequestMapping注解。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


前言

@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

三、源码

工程目录:
SpringMVC之@RequestMapping注解,SpringMVC,后端,springMVC,java
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的讲解。文章来源地址https://www.toymoban.com/news/detail-661172.html

到了这里,关于SpringMVC之@RequestMapping注解的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SpringMVC中@RequestMapping注解的详细说明

    @RequestMapping 是Spring MVC中一个用于映射HTTP请求和控制器方法之间关系的注解。它用于定义控制器方法如何响应特定的HTTP请求,包括GET、POST、PUT、DELETE等。以下是 @RequestMapping 注解的详细说明: 基本用法: @RequestMapping 用于注解一个控制器方法,指定该方法应该处理的请求路径

    2024年02月07日
    浏览(32)
  • springMVC-@RequestMapping

    @RequestMapping注解可以指定控制器/处理器的某个方法的请求的url, 示例 (结合springMVC基本原理理解) @RequestMapping不仅可以修饰方法, 还可以 修饰类 当同时修饰类和方法时,jsp请求的url 就是/类请求值/方法请求值 @RequestMapping还可以指定请求的方式(post/get/put/delete..) 相应地, 

    2024年02月04日
    浏览(36)
  • @JsonProperty 前端传参数名和后端参数名不一样 入参 出参 映射 注解 springboot springmvc

    使用 @JsonProperty 前端传productName,后端使用  @JsonProperty 转换一下。 返回也是一样。如果出参也用这个对象,出参用的是  @JsonProperty 里的字段名。前端拿到的是productName。 @JsonProperty  位于  com.fasterxml.jackson.annotation   依赖如下  常用到jackson的注解: @JsonProperty、@JsonIgnore、

    2024年04月23日
    浏览(21)
  • SpringMVC 注解配置SpringMVC

    使用配置类和注解代替web.xml和SpringMVC配置文件的功能 1、创建初始化类,代替web.xml 在Servlet3.0环境中,容器会在类路径中查找实现javax.servlet.ServletContainerInitializer接口的类,如果找到的话就用它来配置Servlet容器。 Spring提供了这个接口的实现,名为SpringServletContainerInitializer,这

    2024年01月24日
    浏览(32)
  • SpringMVC之注解配置SpringMVC

    学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩;迟一天就多一天平庸的困扰。各位小伙伴,如果您: 想系统/深入学习某技术知识点… 一个人摸索学习很难坚持,想组团高效学习… 想写博客但无从下手,急需写作干货注入能量… 热爱写作,愿意让自己成为更好

    2024年02月01日
    浏览(35)
  • 【SpringMVC】| SpringMVC执行流程原理 | 常用注解 剥析

    MVC全称Model View Controller,是一种设计创建Web应用程序的模式。这三个单词分别代表Web应用程序的三个部分: Model (模型):指数据模型。用于存储数据以及处理用户请求的业务逻辑。在Web应用中,JavaBean对象,业务模型等都属于Model。 View (视图):用于展示模型中的数据的

    2024年02月06日
    浏览(27)
  • Spring 注解 和SpringMVC注解

    Spring和Spring MVC是两个紧密相关但又不同的框架,它们都使用一系列注解来简化开发。以下是Spring和Spring MVC中一些常用的注解: ### Spring 注解: 1. **`@Component`:**    - 用于将类标记为Spring容器中的组件,由Spring自动扫描并进行管理。    - 具体的派生注解有`@Service`、`@Reposit

    2024年01月23日
    浏览(43)
  • SpringMVC及注解介绍(一)

    目录 1.什么是 Spring MVC? 2.创建一个SpringMVC项目 3.MVC定义 4.MVC和SpringMVC的关系 5.如何学SpringMVC 6.SpringMVC注解介绍 1.@RequestMapping 2.@ResponseBody 3.@RestController = @Controller + @ResponseBody 4.更换五大注解 5.@RequestMapping 是 post 还是 get 请求? 6.@GetMapping(设置请求方法)  7.获取参数 7.1通过

    2024年02月16日
    浏览(28)
  • 注解配置SpringMVC

    使用配置类和注解代替web.xml和SpringMVC配置文件的功能。 创建模块并导入依赖 在config文件夹下新建WebInit类 在Servlet 3.0环境中,容器会在类路径中查找实现 javax.servlet.ServletContainerInitializer 接口的类,如果找到的话,这些接口的实现类可以用来配置Servlet容器。 Spring提供了一个实

    2024年02月09日
    浏览(30)
  • 【SpringMVC】自定义注解

    🎉🎉欢迎来到我的CSDN主页!🎉🎉 🏅我是Java方文山,一个在CSDN分享笔记的博主。📚📚 🌟在这里,我要推荐给大家我的专栏《Spring MVC》。🎯🎯 🚀无论你是编程小白,还是有一定基础的程序员,这个专栏都能满足你的需求。我会用最简单易懂的语言,带你走进Spring MV

    2024年02月07日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包