需求:讀取資料庫的資料展現到前端頁面 技術棧:後端有主要有SpringBoot,lombok,SpringData JPA,Swagger,跨域,前端有Vue和axios 不瞭解這些技術的可以去入門一下 lombok入門 swagger入門 SpringData JPA入門 配置:mysql 8.0.11,IntelliJ IDEA 2017.1.2,HBuilderX 1.9.3
首先建立一個Spring Boot專案,目錄結構如下:
在pom.xml中加入如下依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
複製程式碼
application.properties配置
#埠
server.port=8888
#連線資料庫的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.password=Panbing936@
spring.datasource.username=root
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
#SpringData JPA的配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL5Dialect
複製程式碼
實體類User.java
@Entity
@Data
public class User{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(length = 55)
private String name;
private String avatarURL;
}
複製程式碼
介面UserMapper.java繼承JpaRepository
public interface UserMapper extends JpaRepository<User,Integer> {
}
複製程式碼
Controller.java
@RestController
@RequestMapping(value = "/api",produces = APPLICATION_JSON_VALUE)
@Api(description = "使用者管理")
public class UserController {
@Autowired
private UserMapper userMapper;
@ApiOperation(value = "使用者列表",notes = "查尋所有已註冊過的使用者資訊")
@RequestMapping(value = "getAll",method = RequestMethod.GET)
public List<User> getAll()
{
return userMapper.findAll();
}
}
複製程式碼
SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.niit.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2實現前後端分離開發")
.description("此專案只是練習如何實現前後端分離開發的小Demo")
.termsOfServiceUrl("https://www.jianshu.com/u/2f60beddf923")
.contact("WEN")
.version("1.0")
.build();
}
}
複製程式碼
WebConfig.java是實現跨域的配置,務必記得
@Configuration
class WebMvcConfigurer extends WebMvcConfigurerAdapter {
//跨域配置
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
//重寫父類提供的跨域請求處理的介面
public void addCorsMappings(CorsRegistry registry) {
//新增對映路徑
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否傳送Cookie資訊
.allowCredentials(true)
//放行哪些原始域(請求方式)
.allowedMethods("GET", "POST", "PUT", "DELETE")
//放行哪些原始域(頭部資訊)
.allowedHeaders("*")
//暴露哪些頭部資訊(因為跨域訪問預設不能獲取全部頭部資訊)
.exposedHeaders("Header1", "Header2");
}
};
}
}
複製程式碼
點選localhost:8888/swagger-ui.html檢視生成的介面文件,測試一下
返回資料沒有問題,接著可以根據文件開發前端程式碼了
用HBuilderX新建一個test.html頁面,具體程式碼如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Vue.js-訪問API介面資料-藍墨雲班課練習</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- 通過CDN引入Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 通過CDN引入axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style type="text/css">
.container{
display: flex;
flex-direction: column;
}
.card{
display: flex;
margin-bottom: 10px;
}
.cover{
width: 100px;
height: 100px;
}
.cover img{
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="app">
<div class="top">
<p>{{users.length}}個人線上</p>
</div>
<hr>
<div class="container">
<div class="card" v-for="user in users">
<div class="cover">
<img :src="'img/'+user.avatarURL">
</div>
<div class="">
<p>{{user.id}}</p>
</div>
<div class="">
<p>{{user.name}}</p>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
users: []
},
created: function() {
var _this = this;
axios.get('http://localhost:8888/api/getAll')
.then(function(response) {
_this.users = response.data;
})
}
})
</script>
</body>
</html>
複製程式碼
目錄結構和執行結果如下
完美收官!!!!!!!