Java教程

springmvc的视图

本文主要是介绍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,然后点击超链接

在这里插入图片描述

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

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>

在这里插入图片描述
可以发现跳转的是第一个页面,但是上面的连接依然是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>

点击超链接
在这里插入图片描述
可以发现连接栏里面的链接不是testRedirect而是testThymeleafview,实现了重定向

这篇关于springmvc的视图的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!