处理器映射器:根据请求URL查找对应的Handler(处理器)
处理器适配器:根据请求URL执行对应的Handler(处理器)
一、常见的处理器映射器(非注解类)
1、BeanNameUrlHandlerMapping(org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping)
查看源码:
public class BeanNameUrlHandlerMapping extends AbstractDetectingUrlHandlerMapping {
/**
* Checks name and aliases of the given bean for URLs, starting with "/".
*/
@Override
protected String[] determineUrlsForHandler(String beanName) {
List<String> urls = new ArrayList<String>();
if (beanName.startsWith("/")) {
urls.add(beanName);
}
String[] aliases = getApplicationContext().getAliases(beanName);
for (String alias : aliases) {
if (alias.startsWith("/")) {
urls.add(alias);
}
}
return StringUtils.toStringArray(urls);
}
}
可见,该映射器是解析handler bean的name属性,跟URL进行匹配。
该映射器的配置:
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
使用:
使用该映射器的时候,handler的配置如下:
<bean id="itemHandler01" name="/itemlist.action" class="com.js.springmvc01.ItemController01"/>
bean的name属性为请求的URL,匹配的URL请求将会被DispatcherServlet请求适配器去调用class属性所指向的handler去处理。
2、SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping)
查看源码:
public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {
private final Map<String, Object> urlMap = new HashMap<String, Object>();
/**
* Map URL paths to handler bean names.
* This is the typical way of configuring this HandlerMapping.
* <p>Supports direct URL matches and Ant-style pattern matches. For syntax
* details, see the {@link org.springframework.util.AntPathMatcher} javadoc.
* @param mappings properties with URLs as keys and bean names as values
* @see #setUrlMap
*/
public void setMappings(Properties mappings) {
CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap);
}
/**
* Set a Map with URL paths as keys and handler beans (or handler bean names)
* as values. Convenient for population with bean references.
* <p>Supports direct URL matches and Ant-style pattern matches. For syntax
* details, see the {@link org.springframework.util.AntPathMatcher} javadoc.
* @param urlMap map with URLs as keys and beans as values
* @see #setMappings
*/
public void setUrlMap(Map<String, ?> urlMap) {
this.urlMap.putAll(urlMap);
}
可见,该映射器需要注入mapping属性,该变量就是handler bean的id与URL的对应关系,类似于键值对。
该映射器的配置:
<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/itemlist01.action">itemHandler01</prop>
<prop key="/itemlist02.action">itemHandler02</prop>
</props>
</property>
</bean>
使用:
使用该映射器的时候,handler的配置如下:
<bean id="itemHandler02" class="com.js.springmvc01.ItemController02"/>
访问key值指向的URL,则会由id值与value值相等的handler去处理该请求。