學習springboot第一天~

1. springboot是對spring的缺點進行改善和優化,它的約定大於配置,開箱即用,沒有代碼生成,也不須要xml文件配置,能夠修改屬性值來知足需求前端

2. springboot的入門程序java

在idea中建立springboot的項目web

(1) 默認有個DemoApplication類,是springboot的啓動類spring

這個類必需要和其餘代碼的父級齊平,即它與全部類的父級是同一等級瀏覽器

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

}

(2) 在resource目錄下有application.properties,是springboot的配置文件tomcat

(3) test包下有DemoApplicationTests測試類,是springboot的單元測試springboot

(4) pom.xml文件架構

 

3. springboot web應用mvc

建立實體bean Car類app

導入依賴,安裝lombok插件

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

Car.java

@Data               //set+get
@NoArgsConstructor  //無參構造
@AllArgsConstructor //包含全部參數的有參構造
public class Car {
    private Integer id;
    private String name;
    private Float price;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")//時間格式轉化
    private Date createDate;
}

CarController.java

@RequestParam:獲取查詢參數

@PathVariable:獲取路徑參數

@RestController  //@RestController:至關於@Controller+@ResponseBody
@RequestMapping("/car")
public class CarController {
  @RequestMapping(
"/findCar")
  public Car findCar(){
    Car car
= new Car(1, "寶馬", 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;
  }
}

 

 

獲取springboot靜態資源

(1) 默認靜態資源映射

springboot默認將/**全部訪問映射到classpath:/static,classpath:/public,classpath:/WETA-INF/resources

即在resources目錄下新建public,static,META-INF/resources,分別放入靜態資源文件,能夠直接經過訪問資源名稱,便可訪問

Spring Boot 默認會挨個從 public、META-INF/resources、static 裏面找是否存在相應的資源,若是有則直接返回

(2) 自定義靜態資源訪問

第一種方式:能夠建立一個配置類

@Configuration   //將一個java類做爲一個配置類
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {  
    //將全部d:\\Desktop\\訪問都映射到/pathFile/**路徑下
    registry.addResourceHandler("/pathFile/**").addResourceLocations("file:d:\\Desktop\\");
  }
}

在瀏覽器輸入:localhost:8080/pathFile/1.jpg便可訪問該圖片資源

第二種方式:修改配置文件application.properties

編寫配置文件中的代碼時,必定要細心,我同窗就是由於在spring.mvc.static-path-pattern=/**後多寫了一個空格,致使一直訪問出錯,因此在配置時,必定要仔細檢查

# 自定義的屬性,指定一個路徑
web.upload-path=d:/Desktop/
#表示全部的訪問都通過靜態資源路徑
spring.mvc.static-path-pattern=/**
# 配置靜態資源路徑,這裏的配置會覆蓋默認訪問配置(public、static、resources路徑訪問將會失效),因此須要配置
spring.resources.static-locations=classpath:/static/,classpath:/public/,classpath:/META-INF/resources/,file:${web.upload-path}

在瀏覽器輸入:localhost:8080/1.jpg便可訪問

 

WebJars

將全部前端的靜態文件打包成一個jar包,而後引入此jar包,能夠很好的對前端靜態資源進行管理

當時在打包時,由於直接把整個項目打成jar包,在本項目中引入後訪問,一直報404。項目不能引入本身的jar包?我也不清楚什麼緣由,反正就是一直報錯,就很煩~。

解決:1.必定要新建一個項目,在新項目中引入jar包的依賴,

   2. 要保證新項目中沒有該jar包中的靜態資源文件

 

 

3.springboot屬性配置

修改springboot自動生成的application.properties配置文件的後綴名爲yml(yml幹嗎的我也不清楚,反正就是要修改爲yml,可能更好用?),能夠修改默認配置

springboot開發web應用的時候,默認tomcat啓動端口號爲8080,能夠在配置文件中修改訪問的端口號:

server:
  port: 8888

注意:port前必定要留有空格,port:後也要留有空格(不留,在idea中port單詞會不變色,不能使用)

也能夠修改訪問路徑:

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

此時能夠訪問:http://localhost:8888/java0708

書寫是有順序的,也有約束,要根據約束寫,否則不起做用

也能夠自定義屬性和讀取

在application.yml中定義常量:

offcn_ip: 12.134

編寫Controller類,讀取自定義的屬性:

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

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

 

實體類屬性賦值

在application.yml中配置:

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

不能再配置文件中寫中文,會出現亂碼,須要經過轉碼工具,才能輸出中文(很麻煩,因此我寫的是英文)

建立實體類

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

編寫Controller調用屬性bean

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

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

 

springboot構建RESTful

RESTful是一種軟件架構風格!

RESTful架構風格規定,數據的元操做,即CRUD(create, read, update和delete,即數據的增刪查改)操做,分別對應於HTTP方法:GET用來獲取資源,

POST用來新建資源(也能夠用於更新資源),

PUT用來更新資源,

DELETE用來刪除資源,

這樣就統一了數據操做的接口,僅經過HTTP方法,就能夠完成對數據的全部增刪查改工做

HTTP協議請求方法

SpringBoot註解

URL

功能說明

POST

@PostMapping

/users

建立一個用戶

GET

@GetMapping

/users

查詢用戶列表

GET

@GetMapping

/users/id

根據id查詢一個用戶

PUT

@PutMapping

/users/id

根據id更新一個用戶

DELETE

@DeleteMapping

/users/id

根據id刪除一個用戶

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

    //獲取所有用戶信息
    @GetMapping("/")
    public List<User> getUserList(){
        return userList;
    }

    //添加用戶信息
    @PostMapping("/")
    public String createUser(User user){
        userList.add(user);
        return "success";
    }

    //獲取指定用戶id信息
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Long id){
        for (User user : userList) {
            if (user.getId() == id){
                return user;
            }
        }
        return null;
    }

    //修改指定用戶id信息
    @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";
    }

    //刪除指定用戶id信息
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable("id")Long id){
        userList.remove(getUser(id));
        return "success";
    }
}

 

今天知識有點多,有點雜,不少代碼都沒有貼出來了,我仍是比較懶,就總結了一些重要的知識點,應該不太全面,以後有時間會繼續完善的

做爲初學者的我,這東西不是太好用,可能用spring習慣了,不過大多的知識仍是比較基礎的,今天學習比較輕鬆,明天繼續努力啦

相關文章
相關標籤/搜索