SpringBoot,Vue先後端分離開發首秀

需求:讀取數據庫的數據展示到前端頁面
技術棧:後端有主要有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頁面,具體代碼以下javascript

<!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>
目錄結構和運行結果以下
完美收官!!!!!!!
github代碼

我的網站css

相關文章
相關標籤/搜索