再做页面静态化处理时,有时候我们需要 两种或者两种以上的视图解析方式,比如 jsp,html,json,jstl,ftl等等,显然默认的 springmvc 只配置一种视图解析方式是满足不了我们的,但是放心,springmvc提供了配置多视图解析的方式:
比如:一种视图解析用来 解析 freemarker静态化后的html,另一种视图解析用来解析 jsp(jstl)
网上好多方式都有提到用 order 来设置解析器的优先级,但经试验,优先级低的还是生效不了,不知道是否有其他的解决方法?最终查看源码才发现原来springmvc 只给我们提供了 待我们重写的方法,看源码:
[java] view plain copy
/*** Eclipse Class Decompiler plugin, copyright (c) 2012 Chao Chen (cnfree2000@hotmail.com) ***/
package org.springframework.web.servlet.view;
import java.util.Locale;
import org.springframework.beans.factory.InitializingBean;
public
abstract class AbstractUrlBasedView extends AbstractView implements
InitializingBean {
private String url;
protected AbstractUrlBasedView() {
}
protected AbstractUrlBasedView(String url) {
this.url = url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return this.url;
}
public void afterPropertiesSet()
throws Exception {
if ((isUrlRequired()) && (getUrl() ==
null))
throw new IllegalArgumentException(
"Property 'url' is required");
}
protected boolean isUrlRequired() {
return true;
}
<span style=
"background-color: rgb(255, 255, 204);">public boolean checkResource(Locale locale)
throws Exception {
return true;
}</span>
public String toString() {
StringBuilder sb =
new StringBuilder(
super.toString());
sb.append(
"; URL [").append(getUrl()).append(
"]");
return sb.toString();
}
}
所以怎么做就很明确了:
第一步:新建一个html的解析器并继承 InternalResourceView 后重写 checkResource
[java] view plain copy
package com.izhbg.typz.common.springmvc.view;
import java.io.File;
import java.util.Locale;
import org.springframework.web.servlet.view.InternalResourceView;
/**
*
* @ClassName: HtmlResourceView
* @author caixl
* @date 2016-6-8 上午11:01:41
*
*/
public
class HtmlResourceView extends InternalResourceView {
@Override
public boolean checkResource(Locale locale) {
File file =
new File(
this.getServletContext().getRealPath(
"/") + getUrl());
return file.exists();
}
}
第二步:在xml配置文件中 指定解析器的 viewClass为该解析类
[html] view plain copy
<!-- 定义HTML文件的位置 -->
<bean id=
"htmlviewResolver"
class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name=
"viewClass" value=
"com.izhbg.typz.common.springmvc.view.HtmlResourceView"/>
<property name=
"order" value=
"0" />
<property name=
"prefix" value=
"/cms/"/>
<property name=
"suffix" value=
".html" />
<property name=
"contentType" value=
"text/html;charset=UTF-8"></property>
</bean>
<!-- 定义JSP文件的位置 -->
<bean id=
"jspViewResolver" class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name=
"order" value=
"1" />
<property name=
"prefix" value=
"/views/"/>
<property name=
"suffix" value=
".jsp"/>
</bean>
源码可参考 开源项目:https: