您的位置:首页 > 编程语言 > Java开发

Spring boot 2.0+引用静态文件js、css、html

2019-07-18 15:11 309 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_44037376/article/details/96430843

1、先上目录


上图红框圈出来的文件为接下来会用到的文件

2、maven包的pom.xml

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3、配置文件application.properties

spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.mode=HTML5

4、spring boot 启动类Application.java

@SpringBootApplication
@MapperScan("com.chat.mapper")
public class Application extends WebMvcConfigurationSupport {

public static void main(String[] args){

SpringApplication.run(Application.class,args);

}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
super.addResourceHandlers(registry);
}
}

5.Controller

@Controller
public class HtmlController {

@RequestMapping(value = "/html/empower")
public ModelAndView empower(ModelAndView modelAndView){
modelAndView.setViewName("empower");
modelAndView.addObject("name","name");
modelAndView.addObject("value","value");
return modelAndView;
}
}

这里的@Controller 千万别用@RestController, (谁用谁知道)

6、html页面,引用js,css

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link th:href="@{~/static/css/empower.css}" rel="stylesheet">
<script type="text/javascript" th:src="@{~/static/js/empower.js}"></script>
</head>
<body>

<div class="a">

<h1 th:text="${name}"></h1>
<h1 th:text="${value}"></h1>
</div>

</body>
</html>

注意:页面引用css,js 的区别,路径是采用的绝对路径。

7.css 就不贴了,我们看下效果


end!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: