网上搜了下资料,自己也实战了下。分享一下。
传统的web.xml写法不变,如下为相关配置信息:
<servlet>
<servlet-name>myportal</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myportal</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
之所以将url-pattern配置成*.html,一是隐藏技术实现,二是增加搜索引擎的搜索概率。看个人爱好。
关键是对应的myportal-servlet.xml文件中的配置.
<bean id="viewResolver" class="com.myportal.web.core.MultipleViewResolver">
<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/</value>
</property>
</bean>
</entry>
<entry key="vm">
<bean class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="contentType" value="text/html;charset=UTF-8" />
</bean>
</entry>
</map>
</property>
</bean>
然后大家在自己的Controller类里面必须返回如下视图:new ModelAndView("test.jsp");或者new ModelAndView("test.vm");
最后是自己写的ViewResolver,如下:
public class MultipleViewResolver implements ViewResolver
{
private Map<String, ViewResolver> resolvers;
public void setResolvers(Map<String, ViewResolver> resolvers)
{
this.resolvers = resolvers;
}
public View resolveViewName(String viewName, Locale locale) throws Exception {
int n = viewName.lastIndexOf(".");
if(n==(-1)) return null;
// 获得扩展名:
String suffix = viewName.substring(n+1);
// 取出对应的ViewResolver:
ViewResolver resolver = resolvers.get(suffix);
if(resolver!=null)
return resolver.resolveViewName(viewName, locale);
// 没有找到对应的ViewResolver就抛异常:
return null;
}
}
当然,大家可以对自己写的ViewResovler进行功能上的丰富,比如:设定默认的视图解析为jsp,那你的Controller的View就可以偷懒写成new ModelAndView("test")了。基本功能有了,完善慢慢来。