从头搭建Spring Boot(一) eclipse

本章主要目标完成Spring Boot基础项目的构建,并且实现一个简单的Http请求处理,通过这个例子对Spring Boot有一个初步的了解,并体验其结构简单、开发快速的特性。

通过SPRING INITIALIZR工具产生基础项目

步骤1 : 使用浏览器打开: http://start.spring.io

步骤2 : 填写项目相关信息,选取依赖,然后生成项目。注:本人选择的是Maven Project,JAVA(1.8),Spring Boot(2.0.0)

步骤3 : 解压项目,导入Eclipse,大功告成!!

然后需要引入Spring Boot web包,在pom.xml新增

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

在主函数包下新创建一个包,包名随意,创建一个类HelloWorld,如下:

@RestController
public class HelloWorld {

@RequestMapping("/hello")
public String index() {
return "Hello World";
}

}

启动主程序,打开浏览器访问http://localhost:8080/hello,可以看到页面输出Hello World

在spring boot中引入html模板代码index.html,文件位于/resources/static目录下,包括CSS image等如下图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
-----hello jasonLin!------
</body>
</html>

资源访问路径配置 application.properties:

#MVC
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.html

上面说到/resources/static静态资源的默认请求路径为/ 。假如我的静态资源位于/resources/static/dist目录下,但是我不想将请求改为/dist(这里要注意一下html中引用其它资源的相对路径如果是./xxx 在本地更改真个文件加的路径引用的资源文件是能够正常定位,但是在web容器中./xxx需改为/dist/xxx ,这里涉及到web根路径和本地文件路径的问题)可以在application.properties加如下配置: 
spring.resources.static-locations=classpath:/static/dist/ 
这样当我们访问/ 时实际定位的资源文件位置是/resources/static/dist 这样就避免了当更改资源文件的位置时需要更改html中的全部引用。

原文地址:https://www.cnblogs.com/xiaohan666/p/8625211.html