如果想在spring mvc应用程序中使用多个视图解析器,那么可以使用order
属性设置优先级顺序。 以下示例显示如何在spring web mvc框架中使用resourcebundleviewresolver
和internalresourceviewresolver
。
multipleresolver-servlet.xml 配置如下所示 -
<bean class="org.springframework.web.servlet.view.resourcebundleviewresolver">
<property name="basename" value="views" />
<property name="order" value="0" />
</bean>
<bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
<property name="prefix" value="/web-inf/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
这里order
属性定义了视图解析器的排序。0
作为第一解析器,1
作为下一解析器,等等。
views.properties 配置如下所示 -
hello.(class)=org.springframework.web.servlet.view.jstlview
hello.url=/web-inf/jsp/hello.jsp
例如,使用上面的配置,如果uri
:
/hello
请求,dispatcherservlet
会将请求转发到由views.properties
中定义的hello
对应的 hello.jsp
。hello
”是要匹配的视图名称。class
指定视图类型,url
是视图的位置。首先,使用eclipse ide,并按照以下步骤使用spring web framework开发基于动态表单的web应用程序:
com.h3.springmvc
包下创建一个java类hellocontroller
。jsp
子文件夹下创建一个视图文件:hello.jsp
。src
文件夹下创建属性文件views.properties
。classpath
中。完整的项目文件目录结构如下所示 -
hellocontroller.java 的代码如下所示 -
package com.h3.springmvc;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.ui.modelmap;
@controller
@requestmapping("/hello")
public class hellocontroller{
@requestmapping(method = requestmethod.get)
public string printhello(modelmap model) {
model.addattribute("message", "hello,spring mvc资源绑定视图解析器!");
return "hello";
}
}
multipleresolver-servlet.xml 配置如下所示 -
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="
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">
<context:component-scan base-package="com.h3" />
<bean class="org.springframework.web.servlet.view.resourcebundleviewresolver">
<property name="basename" value="views" />
<property name="order" value="0" />
</bean>
<bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
<property name="prefix" value="/web-inf/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
</beans>
views.properties 配置如下所示 -
hello.(class)=org.springframework.web.servlet.view.jstlview
hello.url=/web-inf/jsp/hello.jsp
hello.jsp 的代码如下所示 -
<%@ page contenttype="text/html; charset=utf-8" %>
<html>
<head>
<title>hello world</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
完成创建源和配置文件后,发布应用程序到tomcat服务器。
现在启动tomcat服务器,当访问url => http://localhost:8080/multipleresolver/hello , 如果spring web应用程序没有问题,应该看到以下结果: