3、SpringMVC之RequestMapping注解

发布时间 2023-09-27 11:49:24作者: Javaer1995

3.1、环境搭建

创建名为spring_mvc_demo的新module,过程参考2.1节

3.1.1、创建SpringMVC的配置文件

image

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--在指定的包中,扫描控制层组件-->
    <context:component-scan base-package="org.rain.controller"></context:component-scan>

    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean
                            class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

</beans>

3.1.2、配置web.xml

image

    <!--配置SpringMVC的前端控制器DispatcherServlet,对浏览器发送的请求统一进行处理-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置和名称-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <!--将DispatcherServlet的初始化时间提前到服务器启动时-->
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

3.1.3、创建请求控制器

image

package org.rain.controller;

import org.springframework.stereotype.Controller;

/**
 * @author liaojy
 * @date 2023/9/21 - 8:47
 */
@Controller
public class TestRequestMappingController {
}

image

package org.rain.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author liaojy
 * @date 2023/9/21 - 8:49
 */
@Controller
public class PortalController {

    @RequestMapping("/")
    public String portal(){
        return "index";
    }

}

3.1.4、创建静态资源目录及页面

image

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>

<h1>index.html</h1>

</body>
</html>

image

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成功</title>
</head>
<body>
<h1>success.html</h1>
</body>
</html>

3.1.5、配置tomcat

image

image

细节请参考2.6节

3.2、注解的功能

  • 从注解名称上可以看出,@RequestMapping注解的作用就是将请求和处理请求的控制器方法关联起来,建立映射关系;

  • SpringMVC 的前端控制器(DispatcherServlet)接收到请求后,就会在映射关系中找到对应的控制器方法来处理这个请求;

3.3、注解的位置

3.3.1、源码定义

image

从源码可知,@RequestMapping注解既可以标识在类上,也可以标识在方法上

3.3.2、控制器示例

  • @RequestMapping标识在类上:设置映射请求的基础信息

  • @RequestMapping标识在方法上:设置映射请求的具体信息

image

@Controller
@RequestMapping("/test")
public class TestRequestMappingController {

    // 此时控制器方法所匹配的请求的请求路径为:/test/hello
    @RequestMapping("/hello")
    public String hello(){
        return "success";
    }

}

3.3.3、请求示例

image

注意html要引入thymeleaf的约束:xmlns:th="http://www.thymeleaf.org"

<a th:href="@{/hello}">测试/hello请求</a>

<a th:href="@{/test/hello}">测试/test/hello请求</a>

3.3.4、测试效果

image

image

image

image

3.3.5、双重位置的作用

可以根据业务需要划分模块,在请求路径中就可以体现出请求的是哪个模块的资源

3.4、注解的value属性

@RequestMapping注解的value属性必须设置,其作用是根据请求路径来匹配请求

3.4.1、源码定义

image

value属性的别名是path,所以用path属性代替也可以;

value属性是字符串数组类型,所以可以设置多个值;

3.4.2、匹配多个请求的控制器示例

image

普通的servlet,也可以在web.xml的<servlet-mapping>标签中,设置多个<url-pattern>子标签,从而实现同样的效果

    @RequestMapping({"/hello","/hi"})

image

<a th:href="@{/test/hi}">测试/test/hi请求</a>

3.4.3、测试效果

image

image

image

image

3.5、注解的method属性

  • @RequestMapping注解的method属性的作用是,根据请求方式(get或post)匹配请求

  • 若当前请求的请求地址满足value属性,但是请求方式不满足method属性,
    则浏览器报错 405:Request method '请求方式' not supported

3.5.1、源码定义

image

method属性是RequestMethod数组类型,所以可以设置多个值;

image

RequestMethod是枚举类型,有固定的可选值

3.5.2、控制器示例

image

    @RequestMapping(value = {"/hello","/hi"},method = {RequestMethod.GET,RequestMethod.POST})

3.5.3、请求示例

image

<!--除了form表单和Ajax设置为post请求之外,其他诸如超链接、直接浏览器地址栏访问等均为get请求-->
<a th:href="@{/test/hello}">测试/test/hello请求</a>

<!--表单默认为get请求,使用post请求须显式设置-->
<form th:action="@{/test/hello}" method="post">
    <input type="submit" value="测试@RequestMapping注解的method属性的post请求">
</form>

3.5.4、测试效果

image

image

++++++++++++++++++++++++++分割线++++++++++++++++++++++++++

image

image

3.5.5、结合请求方式的派生注解

对于处理指定请求方式的控制器方法,SpringMVC中提供了@RequestMapping的派生注解

  • 处理get请求的派生注解-->@GetMapping

  • 处理post请求的派生注解-->@PostMapping

  • 处理put请求的派生注解-->@PutMapping

  • 处理delete请求的派生注解-->@DeleteMapping

image

    // 只处理post请求方式的请求
    @PostMapping("/hello")

image

image

++++++++++++++++++++++++++分割线++++++++++++++++++++++++++

image

image

3.6、注解的params属性(了解)

  • @RequestMapping注解的params属性的作用是,根据请求参数匹配请求

  • 浏览器发送的请求的请求参数,必须满足params属性的设置(如果有的话)
    否则报错:HTTP状态 400 - 错误的请求

3.6.1、源码定义

image

params属性是字符串数组类型,所以可以设置多个值;

注意:请求必须满足params属性所有值的要求。

3.6.2、params属性的四种表达式

  • "param":表示所匹配的请求的请求参数中,必须携带param参数

  • "!param":表示所匹配的请求的请求参数中,必须不能携带param参数

  • "param=value":表示所匹配的请求的请求参数中,必须携带param参数,且值必须为value

  • "param!=value":表示所匹配的请求的请求参数中,可以不携带param参数;若携带param参数,其值必须不能为value

3.6.3、控制器示例

image

    @RequestMapping(
            value = {"/hello","/hi"},
            method = {RequestMethod.GET,RequestMethod.POST},
            params = {"username","!password","age=18","gender!=女"}
            )

3.6.4、请求示例

image

<!--使用传统的?分隔符传参,虽然是有效果的,但thymeleaf语法会有错误提示-->
<a th:href="@{/test/hello?username=admin&age=18}">测试@RequestMapping注解的params属性(传统?传参)</a>

<br><br>

<!--thymeleaf语法的标准传参方式,注意字符串要用单引号-->
<a th:href="@{/test/hello(username='admin',age=18)}">测试@RequestMapping注解的params属性(thymeleaf语法传参)</a>

3.6.5、测试效果

image

image

++++++++++++++++++++++++++分割线++++++++++++++++++++++++++

image

image

++++++++++++++++++++++++++分割线++++++++++++++++++++++++++

image

image

3.7、注解的headers属性(了解)

  • @RequestMapping注解的headers属性的作用是,根据请求头信息匹配请求

  • 浏览器发送的请求的请求头信息,必须满足headers属性的设置(如果有的话)
    否则报错:HTTP状态 404 - 未找到

3.7.1、源码定义

image

headers属性是字符串数组类型,所以可以设置多个值;

注意:请求必须满足headers属性所有值的要求。

3.7.2、headers属性的四种表达式

  • "header":表示所匹配的请求,必须携带header请求头信息

  • "!header":表示所匹配的请求,必须不能携带header请求头信息

  • "header=value":表示所匹配的请求,必须携带header请求头信息,且值必须为value

  • "header!=value":表示所匹配的请求,可以不携带header请求头信息;若携带header请求头信息,其值必须不能为value

3.7.3、控制器示例

image

注意:请求头信息的键不区分大小写,但其值区分大小写

    @RequestMapping(
            value = {"/hello","/hi"},
            method = {RequestMethod.GET,RequestMethod.POST},
            params = {"username","!password","age=18","gender!=女"},
            headers = {"referer"}
            )

3.7.4、请求示例

image

image

Referer请求头表示请求的来源,本例的请求来源为http://localhost:8080/spring_mvc_demo/

image

如果是通过浏览器地址栏直接访问,是没有Referer(请求来源)的

3.8、ant风格的路径

3.8.1、通配符

  • ? :表示任意的单个字符(不包括 ? 和 / ,因为它们是分隔符)

  • * :表示任意个数的任意字符(不包括 ? 和 / )

  • ** :表示任意层数的任意目录(其用法是 /**/xxx 的方式)

3.8.2、? 通配符示例

image

    @RequestMapping("/a?a")
    public String testAnt(){
        return "success";
    }

image

image

image

3.8.3、* 通配符示例

image

    @RequestMapping("/a*a")
    public String testAnt(){
        return "success";
    }

image

image

image

3.8.4、** 通配符示例

image

    @RequestMapping("/**/aa")
    public String testAnt(){
        return "success";
    }

image

image

3.9、路径中的占位符(重点)

  • 原始风格的请求(?分隔符前面是路径,后面是参数):/deleteUser?id=1

  • RESTful 风格的请求(参数是路径的一部分):/user/delete/1

  • SpringMVC 路径中的占位符常用于RESTful风格中;

  • 在@RequestMapping注解的value属性中,通过占位符{xxx}表示路径中传输的数据;

  • 再通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参。

3.9.1、控制器示例

image

对于占位符的数据类型,@PathVariable注解会自动转换赋值给控制器方法的形参

    @RequestMapping("/rest/{restfulId}/{restfulUsername}")
    public String testRestful(@PathVariable("restfulId") Integer id,@PathVariable("restfulUsername") String username){
        System.out.println("id:"+id);
        System.out.println("username:"+username);
        return "success";
    }

3.9.2、请求示例

image

<a th:href="@{/test/rest/12345/zhangsan}">测试@RequestMapping注解的value属性中的占位符</a>

3.9.3、测试效果

image

image

image