看看源码你会找到答案:
public abstract class AbstractUrlBasedView{
...
public boolean checkResource(Locale locale) throws Exception {
return true;
}
...
}
public class InternalResourceView extends AbstractUrlBasedView {
//!!not override the checkResource method!!
}
public class FreeMarkerView extends AbstractTemplateView {
...
@Override
public boolean checkResource(Locale locale) throws Exception {
try {
// Check that we can get the template, even if we might subsequently get it again.
getTemplate(getUrl(), locale);
return true;
}
catch (FileNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("No FreeMarker view found for URL: " + getUrl());
}
return false;
}
catch (ParseException ex) {
throw new ApplicationContextException(
"Failed to parse FreeMarker template for URL [" + getUrl() + "]", ex);
}
catch (IOException ex) {
throw new ApplicationContextException(
"Could not load FreeMarker template for URL [" + getUrl() + "]", ex);
}
}
...
}
这样您就可以扩展 InternalResourceView,如下所示:
public class MyInternalResourceView extends InternalResourceView {
private static final boolean SEP_IS_SLASH = File.separatorChar == '/';
protected File getTemplate(String name, Locale locale) throws IOException {
File source;
if(getServletContext()!=null){
name = getServletContext().getRealPath("")+name;
source = new File( SEP_IS_SLASH ? name : name.replace('/',
File.separatorChar));
}
else{
source = new File( SEP_IS_SLASH ? name : name.replace('/',
File.separatorChar));
}
if (!source.isFile()) {
return null;
}
return source;
}
@Override
public boolean checkResource(Locale locale) throws Exception {
try {
// Check that we can get the template, even if we might subsequently
// get it again.
return getTemplate(getUrl(), locale)!=null;
} catch (IOException ex) {
return false;
}
}
}
并在 viewResolver 中设置您的视图类
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="com.xxxx.MyInternalResourceView" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:contentType="text/html;charset=UTF-8" />