Springboot不使用模板引擎加载html

时间:2024-05-19 15:42:48

原文地址:点我

一、使用maven构建springboot项目

目录结构:

Springboot不使用模板引擎加载html

1.pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.itxsl</groupId>
    <artifactId>springboot-example08</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

 

2.启动类及视图映射:

package cn.itxsl;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

/**
 * @Author itxsl
 * @Description
 * @Date 2018/10/8 11:03
 */
@Controller
@SpringBootApplication
public class Start {

    public static void main(String[] args) {
        SpringApplication.run(Start.class, args);
    }

    @GetMapping({"/index","/"})
    public String index(){
        return "index";
    }

}

 

3.html和js:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<h1>哈哈</h1>
<button id="dw" >点我</button>
</body>
<script src="/jquery.min.js"></script>
<script>
    $("#dw").click(function () {
        alert("你好,张磊!!!")

    })
</script>

</html>

4.application.yml配置文件:

用法一、文件放在resources下

server:
  port: 8080
spring:
  mvc:
    view:
      suffix: .html
    static-path-pattern: /**
  resources:
    static-locations: classpath:/templates/,classpath:/static/

用法二、文件放在任意路径下

server:
  port: 8080
spring:
  mvc:
    view:
      suffix: .html
    static-path-pattern: /**
  resources:
    static-locations: file:D:\gzzg\springboot-example08\templates\,file:D:\gzzg\springboot-example08\static

最后结果图:

Springboot不使用模板引擎加载html