Spring MVC的视图解析

ThymeleafView

当使用的视图解析技术为Thymeleaf,并且在SpringMVC的配置中配置了ThymeleafViewResolver视图解析器时;
如果控制器(Controller)中所设置的视图名称没有任何前缀,此时视图名称会被配置好的视图解析器解析,视图名称拼接视图前缀和试图后缀所得到的最终路径,会通过转发的方式实现跳转;

    @RequestMapping("/")
    public String index(){
        //只有视图名称,转发跳转到index.html
        return "index";
    }
<!--Thymeleaf视图解析器-->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
   <property name="order" value="1"/>
   <property name="characterEncoding" value="UTF-8"/>
   <property name="templateEngine">
       <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
           <property name="templateResolver">
               <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                   <!--视图前缀-->
                   <property name="prefix" value="/WEB-INF/templates/"/>
                   <!--视图后缀-->
                   <property name="suffix" value=".html"/>
                   <property name="templateMode" value="HTML5"/>
                   <property name="characterEncoding" value="UTF-8"/>
               </bean>
           </property>
       </bean>
   </property>
</bean>

InternalResourceView转发视图

Spring MVC中默认的转发视图就是InternalResourceView;
当控制器中的视图名称是以forward:为前缀时,会创建InternalResourceView视图,此时视图名称不会被配置文件中的ThymeleafViewResolver视图解析器解析,而是会将forward:去掉,剩余部分作为最终路径通过转发的方式实现跳转;

    @RequestMapping("/hello")
    public String index(){
        return "index";
    }

    @RequestMapping("/forward")
    public String sayHello(){
    	//转发到/hello方法,然后再通过thymeleaf解析了一次
    	//地址栏的地址不会变,还是/forward
        return "forward:/hello";
    }

RedirectView重定向视图

当控制器的方法设置的视图名称以redirect:为前缀时,创建的是RedirectView视图,此时视图名称不会被配置文件中的ThymeleafViewResolver视图解析器解析,而是会将redirect:去掉,剩余部分通过重定向的方式实现跳转;

    @RequestMapping("/hello")
    public String index(){
        return "index";
    }

    @RequestMapping("/redirect")
    public String sayHello(){
    	//转发到/hello方法,然后再通过thymeleaf解析了一次
    	//地址栏的地址会变成重定向的地址,/hello
        return "redirect:/hello";
    }

View-Controller视图控制器

在当前控制器方法中没有其他请求,只需要设置一个视图名称的话,可以用ViewController进行设置;
在springMVC配置文件中配置

  <mvc:view-controller path="/" view-name="index"/>

如果还有其他控制器方法需要实现请求映射,则需要增加另外一个配置;

    <!--开启SpringMVC注解支持-->
    <mvc:annotation-driven/>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值