The first day of learning springboot~

Posted by flhtc on Mon, 04 Nov 2019 23:17:54 +0100

1. springboot is to improve and optimize the disadvantages of spring. Its convention is larger than configuration. It can be used out of the box without code generation or xml file configuration. The property value can be modified to meet the requirements

2. Getting started with springboot

Create a spring boot project in idea

(1) by default, there is a DemoApplication class, which is the springboot startup class

This class must be flush with the parent of other code, that is, it is the same level as the parent of all classes

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

}

(2) in the resource directory, there is application.properties, which is the configuration file of springboot

(3) there is DemoApplicationTests test class under the test package, which is a unit test of springboot

(4) pom.xml file

 

3. springboot web application

Create entity bean Car class

Import dependency, install lombok plug-in

<dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.6</version>
</dependency>

Car.java

@Data               //set+get
@NoArgsConstructor  //Non parametric structure
@AllArgsConstructor //Parametric construction with all parameters
public class Car {
    private Integer id;
    private String name;
    private Float price;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")//Time format conversion
    private Date createDate;
}

CarController.java

@RequestParam: get query parameters

@PathVariable: get path parameter

@RestController  //@RestController: Amount to@Controller+@ResponseBody
@RequestMapping("/car")
public class CarController {
  @RequestMapping(
"/findCar")
  public Car findCar(){
    Car car
= new Car(1, "BMW", 123.0F, new Date()); return car;
  }

  @RequestMapping(
"/getCar/{id}")
  public Car findOne(@PathVariable("id")Integer id, @RequestParam("name")String name,@RequestParam("price")Float price){
    Car car
= new Car();
    car.setId(id); car.setName(name);
    car.setPrice(price);
    return car;
  }
}

 

 

Get spring boot static resources

(1) default static resource mapping

By default, springboot maps / * * all accesses to classpath:/static, classpath:/public, classpath:/WETA-INF/resources

That is, create a new public, static, META-INF/resources in the resources directory, and put them into the static resource file. You can access the resource name directly

By default, Spring Boot will find whether there are corresponding resources in public, META-INF/resources and static one by one. If so, it will return directly

(2) user defined static resource access

The first way: you can create a configuration class

@Configuration   //Take a java class as a configuration class
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {  
    //Map all d:\Desktop \ \ accesses to the path of / pathFile / *
    registry.addResourceHandler("/pathFile/**").addResourceLocations("file:d:\\Desktop\\");
  }
}

Enter: localhost:8080/pathFile/1.jpg in the browser to access the image resource

The second way: modify the configuration file application.properties

When writing the code in the configuration file, we must be careful. My classmate wrote an extra space after spring. MVC. Static path pattern = / *, which led to the access error all the time. Therefore, we must carefully check the configuration

#Custom properties, specifying a path
web.upload-path=d:/Desktop/
#Indicates that all accesses go through the static resource path
spring.mvc.static-path-pattern=/**
#Configure the static resource path. The configuration here will override the default access configuration (public, static, resources path access will fail). Therefore, you need to configure
spring.resources.static-locations=classpath:/static/,classpath:/public/,classpath:/META-INF/resources/,file:${web.upload-path}

Enter: localhost:8080/1.jpg in the browser to access

 

WebJars

Package all the static files of the front end into a jar package, and then introduce this jar package to manage the static resources of the front end

At that time, when packaging, because the whole project was directly packaged as a jar package, it was accessed after being introduced into the project and reported 404 all the time. Can't the project import its own jar package? I don't know what the reason is. Anyway, I've been reporting mistakes all the time, so I'm very upset.

Solution: 1. Make sure to create a new project and introduce the dependency of jar package into the new project,

2. Make sure that there is no static resource file in the jar package in the new project

 

 

3.springboot property configuration

Modify the suffix name of the application.properties configuration file automatically generated by springboot to yml (I don't know why yml is used, but it's better to change it to yml anyway? ), you can modify the default configuration

When springboot develops web applications, the default tomcat startup port number is 8080. You can modify the access port number in the configuration file:

server:
  port: 8888

Note: you must leave a space before the port, and a space after the port (do not leave it, the port word will remain the same color in idea, and cannot be used)

You can also modify the access path:

server:
  port: 8888
  servlet:
    context-path: /java0708

At this time, you can visit: http://localhost:8888/java0708

There are order and restriction in writing. Write according to the restriction, or it will not work

You can also customize properties and reads

Define constants in application.yml:

offcn_ip: 12.134

Write the Controller class and read the custom properties:

@RestController
public class TestConController {
    @Value("${offcn_ip}")
    private String offcn_ip;

    @GetMapping("/getValue")
    public String getIP(){
        return "ip:"+offcn_ip;
    }
}

 

Entity class property assignment

Configure in application.yml:

userbody:
  name: offcn
  password: 123456
  birthday: 1992.10.28
  mobile: 13802789765
  address: beijing

You can't write Chinese in the configuration file, and there will be garbled code. You need to use the transcoding tool to output Chinese (it's very troublesome, so I write English)

Create entity class

@ConfigurationProperties(prefix = "userbody")
public class UserBody {
    private String name;
    private String password;
    private String birthday;
    private String mobile;
    private String address;
}

Write Controller call property bean

@RestController
@EnableConfigurationProperties({UserBody.class})
public class HelloControllerBean {
    @Autowired
    UserBody userbody;

    @GetMapping("/getUser")
    public String getUser(){
        return userbody.toString();
    }
}

 

Spring boot builds RESTful

RESTful is a software architecture style!

The RESTful architecture style stipulates that the meta operation of data, namely CRUD(create, read, update and delete, namely data addition, deletion, query and modification), corresponds to HTTP method respectively: GET is used to obtain resources,

POST is used to create new resources (or update resources),

PUT is used to update resources,

DELETE is used to DELETE resources,

In this way, the interface of data operation is unified. Only through HTTP method, all the work of adding, deleting, checking and modifying data can be completed

HTTP protocol request method

SpringBoot annotation

URL

Function description

POST

@PostMapping

/users

Create a user

GET

@GetMapping

/users

Query user list

GET

@GetMapping

/users/id

Query a user by id

PUT

@PutMapping

/users/id

Update a user by id

DELETE

@DeleteMapping

/users/id

Delete a user by id

@RestController
@RequestMapping("/user-test")
public class UserController {
    private List<User> userList = Collections.synchronizedList(new ArrayList<User>());

    //Get all user information
    @GetMapping("/")
    public List<User> getUserList(){
        return userList;
    }

    //Add user information
    @PostMapping("/")
    public String createUser(User user){
        userList.add(user);
        return "success";
    }

    //Get the specified user id information
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Long id){
        for (User user : userList) {
            if (user.getId() == id){
                return user;
            }
        }
        return null;
    }

    //Modify the specified user id information
    @PutMapping("/{id}")
    public String updateUser(@PathVariable("id")Long id,User user){
        for (User user1 : userList) {
            if (user1.getId() == id){
                user1.setName(user.getName());
                user1.setAge(user.getAge());
            }
        }
        return "success";
    }

    //Delete specified user id information
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable("id")Long id){
        userList.remove(getUser(id));
        return "success";
    }
}

 

Today, I have a little more knowledge, a little bit miscellaneous, and many codes have not been posted. I am still lazy, so I summed up some important knowledge points, which should not be comprehensive, and I will continue to improve later

As a beginner, I'm not very good at using this thing. Maybe I'm used to spring, but most of my knowledge is relatively basic. It's easier to learn today, and I'll continue to work hard tomorrow

Topics: Java SpringBoot Spring xml