SpringMVC中DispatcherServlet通过访问SimpleUrlHandlerMapping获得页面的url和具体后端控制器之间的映射
下面,分析一下SimpleUrlHandlerMapping源码,了解它的作用机理:
public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {
private final Map<String, Object> urlMap = new LinkedHashMap();
public SimpleUrlHandlerMapping() {
}
public void setMappings(Properties mappings) {
CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap);
}
public void setUrlMap(Map<String, ?> urlMap) {
this.urlMap.putAll(urlMap);
}
public Map<String, ?> getUrlMap() {
return this.urlMap;
}
public void initApplicationContext() throws BeansException {
super.initApplicationContext();
this.registerHandlers(this.urlMap);
}
protected void registerHandlers(Map<String, Object> urlMap) throws BeansException {
String url;
Object handler;
if (urlMap.isEmpty()) {
this.logger.warn("Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping");
} else {
for(Iterator var2 = urlMap.entrySet().iterator(); var2.hasNext(); this.registerHandler(url, handler)) {
Entry<String, Object> entry = (Entry)var2.next();
url = (String)entry.getKey();
handler = entry.getValue();
if (!url.startsWith("/")) {
url = "/" + url;
}
if (handler instanceof String) {
handler = ((String)handler).trim();
}
}
}
}
}
可以看到,它继承于AbstractUrlHandlerMapping,主要是对urlMap进行设置,即创建url与后端控制器映射,其中主要有两种设置方法,第一种为用set方法直接设置,可以在spring配置文件中配置urlMap
<property name="mappings">
<props>
<prop key="">helloController</prop>
</props>
</property>
<property name="urlMap">
<map>
<entry key="" value=""/>
</map>
</property>
或者说可以用Properties设置参数,此时设置xml文档为<pros></props>在<prop key>class</prop>设置key和映射的class文件
而如果用Properties设置参数,它内部会调用setMappings方法,而在方法中又调用了CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap)方法,可以猜想,此方法是解析properties文件获得相应的映射关系,然后在赋值给urlMap,查看其源码:
public static <K, V> void mergePropertiesIntoMap(Properties props, Map<K, V> map) {
if (map == null) {
throw new IllegalArgumentException("Map must not be null");
} else {
String key;
Object value;
if (props != null) {
for(Enumeration en = props.propertyNames(); en.hasMoreElements(); map.put(key, value)) {
key = (String)en.nextElement();
value = props.get(key);
if (value == null) {
value = props.getProperty(key);
}
}
}
}
}
可以看出,如果map不是null时,用Enumeration解析Properties文件,将配置文件中key和value赋值给map
最下面的registerHandlers方法则是将urlMap解析并将其数据放入registerHandler等待调用.