SpringMVC_2_使用@RequestMapping映射请求

例子程序

程序结构:

在这里插入图片描述

  • SpringMVC使用@RequestMapping注解为控制器指定可以处理哪些URL请求

  • 在控制器的类定义及方法定义处都可标注@RequestMapping

  1. 类定义处: 提供初步的请求映射信息。相对于WEB应用的根目录

在这里插入图片描述
在这里插入图片描述

             2.方法处:提供进一步的细分映射信息。相对于类定义处的URL。若类定义处未标注@RequestMapping,则方法处标记的URL相对于WEB应用的根目录

在这里插入图片描述
在这里插入图片描述

  • DispatcherServlet截获请求后,就通过控制器上@RequestMapping提供的映射信息确定请求所对应的处理方法

web/WEB-INF/springDispatcherServlet-servlet.xml

<?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 http://www.springframework.org/schema/context/spring-context.xsd">


    <!--配置自定扫描的包-->
    <context:component-scan base-package="com.springmvc.handlers"></context:component-scan>

    <!--配置视图解析器: 如何把handler方法返回值解析为实际的物理视图-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>




映射请求参数、请求方法或请求头

  • @RequestMapping除了可以使用请求URL映射请求外,还可以使用请求方法、请求参数及请求头映射请求

在这里插入图片描述
在这里插入图片描述

  • @RequestMapping的value、method、params、及heads分别表示请求URL、请求方法请求参数及请求头的映射条件,他们之间是的关系,联合使用多个条件可让请求映射更加精确化

在这里插入图片描述
在这里插入图片描述

  • params和headers支持简单的表达式
  1. param1:表示请求必须包含名为param1的请求参数
  2. !param1:表示请求不能包含名为param1的请求参数
  3. param1!=value1:表示请求包含名为param1的请求参数,但其值不能为value!
  4. {“param1=value1”,“param2”}:请求必须包含名为param1和param2的两个请求参数,且param1参数的值必须为value1

请看上图



使用@RequestMapping映射请求

  • Ant 风格资源地址支持3种匹配符:
  1. ?:匹配文件名中的一个字符
  2. “*”:匹配文件名中的任意字符
  3. “**”:匹配多层路径
  • @RequestMapping还支持Ant风格的URL
  1. /user/*/createUser: 匹配/user/aaa/createUser、/user/bbb/createUser等URL
  2. /user/**/createUser: 匹配/user/createUser、/user/aaa/bbb/createUser等URL
  3. /user/createUser??: 匹配/user/createUseraa、/user/createUserbb等URL

在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42036647/article/details/85223892
今日推荐