如何进行springboot配置templates直接访问的实现

这篇文章给大家介绍如何进行springboot配置templates直接访问的实现,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

springboot配置templates直接访问

springboot下的templates目录的资源默认是受保护的,类似于javaweb项目的WEB-INF目录,但是给每个springboot的html页面都配置控制器跳转过于麻烦

配置公有访问方式如下

在配置文件加如下:

spring.resources.static-locations=classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/templates/, classpath:/public/

附上spring 各种配置的官方url:方便后期查阅

springboot的templates用法

@Controller
public class HelloController {
    @RequestMapping("/test")
    public String test(Model model){
        model.addAttribute("msg","<h2>templates测试</h2>");
        model.addAttribute("users", Arrays.asList("lishao","liyuan"));
        return "/test";
    }
}

在controller中添加视图

在html中调用

<body>
<h4>test</h4>
<!--不转义-->
<div th:text="${msg}"></div>
<!--转义h2-->
<div th:utext="${msg}"></div>
<hr>
<h4 th:each="user : ${users}" th:text="${user}"></h4>

</body>

记得要导入templates的依赖

当你导入了templates依赖,

如何进行springboot配置templates直接访问的实现  springboot 第1张

就会直接识别出来文件下的test,简单方便

 <!--templates-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

html中也要导入

<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

一个是转义一个是不转义

以下是运行的结果

如何进行springboot配置templates直接访问的实现  springboot 第2张

如何进行springboot配置templates直接访问的实现  springboot 第3张

关于如何进行springboot配置templates直接访问的实现就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接