例子程序
程序结构:
-
SpringMVC使用@RequestMapping注解为控制器指定可以处理哪些URL请求
-
在控制器的类定义及方法定义处都可标注@RequestMapping
- 类定义处: 提供初步的请求映射信息。相对于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支持简单的表达式:
- param1:表示请求必须包含名为param1的请求参数
- !param1:表示请求不能包含名为param1的请求参数
- param1!=value1:表示请求包含名为param1的请求参数,但其值不能为value!
- {“param1=value1”,“param2”}:请求必须包含名为param1和param2的两个请求参数,且param1参数的值必须为value1
请看上图
使用@RequestMapping映射请求
- Ant 风格资源地址支持3种匹配符:
- ?:匹配文件名中的一个字符
- “*”:匹配文件名中的任意字符
- “**”:匹配多层路径
- @RequestMapping还支持Ant风格的URL:
- /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