论坛首页 入门技术论坛

无聊贴一个Spring multiple view resolver

浏览 2784 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-06-05   最后修改:2009-06-05

 

package org.dy.ext.spring.web;

import java.util.Locale;
import java.util.Map;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

public class MultipleViewResolver extends UrlBasedViewResolver {

	private Map<String, ViewResolver> resolvers;
	
	@Override
	protected View loadView(String viewName, Locale locale) throws Exception {
		// TODO Auto-generated method stub
		return internalResolveViewName(viewName, locale);
	}

	public View internalResolveViewName(String viewName, Locale locale)
			throws Exception {
		// 获得扩展名
		int n = viewName.lastIndexOf(".");
		if (n == -1)
			return null;
		String suffix = viewName.substring(n + 1);

		String resolverViewKey = "";
		// 查找 eg. zftl,ftl = oneResolver => ftl = oneResolver
		for (String key : resolvers.keySet()) {
			String[] arr = key.split(",");
			for (String subViewName : arr) {
				if (subViewName.equals(suffix)) {
					resolverViewKey = key;
					break;
				}
			}
		}

		// 取出对应的ViewResolver:
		ViewResolver resolver = resolvers.get(resolverViewKey);
		if (resolver != null)
			return resolver.resolveViewName(viewName, locale);

		// 没有找到对应的ViewResolver就抛异常
		return null;
	}

	public Map<String, ViewResolver> getResolvers() {
		return resolvers;
	}

	public void setResolvers(Map<String, ViewResolver> resolvers) {
		this.resolvers = resolvers;
	}

}
 

 

<bean id="viewResolver"
		class="org.dy.ext.spring.web.MultipleViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="resolvers">
			<map>
				<entry key="jsp">
					<bean
						class="org.springframework.web.servlet.view.InternalResourceViewResolver">
						<property name="viewClass"
							value="org.springframework.web.servlet.view.JstlView" />
						<property name="prefix" value="/WEB-INF/jsp/" />
					</bean>
				</entry>
				<!-- 其中的js/css表示当需要freemarker动态生成js/css文件 -->
				<entry key="ftl,zftl,js,css">
					<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
						<property name="cache">
							<value>true</value>
						</property>
						<property name="viewClass">
							<value>
								org.springframework.web.servlet.view.freemarker.FreeMarkerView
							</value>
						</property>
						<property name="contentType">
							<value>text/html;charset=utf-8</value>
						</property>
						<property name="exposeSpringMacroHelpers">
							<value>true</value>
						</property>
					</bean>
				</entry>
			</map>
		</property>
	</bean>
							
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics