springMVC源码分析--ControllerBeanNameHandlerMapping(八)

时间:2021-01-19 15:19:35

在上一篇博客springMVC源码分析--AbstractControllerUrlHandlerMapping(六)中我们介绍到AbstractControllerUrlHandlerMapping定义了抽象方法buildUrlsForHandler,接下来我们看看在其子类ControllerBeanNameHandlerMapping中的实现。

springMVC源码分析--ControllerBeanNameHandlerMapping(八)

ControllerBeanNameHandlerMapping中buildUrlsForHandler的实现如下,还是讲beanName及其别名作为url

@Override
	protected String[] buildUrlsForHandler(String beanName, Class<?> beanClass) {
		List<String> urls = new ArrayList<String>();
		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实现的功能很简单,就是将beanName及其别名作为url返回。

ControllerBeanNameHandlerMapping源码如下:

public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandlerMapping {

	private String urlPrefix = "";

	private String urlSuffix = "";

	public void setUrlPrefix(String urlPrefix) {
		this.urlPrefix = (urlPrefix != null ? urlPrefix : "");
	}

	public void setUrlSuffix(String urlSuffix) {
		this.urlSuffix = (urlSuffix != null ? urlSuffix : "");
	}

	//通过beanName构造url数组
	@Override
	protected String[] buildUrlsForHandler(String beanName, Class<?> beanClass) {
		List<String> urls = new ArrayList<String>();
		urls.add(generatePathMapping(beanName));
		String[] aliases = getApplicationContext().getAliases(beanName);
		for (String alias : aliases) {
			urls.add(generatePathMapping(alias));
		}
		return StringUtils.toStringArray(urls);
	}
	//给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();
	}

}