springboot的使用html页面及css、js路径的配置

1. springboot集成 html页面

pom.xml文件中增加thymeleaf的starter引用

 
    org.springframework.boot
    spring-boot-starter-thymeleaf
 

springboot项目,在application.yml配置文件中增加如下配置

spring:
  thymeleaf:
    prefix: classpath:/templates
    suffix: .html
    cache: false
  • prefix
    prefix意为前缀
  • suffix
    suffix意为后缀

如我的页面为hello-world.html,它所在的目录结构就应该为
resource–> templates --> hello-world.html
在controller中,return的值则为 /hello-world ,系统会自动给加上.html的后缀

然后增加如下controller中就可以访问到hello-world.html页面了

@Controller
@RequestMapping("/")
public class HelloWorldController {

    @RequestMapping("hello-world")
    public String index() {
        return "/hello-world";
    }
   }

2.页面中引用本地js、css文件的路径配置

我的页面中本来都是直接使用的element-ui和vue直接提供的在线js,但是因为页面嵌套会有跨域的问题,所以页面中的js、css都要改为使用本地文件。在网上试了很多的方法,最后使用排除法缩减到最后的方法如下:

  • resource目录下,创建static目录,在static目录下分别创建js目录和css目录来存放js文件和css文件。

    springboot的使用html页面及css、js路径的配置_第1张图片
  • 在springboot入口的Application文件中增加WebMvc配置,首先继承WebMvcConfigurationSupport类,然后重写addResourceHandlers方法,在里面增加对/css路径和/js路径的映射。

    	public class ApplicationBootStrap extends WebMvcConfigurationSupport {
    	
    		public static void main(String[] args) {
    			SpringApplication.run(ApplicationBootStrap.class, args);
    		}
    	
    	    @Override
    	    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    	        registry.addResourceHandler("/css/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/css/");
    	        registry.addResourceHandler("/js/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/js/");
    	        super.addResourceHandlers(registry);
    	    }
    	}
    
  • 页面引用配置

    • 1.html标签 要增加 xmlns:th="http://www.thymeleaf.org" 引用
    • 2.
      标签中增加 配置
    • 3.css引入增加 th:href配置路径,js引入增加th:src路径配置。这里要注意link要有 rel="stylesheet"script要有type="text/javascript"的格式说明,这是规范。

    然后就大功造成了。文件内配置如以下代码。

    
    
    
        
        
        
        
    
    
    

你可能感兴趣的:(springboot,js,css)