SpringBoot基础03:静态资源和首页定制
SpringBoot基础03:静态资源和首页定制
静态资源
- 在SpringBoot中,可以使用一下方式处理静态资源
-
webjars
http://localhost:8080/webjars/ -
public,static,/**,resources
http://localhost:8080
- 优先级:resources>static(默认)>public
首页如何定制
-
导入模板引擎:在pom.xml中导入thymeleaf中添加相关启动器SpringBoot将自动配置相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> -
通过源码分析,默认在classpath:/templates/下寻找.html文件,因此在resources目录下的templates目录中创建相关.html文件就可以通过controller来访问相关页面了
@ConfigurationProperties(prefix = "spring.thymeleaf") public class ThymeleafProperties { private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8; public static final String DEFAULT_PREFIX = "classpath:/templates/"; public static final String DEFAULT_SUFFIX = ".html";
-
通过Controller类来传参,并在html页面中显示出来,前端界面获取后端元素 th:元素名的方式来进行替换
package com.lurenj.controller; import org.springframework.ui.Model; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; //在templates目录下的所有页面,只能通过controller来跳转 //需要模板引擎的支持! thymeleaf @Controller public class IndexController { @RequestMapping("/test") public String test(Model model){ model.addAttribute("msg","springboot"); return "test"; } }<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--所有的html元素都可以被thymeleaf替换接管: th:元素名--> <h1 th:text="${msg}"></h1> </body> </html> -
自定义视图解析器,在主程序同级目录下创建config文件夹,在其中建立自定义类,通过ViewResolver接口实现自定义试图解析器,并加入到容器中
package com.lurenj.config; //全面扩展 springMVC import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.View; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.util.Locale; @Configuration public class MyMvcConfig implements WebMvcConfigurer { //public interface ViewResolver 实现了视图解析器接口的类,我们就可以把它看做视图解析器@Bean public ViewResolver myViewResolver(){ return new MyViewResolver(); } //自定义一个自己的视图解析器MyViewResolver public static class MyViewResolver implements ViewResolver{ @Override public View resolveViewName(String viewName, Locale locale) throws Exception { return null; } }}
-
扩展SpringMvc
package com.lurenj.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; //如果我们要扩展springMVC,官方建议的做法如下! @Configuration public class MyMvcConfig implements WebMvcConfigurer { //视图跳转 @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/lurenj").setViewName("test"); } }

浙公网安备 33010602011771号