SpringMVC 配置多视图解析器(velocity,jsp)

1.自定义视图解析器

package com.zhaochao.controller;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

/**
 * 自定义视图解析(通过配置实现多视图整合,如jsp,velocity,freemarker,pdf,excel...)
 * @author zhaochao
 *
 */
public class JeeDevViewResolver implements ViewResolver  {

    private static Log logger = LogFactory.getLog(JeeDevViewResolver.class);

    public View resolveViewName(String viewName, Locale locale) throws Exception {
       for(Map.Entry<Set<String>, ViewResolver> map : viewResolverMap.entrySet()){
           Set<String> suffixs = map.getKey();
           for(String suffix : suffixs){
        	   System.out.println(suffix+" == "+viewName);
               if (viewName.endsWith(suffix)){
                   ViewResolver viewResolver = map.getValue();
                   if(null != viewResolver){
                       if (logger.isDebugEnabled()) {
                            logger.debug("found viewResolver '" + viewResolver + "' for viewName '" + viewName+ "'");
                        }
                       return viewResolver.resolveViewName(viewName, locale);
                   }
               }

           }
       }
       if(defaultViewResolver != null){
           return defaultViewResolver.resolveViewName(viewName+".jsp", locale);
       }
       // to allow for ViewResolver chaining
       return null;
    }
    private Map<Set<String>,ViewResolver> viewResolverMap = new HashMap<Set<String>,ViewResolver>();
    private ViewResolver defaultViewResolver = null;
    public Map<Set<String>, ViewResolver> getViewResolverMap() {
        return viewResolverMap;
    }
    public void setViewResolverMap(Map<Set<String>, ViewResolver> viewResolverMap) {
        this.viewResolverMap = viewResolverMap;
    }
    public ViewResolver getDefaultViewResolver() {
        return defaultViewResolver;
    }
    public void setDefaultViewResolver(ViewResolver defaultViewResolver) {
        this.defaultViewResolver = defaultViewResolver;
    }
}

2.SpringMVC配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	default-autowire="byName">

	<!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
	<context:component-scan base-package="com.zhaochao.controller" />

	<!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->
	<bean id="mappingJacksonHttpMessageConverter"
		class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
		<property name="supportedMediaTypes">
			<list>
				<value>text/html;charset=UTF-8</value>
			</list>
		</property>
	</bean>

	<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
			</list>
		</property>
	</bean>

	<bean id="viewResolver" class="com.zhaochao.controller.JeeDevViewResolver">
		<property name="defaultViewResolver" ref="jspViewResolver" />
		<property name="viewResolverMap">
			<map>
				<entry>
					<key>
						<set>
							<value>.vm</value>
						</set>
					</key>
					<ref bean="velocityViewResolver" />
				</entry>
				<entry>
					<key>
						<set>
							<value>jsp</value>
						</set>
					</key>
					<ref bean="jspViewResolver" />
				</entry>
			</map>
		</property>
	</bean>

	<bean id="beanNameViewResolver"
		class="org.springframework.web.servlet.view.BeanNameViewResolver" />

	<bean id="jspViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<!--<property name="suffix" value=".jsp"/> -->
	</bean>

	<!-- Velocity ViewResolver Configuration -->
	<bean id="velocityViewResolver"
		class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
		<property name="order" value="0" />
		<property name="contentType" value="text/html;charset=UTF-8" />
		<property name="requestContextAttribute" value="req" />
	</bean>

	<!-- Velocity Configuration -->
	<bean id="velocityConfig"
		class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
		<property name="configLocation" value="/WEB-INF/velocity.properties" />
		<property name="resourceLoaderPath" value="/WEB-INF/vm/" />
		<property name="velocityProperties">
			<props>
				<prop key="input.encoding">UTF-8</prop>
				<prop key="output.encoding">UTF-8</prop>
			</props>
		</property>
	</bean>

</beans>

3.Controller控制器

package com.zhaochao.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zhaochao.bean.user.UserBean;
import com.zhaochao.service.user.UserService;

@Controller
@RequestMapping("/userAction")
public class UserController {
	private UserService userService;
	public UserService getUserService() {
		return userService;
	}
	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@RequestMapping(value = "/def")
	public String def(HttpServletRequest request, ModelMap map) {
		map.put("name", "hello world");
		request.setAttribute("name", "hello wrod!");
		List<UserBean> users=userService.getUserEntities();
		map.put("name", "hello world");
		map.put("users", users);
		return "def";
	}
	@RequestMapping(value = "/jsp")
	public String test1(HttpServletRequest request, ModelMap map) {
		map.put("name", "hello world");
		request.setAttribute("name", "hello wrod!");
		List<UserBean> users=userService.getUserEntities();
		map.put("name", "hello world");
		map.put("users", users);
		return "index.jsp";
	}
	@RequestMapping(value = "/vm")
	public String test3(HttpServletRequest request, ModelMap map) {
		List<UserBean> users=userService.getUserEntities();
		map.put("name", "hello world");
		map.put("users", users);
		return "index.vm";
	}

}

4.View层目录结构

5.效果

完整项目下载地址

http://download.csdn.net/detail/whzhaochao/8631177

时间: 2024-10-20 11:44:25

SpringMVC 配置多视图解析器(velocity,jsp)的相关文章

SpringMVC自定义多视图解析器

实现通过请求url后缀判断返回值类型, 例如 localhost:8080/list 返回JSP页面, localhost:8080/list.json返回json格式数据 1.创建一枚举返回值类型 public enum ResultType { REDIRECT, JSP, JSON, XML } 2.创建自定义的viewResolver 1 public class JsonViewResolver implements ViewResolver { 2 3 private View vi

beetl 配置多视图解析器

如下配置,指定了三个视图解析器,一个用于beetl页面渲染,一个用于cms,采用了beetl技术,另外一个一些遗留的页面采用jsp <bean name="beetlConfig" class="org.beetl.ext.spring.BeetlGroupUtilConfiguration" init-method="init"> <property name="configFileResource" va

springmvc 返回ModelAndView视图解析不到jsp

问题重现 : 我在页面中请求的路径是, 类中对应的映射为, 但是实际执行是并没有把返回路径映射到 userinfo/MyJsp.jsp ,而是映射到了 userinfo/adduserinfo.jsp. 解决方法: 导致该问题出现的原因为导入的 ModelAndView 包错误,此时引入的包为org.springframework.web.portlet.ModelAndView;而正确包应该是 import org.springframework.web.servlet.ModelAndVie

SpringMVC与Freemarker的集成以及多视图解析器配置

一.Spring MVC视图解析器 视图解析器的工作流程大致是这样的:Controller的某个方法执行完成以后,返回一个视图(比如:listUser),视图解析器要做的工作就是找到某个对象 来完成视图的渲染,或者跳转到其他的逻辑视图.这里的渲染对象通常就是我们的jsp文件或者我们下面用的Freemarker(例如listUser.jsp或者 listUser.ftl).渲染完成以后,将解析结果发送到客户端浏览器. 下面介绍一下本文需要用到的解析器(更多解析器资料,请参考 http://e-fr

SpringMVC中用于绑定请求数据的注解以及配置视图解析器

SpringMVC中用于绑定请求数据的注解 在上一篇文章中我们简单介绍了@RequestMapping与@RequestParam注解,知道了如何去配置地址映射,本篇则介绍一些用于处理request数据的注解. [email protected]注解,该注解用于处理request中的header部分,也就是http请求头的部分,它可以把header部分的值绑定到方法的参数上,示例: package org.zero01.test; import org.springframework.stere

SpringMVC——视图和视图解析器

请求处理方法执行完成后,最终返回一个 ModelAndView对象.对于那些返回 String,View 或 ModeMap 等类型的处理方法,Spring MVC 也会在内部将它们装配成一个ModelAndView 对象,它包含了逻辑名和模型对象的视图 Spring MVC 借助视图解析器(ViewResolver)得到最终的视图对象(View),最终的视图可以是 JSP ,也可能是Excel.JFreeChart 等各种表现形式的视图 对于最终究竟采取何种视图对象对模型数据进行渲染,处理器并

SpringMVC配置多视图JSP+freemarker,实践成功!(网上好多坑)

今天自己配置了一下SpringMVC 的多视图,本以为很简单,实践后发现各种问题,在网上查了很多资料,最后还是选择了看源码,终于知道为什么失败了,下面介绍一下. 失败配置! 成功只是改了几个小地方. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="ht

学习SpringMVC——说说视图解析器

各位前排的,后排的,都不要走,咱趁热打铁,就这一股劲我们今天来说说spring mvc的视图解析器(不要抢,都有位子~~~) 相信大家在昨天那篇如何获取请求参数篇中都已经领略到了spring mvc注解的魅力和套路了.搭上@RequestMapping的便车,我们可以去到我们想去的地方(方法)去,借助@RequestParam.@PathVariable等我们可以得到请求中想要的参数值,最终还能够通过神奇的“return SUCCESS”到达我们的目的地.今天主要就来说说在达到目的地的路上,我们

SpringMvc:视图和视图解析器

请求处理方法执行完成后,最终返回一个ModelAndView对象,对于返回String,View或ModelMap等类型的处理方法,SpringMvc也会在内部将它们装配成一个ModelAndView对象的,它包含了逻辑名和模型对象的视图. SpringMvc借助视图解析器(ViewResolver)得到最终的视图对象(View),最终的视图可能是JSP,也可能是Excel等各种表现形式的视图.对于最终采取何种视图对象对模型数据进行渲染,处理器并不关心,处理器的工作重点聚焦在生产模型数据的工作上