Spring MVC视图解析器:Spring MVC ResourceBundleViewResolver示例

在Spring MVC中,使用ResourceBundleViewResolver基于“.properties”文件中的视图bean来解析“视图名称”。

默认地,ResourceBundleViewResolver将从位于项目class路径根目录下的文件views.properties中加载视图bean,不过,这个位置可以通过“basename”属性覆盖:

<beans ...>
         <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
              <property name="basename" value=”spring-views” </property>
         </bean>
</beans>

  

在上面这个例子中,它从位于项目class路径根目录下的“spring-views.properties”中加载视图bean。

请看下面的ResourceBundleViewResolver示例。

1.  Controller控制器

一个控制器类,返回一个名为“WelcomePage”的视图。

@Controller
@RequestMapping(value = "demo2")
public class WelcomeController {

    @RequestMapping(value = "/welcome")
    public ModelAndView welcome() {
        User user=new User("rollen",12,"beijing");
        return new ModelAndView("welcome","user",user);
    }
}

  

2.  ResourceBundleViewResolver视图解析器

在Spring的bean配置文件中,注册ResourceBundleViewResolver视图解析器,将默认的视图bean位置改为“spring-views.properties”。

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 扫描web包,应用Spring的注解 -->
    <context:component-scan base-package="com.xxx.training"/>


    <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
        <property name="basename">
            <value>spring-views</value>
        </property>
    </bean>

    <mvc:annotation-driven/>
</beans>

  

3.  视图bean

将每个视图bean按普通的资源绑定样式(键-值对)进行声明。其中:

(1)“welcome”是要匹配的视图名称

(2)“.(class)”是视图的类型

(3)“.url”属性是视图的url位置

文件:spring-views.properties

注意:要将这个“spring-views.properties”文件放到项目的class路径下。

welcome.(class)=org.springframework.web.servlet.view.JstlView
welcome.url=/WEB-INF/pages/welcome.jsp

执行过程:

当控制器返回一个名为“welcome”的视图时,ResourceBundleViewResolver将在“spring-views.properties”文件中查找以“welcome”起始的键,并返回相对应的视图URL“/WEB-INF/pages/welcome.jsp”给DispatcherServlet。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值