SpringMVC 配置多視圖解析器(velocity,jsp)

來源:互聯網
上載者:User

標籤: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.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://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的映射 --><beanclass="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;}@Autowiredpublic 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


SpringMVC 配置多視圖解析器(velocity,jsp)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.