5.實現MultiMethodControllerUrlHandlerMapping
我們在上面討論過了怎麼實現MultiMethodControllerUrlHandlerMapping,要實現為 具體的代碼,我們可以通過擴展 org.springframework.web.servlet.handler.AbstractUrlHandlerMapping。 AbstractUrlHandlerMapping擴展了 org.springframework.web.context.support.WebApplicationObjectSupport。 WebApplicationObjectSupport可以獲得當前WebApplicationContext。
1. 重寫initApplicationContext方法,在context中查找所有MultiActionController 類型的bean,把MultiActionController的urlMethodmappings屬性的key值為key值, MultiActionController實例為鍵值的鍵值對添加到一個urlMap中。
public class MultiMethodControllerUrlHandlerMapping extends AbstractUrlHandlerMapping...{
private Map urlMap = new HashMap();
public void initApplicationContext() throws BeansException ...{
initialUrlMap();
}
protected void initialUrlMap()throws BeansException...{
//找查所有MultiMethodController類型和子類型的bean到一個map中,bean Name 為key值 ,bean實例為value值
Map matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(
getWebApplicationContext(),
MultiMethodController.class, true, false);
List controllers = null;
if(!matchingBeans.isEmpty())...{
controllers = new ArrayList(matchingBeans.values());
for(int i = 0; controllers != null && i < controllers.size();i++)...{
MultiMethodController controller = (MultiMethodController) controllers.get(i);
Properties urlPros = controller.getUrlMethodmappings();
Iterator itr = urlPros.keySet().iterator();
for(;itr.hasNext();)...{
String url = (String)itr.next();
urlMap.put(url,controller);
}
}
}
}