SpringBoot-Vue 前后端分离开发首秀
小Hub领读:
很简单的springboot-Vue入门示例,后面会逐渐增加难度,从简单到复杂!
作者:Joker
原文地址 https://juejin.im/post/5ccda966e51d456e51614b4b
需求:读取数据库的数据展现到前端页面 技术栈:后端有主要有 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>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<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 >
<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>
上面前端的代码,主要是通过引入Vue的js文件实现Vue的组件功能,一般在功能复杂的项目中,我们不会这样使用,而是单独新建一个前端的项目,使用NPM来创建运行打包项目。具体的Vue教程,可以去看这个网站:https://www.runoob.com/vue2/vue-tutorial.html。
目录结构和运行结果如下
完美收官!!!!!!!
github 代码:https://github.com/pbw123/spring-boot-demo
个人网站:http://47.101.51.245/
(完)
MarkerHub文章索引:(点击阅读原文直达)
https://github.com/MarkerHub/JavaIndex
【推荐阅读】