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

it2022-05-05  124

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!


最新回复(0)