第二章 @RequestMapping详解

target

掌握@RequestMapping注解的作用
掌握@RequestMapping 可标注的位置
简单了解 @RequestMapping 注解源码
了解@RequestMapping注解中参数的使用
掌握 Ant风格的路径

1. @RequestMapping 概述

在一个控制器中,可以有很多方法,这些方法都是用来处理请求的。那么如何将请求与处理方法一一对应呢?使用@RequestMapping 注解。

压住command键,鼠标单击@ RequestMapping ,可以查看到@ RequestMapping 源码:

package org.springframework.web.bind.annotation;
@Target({ElementType.METHOD, ElementType.TYPE}) 
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
  String[] value() default {}; 
  RequestMethod[] method() default {}; 
  String[] params() default {};
  String[] headers() default {};
  String[] consumes() default {};
  String[] produces() default {}; 
}

可以发现@ RequestMapping注解中可以设置映射值、映射方法、映射参数、请求头等,下面详细讲解。

2. @RequestMapping 可标注的位置

源码@Target({ElementType.METHOD, ElementType.TYPE})表明 @RequestMapping 注解可以标注在方法上,也可以标注在类上。

2.1 标注在类 + 方法上

在类和方法上都标注@RequestMapping注解,就意味着请求先映射到标注类的位置,然后再映射到该类的方法上。

@Controller  
@RequestMapping("helloWorldController")
public class HelloWorldController {

    @RequestMapping(value = "/helloworld")
    public String helloworld() {
        
        System.out.println("hello,world");
        
        return "success"; 
    }
}

访问路径:localhost:8080/项目名/helloWorldController/helloworld

2.2 只标注在方法上

@RequestMapping注解是可以只标注在方法上的,这样请求就直接映射到标注的方法上。

@Controller  
public class HelloWorldController {

    @RequestMapping(value = "/helloworld")
    public String helloworld() {
        
        System.out.println("hello,world");
        
        return "success"; 
    }
}

访问路径:localhost:8080/项目名/helloworld

3. @RequestMapping 中的参数

3.1 headers参数(了解)

可以使用 headers 参数来更加精确的约束映射得请求头信息。
打开浏览器的调试模式,可以在 Network中查看请求头信息:

请求头信息

🌰测试请求头

新建动态web项目:SpringMVC-02

(导入 jar包、web.xml配置、springmvc.xml配置、success.jsp页面步骤全部略,参考第一章,本章案例只讲核心知识点,不重复造轮子。建议新手朋友不要复制项目,一定多练习,才能掌握springmvc运行原理)

控制器代码:

package com.lee.springmvc.controller;

@Controller
public class SpringMvcController {

    @RequestMapping(value = "/testHeaders", headers = {"Accept-Language=zh-CN,zh;q=0.9"})
    public String testHeaders(){
        System.out.println("testHeaders...");
        return "success";       
    }
}

部署项目,浏览器请求URL:http://localhost:8080/SpringMVC-02/testHeaders

如果headers 里面的参数写的和使用的浏览器信息不符,就会映射不到testHeaders()方法。

3.2 映射请求参数(了解)

可以在@RequestMapping注解中设置请求参数信息,这些请求参数会约束请求信息,以保证前台的请求是合法的。
映射请求参数使用 params 属性设置。

① params 支持简单的表达式:

  • param1: 表示请求必须包含名为 param1 的请求参数
  • !param1: 表示请求不能包含名为 param1 的请求参数
  • param1!=value1: 表示请求如果包含名为 param1 的请求参数,其值不能为 value1。当然请求也可以不包含参数param1。
  • {"param1=value1", "param2"}: 请求必须包含名为 param1 和 param2 的两个请求参数,且 param1 参数的值必须为 value1

② 测试

控制器代码为:

package com.lee.springmvc.controller;

@Controller
public class SpringMvcController {

    @RequestMapping(value = "/testParams", params = { "username", "age!=10" })
    public String testParams() {
        System.out.println("testParams...");
        return "success";

    }
}

前端请求:

3.3 请求方法(重点)

浏览器向服务器发送请求,请求方式有很多,比如:get、post等。可以使用 method 属性来约束请求方式。
比如在@RequestMapping注解里加一个方法限定:method = RequestMethod.POST,则请求必须是post的,否则就会发生错误。
按住command,鼠标点击 @RequestMapping 注解:

public @interface RequestMapping {
  ......
/**
     * The HTTP request methods to map to, narrowing the primary mapping:
     * GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE.
     * <p><b>Supported at the type level as well as at the method level!</b>
     * When used at the type level, all method-level mappings inherit
     * this HTTP method restriction (i.e. the type-level restriction
     * gets checked before the handler method is even resolved).
     * <p>Supported for Servlet environments as well as Portlet 2.0 environments.
     */
    RequestMethod[] method() default {};
  
  ...
    
}

可以发现,支持的请求方法有 GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE。

🌰演示 method的使用:

①定义控制器:

package com.lee.springmvc.controller;

@Controller
public class SpringMvcController {

     @RequestMapping(value="/testMethord",method=RequestMethod.POST) 
      public String testMethord(){
        System.out.println("testMethord...");
        return "success"; 
      }
}

② 以get方式请求:

<a href="testMethord">testMethord</a>

请求失败:


方法不允许

映射方法中明确要求请求方式为 post,所以get不被允许。

③以POST方式请求

<form action="testMethord" method="post">
 <input type="submit">
</form>

请求成功。

4. Ant 路径⻛格

Ant风格的路径表达式在日常开发中进行一些系统配置的时候非常有用,就是使用通配符来达到模糊匹配的效果。

4.1 匹配符

Ant ⻛格资源地址支持 3 种匹配符:

?:匹配文件名中的一个字符
*:匹配文件名中的任意多个字符
**:匹配多层路径

4.2 实例

/user/*/createUser   匹配 /user/aaa/createUser、/user/bbb/createUser 等 URL 
/user/**/createUser  匹配 /user/createUser、/user/aaa/bbb/createUser 等 URL 
/user/createUser??   匹配 /user/createUseraa、/user/createUserbb 等 URL

4.3 测试

① ?

@RequestMapping("testPath/abc??")
public String testPath() {
  System.out.println("testPath...");
  return "success";
}

合法请求路径:http://localhost:8080/SpringMVC-02/testPath/abcxx

注意:

请求连接里不能带问号:http://localhost:8080/SpringMVC-02/testPath/abc??,这是不合法的。

② *

@RequestMapping("testPath/abc*")
public String testPath() {
  System.out.println("testPath...");
  return "success";
}

合法请求路径:

http://localhost:8080/SpringMVC-02/testPath/abc
http://localhost:8080/SpringMVC-02/testPath/abcss

错误路径:
http://localhost:8080/SpringMVC-02/testPath/abc/a

③**

@RequestMapping("testPath/abc/**/create")
public String testPath() {
  System.out.println("testPath...");
  return "success";
}

请求路径:

http://localhost:8080/SpringMVC-02/testPath/abc/create
http://localhost:8080/SpringMVC-02/testPath/abc/asdf/cdf/create

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容