ControllerBeanNameHandlerMapping类详解 - HandlerMapping系列五
ControllerBeanNameHandlerMapping是AbstractControllerUrlHandlerMapping的实现类,通过声明在Web应用程序环境中的控制器类型来注册处理器映射的。它从控制器的Bean名字转换出控制器所服务的URL Pattern。这个转换规则是,把Bean名字加上前缀和后缀构成URL Pattern,然后,使用得到的Pattern匹配请求的URL,如果匹配成功,则使用匹配的Bean作为处理器返回。
buildUrlsForHandler() beanName及其别名作为url
@Override protected String[] buildUrlsForHandler(String beanName, Class beanClass) { Listurls = new ArrayList(); urls.add(generatePathMapping(beanName)); String[] aliases = getApplicationContext().getAliases(beanName); for (String alias : aliases) { urls.add(generatePathMapping(alias)); } return StringUtils.toStringArray(urls); }
generatePathMapping() beanName加上以下前缀等
protected String generatePathMapping(String beanName) { String name = (beanName.startsWith("/") ? beanName : "/" + beanName); StringBuilder path = new StringBuilder(); if (!name.startsWith(this.urlPrefix)) { path.append(this.urlPrefix); } path.append(name); if (!name.endsWith(this.urlSuffix)) { path.append(this.urlSuffix); } return path.toString(); }
ControllerBeanNameHandlerMapping源码
public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandlerMapping { private String urlPrefix = ""; private String urlSuffix = ""; @Override protected String[] buildUrlsForHandler(String beanName, Class beanClass) { Listurls = new ArrayList(); // 根据Bean名产生URL Pattern urls.add(generatePathMaping(beanName)); // 对于Bean名的别名,以同样的规则产生URL Pattern String[] aliases = getApplicationContext().getAliases(beanName); for (String alias : aliases) { urls.add(generatePathMapping(alias)); } // 返回URL Pattern数组 return StringUtils.toStringArray(urls); } /** * Prepends a '/' if required and appends the URL suffix to the name. */ protected String generatePathMapping(String beanName) { // 如果bean名不是以斜线(/)开头,则增加斜线(/) String name = (beanName.startsWith("/") ? beanName : "/" + beanName); StringBuilder path = new StringBuilder(); // 添加前缀 if (!name.startsWith(this.urlPrefix)) { path.append(this.urlPrefix); } path.append(name); // 添加后缀 if (!name.endsWith(this.urlSuffix)) { path.append(this.urlSuffix); } return path.toString(); } }
ControllerBeanNameHandlerMapping实现的功能很简单,就是将beanName及其别名作为url返回。
版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。