Springboot2.0 Quick Start (Chapter 1)

1. Introduction to SpringBoot

1.1, review what is Spring

Spring is an open source framework, a lightweight Java development framework that emerged in 2003, author: Rod Johnson.
Spring was created to solve the complexity of enterprise-level application development and simplify development.

1.2, How Spring simplifies Java development

为了降低Java开发的复杂性,Spring采用了以下4种关键策略:

1. Lightweight and minimally invasive programming based on POJO, everything is a bean;
2. Loose coupling is achieved through IOC, dependency injection (DI) and interface-oriented;
3. Declarative programming based on aspects (AOP) and conventions ;
4. Reduce style codes through facets and templates, RedisTemplate, xxxTemplate;

1.3, what is SpringBoot

Spring Boot is a Spring-based framework provided by the Pivotal team, which uses a specific way to configure, so that developers no longer need to define boilerplate configuration. Spring Boot integrates most of the currently popular development frameworks, just like Maven integrates all JAR packages, Spring Boot integrates almost all frameworks, enabling developers to quickly build Spring projects.

Key advantages of Spring Boot:
为所有Spring开发者更快的入门
开箱即用,提供各种默认配置来简化项目配置
内嵌式容器简化Web项目
没有冗余代码生成和XML配置的要求

Two, Hello, World

2.1, preparation work

We will learn how to quickly create a Spring Boot application and implement a simple Http request processing. Have a preliminary understanding of Spring Boot through this example, and experience its simple structure and rapid development.

My environment is prepared:
依赖版本jdk1.8以上
Maven-3.2以上
SpringBoot 2.x

development tools:
IDEA

2.2, create a basic project description

1. First create a maven project
2. Add Springboot's parent project and corresponding dependencies in the maven pom file

insert image description here
insert image description here

Such a maven project is created!
Then add Springboot's parent project and corresponding dependencies to the pom file

    <!--  继承默认值为Spring Boot  -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>

    <dependencies>
        <!--    导入Springweb的依赖    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

insert image description here

2.3, create the first Hello, SpringBoot program

1. Put the startup class in the top-level directory
2. Commonly used annotations
The startup class annotation
@SpringBootApplication is a composite annotation. @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
@Configuration: @Configuration is marked on the class, which is equivalent to using the class as a spring xml configuration file (beans), and its function is to configure the spring container (application context)
@EnableAutoConfiguration: Turn on automatic configuration. Some automatic configuration classes of spring.facotries under MATA-INF
@ComponentScan: scanning annotations. If you do not configure basepackage, all classes in the same class and subdirectories of the @ComponentScan annotation class will be scanned by default. So put the startup class in the top-level directory.
The control layer annotations
@RestController and @RequestMapping are springMVC annotations, not springboot-specific
@RestController = @Controller + @ResponseBody

insert image description here
HelloController类

package com.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController // 控制类
public class HelloController {
    
    

    @RequestMapping("/")
    public String sayHello(){
    
    
        return "hello,SpringBoot!!";
    }
}

在外面创建一个springboot的启动类
insert image description here
DemoApplication启动类

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

// @SpringBootApplication是一个复合型注解,通常情况下,我们会把启动类放到项目的顶级目录
// 注意:SpringBootApplication中的 @ComponentScan 会默认扫描本类所在包以下的子包
@SpringBootApplication 
public class DemoApplication {
    
    

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

The operation is successful, as follows:

insert image description here

Three, HTTP interface get request

3.1, restful protocol, get parameters @PathVariable from the path

    /**
     * 功能描述: restful 协议。从路径中获取参数
     * 1.接口中的参数定义,建议使用下划线隔开,不再使用驼峰
     * 2.path="/{cityid}/{userid}" 标识路径中那些是参数
     * 3.method=RequestMethod.GET 只处理get请求
     * 4.@PathVariable("cityid") 从路径中取出参数值
     * @return
     * */

    @RequestMapping("/{cityid}/{userid}")
    public Object test1(
            @PathVariable("cityid") String cityId,
            @PathVariable("userid") String userId){
    
    
        return cityId + "--" + userId;
    }

insert image description here

3.2, parameter default setting @RequestParam

    /**
     *
     * 参数的默认值设置
     * 添加@RequestParam 默认此参数是必填项
     * @return
     * **/
    @RequestMapping("/test2")
    public Object test2(@RequestParam(required = false,defaultValue = "1") Integer pageNo){
    
    
        return pageNo;
    }

insert image description here

The above shows the default value. If you assign a value to it, the assigned value will replace the default value, as follows:

insert image description here

3.3, pass the bean object by value (data is obtained from the body) @RequestBody

    /**
     *
     * 测试@RequestBody。要从请求体中获取数据
     * 有如下结果
     * 1.数据要在请求体中。
     * 2.数据的格式为JSON。content-type 的值是application/json
     * 3.只有post请求才允许在body中设置数据
     * **/
    @RequestMapping("/test3")
    public Object test3(@RequestBody Person person){
    
    
        return person.getUserId() + "-----" + person.getAge();
    }

insert image description here

3.4, get http request header information, for example get token @RequestHeader

    /**
     * 从请求头获取数据
     * 一般请求头中获取一些认证信息,例如token
     * **/
    @RequestMapping("/test4")
    public Object test4(@RequestHeader String access_token){
    
    
        return access_token;
    }

insert image description here

Fourth, the introduction of commonly used json framework and the processing of jackson return results

简介:介绍常用json框架和注解的使用,自定义返回json结构和格式

  1. Commonly used frameworks such as Ali fastjson, Google gosn, etc.
    JavaBean serialization into json Performance: Jackson > FastJson > Gson > Json-lib The same structure
    Jackson, FastJson, and Gson libraries have their own advantages and specialties.
    Space for time, time for space

2. Jackson handles related automatic
specified fields not to return: @JsonIgnore
specifies the date format: @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss", locale="zh", timezone="GMT+8")
empty The string is not returned: @JsonInclude(JsonInclude.Include.NON_NULL)
specifies the alias: @JsonProperty Note: After using the alias, the Key in the request should also use the alias

4.1, springboot unified return package

创建一个util包

insert image description here
然后创建一个ResultUtil工具类

package com.demo.util;

import lombok.Data;

import java.io.Serializable;

@Data
public class ResultUtil<T> implements Serializable {
    
    

    public static final Integer SUCCESS_CODE = 2000;
    public static final Integer FAIL_CODE = 4000;
    public static final String SUCCESS_MESSAGE = "success";
    public static final String FAIL_MESSAGE = "fail";
    /**
     * 返回状态码
     */
    private Integer code;
    /**
     * 返回信息
     */
    private String message;

    /**
     * 返回数据
     */
    private T data;

    private ResultUtil() {
    
    
    }

    public static <T> ResultUtil<T> success() {
    
    
        ResultUtil<T> resultUtil = new ResultUtil<>();
        resultUtil.setCode(SUCCESS_CODE);
        resultUtil.setMessage(SUCCESS_MESSAGE);
        return resultUtil;
    }

    public static <T> ResultUtil<T> success(T data) {
    
    
        ResultUtil<T> resultUtil = success();
        resultUtil.setData(data);
        return resultUtil;
    }

    public static <T> ResultUtil<T> success(String message, T data) {
    
    
        ResultUtil<T> resultUtil = success();
        resultUtil.setMessage(message);
        resultUtil.setData(data);
        return resultUtil;
    }

    public static <T> ResultUtil<T> success(Integer code, String message, T data) {
    
    
        ResultUtil<T> resultUtil = new ResultUtil<>();
        resultUtil.setCode(code);
        resultUtil.setMessage(message);
        resultUtil.setData(data);
        return resultUtil;
    }

    public static <T> ResultUtil<T> fail() {
    
    
        ResultUtil<T> resultUtil = new ResultUtil<>();
        resultUtil.setCode(FAIL_CODE);
        resultUtil.setMessage(FAIL_MESSAGE);
        return resultUtil;
    }

    public static <T> ResultUtil<T> fail(T data) {
    
    
        ResultUtil<T> resultUtil = fail();
        resultUtil.setData(data);
        return resultUtil;
    }

    public static <T> ResultUtil<T> fail(String message, T data) {
    
    
        ResultUtil<T> resultUtil = fail();
        resultUtil.setMessage(message);
        resultUtil.setData(data);
        return resultUtil;
    }

    public static <T> ResultUtil<T> fail(Integer code, String message) {
    
    
        ResultUtil<T> resultUtil = fail();
        resultUtil.setCode(code);
        resultUtil.setMessage(message);
        return resultUtil;
    }

    public static <T> ResultUtil<T> fail(Integer code, String message, T data) {
    
    
        ResultUtil<T> resultUtil = new ResultUtil<>();
        resultUtil.setCode(code);
        resultUtil.setMessage(message);
        resultUtil.setData(data);
        return resultUtil;
    }

}

This format mainly includes 3 parts:
1.code: status code, the status code of various returned results is uniformly defined by the backend to judge success or failure
2.message: description information, prompt information
3.data: returned data, such as a list data

Person.java实体类修改一下不在需要get,set方法,但是得加上@Data

package com.demo.bean;

import com.fasterxml.jackson.annotation.*;
import lombok.Data;

import java.io.Serializable;
import java.util.regex.Pattern;

@Data
public class Person implements Serializable {
    
    


    private String userId;

    private int age;

}
    /**
     *
     * 测试@RequestBody。要从请求体中获取数据
     * 有如下结果
     * 1.数据要在请求体中。
     * 2.数据的格式为JSON。content-type 的值是application/json
     * 3.只有post请求才允许在body中设置数据
     * **/
    @RequestMapping("/test3")
    public Object test3(@RequestBody Person person){
    
    
        return ResultUtil.success(person);
    }

The result is as follows:

insert image description here

On the premise of writing like this, add a dependency to the pom

insert image description here

at last

送大家一句话:你大好青春,怕什么,只管向前跑

Guess you like

Origin blog.csdn.net/H20031011/article/details/132554627