springmvc的视图

springmvc的视图

在SpringMVC中的视图实现View接口,视图的作用是渲染数据,将模型Model中的数据展示给用户。

SpringMVC中视图的种类很多,默认有转发视图(internalResourceView)和重定向视图(RedirectView)两种。
但当我们的工程引入jstl的依赖的时候,转发视图会自动转换为JstlView。
当我们使用Thymeleaf技术的时候,在SpringMVC的配置文件中配置了Thymeleaf的视图解析器,由此视图解析器解析之后得到的是ThymeleafView。

thymeleafview

thymeleaf是一个视图解析器,它可以解析springmvc中的model中的数据来发送给用户,当不存在前缀的时候解析的视图就是thymeleafview

package com.jin.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
    @RequestMapping("/testThymeleafview")
    public String test1(){
        return "success";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/testThymeleafview}">测试thymeleafview</a>
</body>
</html>

重新部署tomcat,然后点击超链接

springmvc的视图

这是当没有前缀时候的视图解析

internalResourceView(转发视图)

给返回的值添加一个forward前缀,实现internalResourceview

package com.jin.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
    @RequestMapping("/testForword")
    public String test2(){
        return "forward:/testThymeleafview";
    }
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/testForword}">测试internalResourceview</a>
</body>

springmvc的视图
可以发现跳转的是第一个页面,但是上面的连接依然是testForword而不是testThymeleafview,可知实现了视图的转发

RedirectView

实现的是视图的重定向,前缀为redirect


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
    @RequestMapping("/testRedirect")
    public String test3(){
        return "redirect:/testThymeleafview";
    }
}

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a th:href="@{/testRedirect}">测试redirect</a>
</body>
</html>

点击超链接
springmvc的视图
可以发现连接栏里面的链接不是testRedirect而是testThymeleafview,实现了重定向

上一篇:SpringMVC中Controller层的接口的一些不同写法总结


下一篇:Day530.图灵学院之面试题④ -面经