在Spring Framework 2.0中,可以通过以下方式配置ResourceBundleViewResolver:
applicationContext.xml
),添加以下配置项:
<beans>
...
<!-- 配置ResourceBundleViewResolver -->
<bean
id="viewResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
...
</beans>
org.springframework.web.SpringServletApplication
)上,初始化一个ResourceBundleViewResolver,例如:
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
...
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
...
@Configuration
public class ApplicationConfiguration {
@Bean
public ResourceBundleViewResolver viewResolver() {
return new ResourceBundleViewResolver();
}
}
.properties
文件定义视图资源。例如,在classpath下的.properties
文件中定义一个视图资源路径:
views.messages = /WEB-INF/views/messages.properties
views.users = /WEB-INF/views/users.properties
views.orders = /WEB-INF/views/orders.properties
views.cart = /WEB-INF/views/cart.properties
注意:在Spring MVC中,视图资源被表示为一个资源,而视图是由资源加载器(如ResourceBundleViewResolver或UrlBasedViewResolver)加载的。要处理资源路径,通常需要将这些路径设置为视图解析器的basename
属性,以便视图被加载。
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
@Controller("userController")
public class UserController {
@GetMapping("/users")
public String listUsers(Model model) {
model.addAttribute("users", listUsers());
return "users";
}
...
}
上面代码中,当用户访问/users
URI时,Spring MVC会自动加载views.users
视图资源,并使用userController
上下文中定义的listUsers
方法返回的用户列表。其他URI将引用其他的视图资源。
领取专属 10元无门槛券
手把手带您无忧上云