二、SpringBoot接口Http協議開發實戰8節課(1-6)

一、SpringBoot2.xHTTP請求配置講解css

簡介:SpringBoot2.xHTTP請求註解講解和簡化註解配置技巧html

一、@RestController and @RequestMapping是springMVC的註解,不是springboot特有的java

二、@RestController = @Controller+@ResponseBodyweb

三、@SpringBootApplication = @Configuration+@EnableAutoConfiguration+@ComponentScan面試

localhost:8080spring

Demo1:json

SampleControler.java後端

 1 package net.xdclass.demo.controller;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import org.springframework.boot.*;
 7 import org.springframework.boot.autoconfigure.*;
 8 import org.springframework.web.bind.annotation.*;
 9 
10 @RestController
11 public class SampleControler {
12 
13     @RequestMapping("/")
14     String home() {
15         return "Hello World!";
16     }
17 
18     /*public static void main(String[] args) throws Exception {
19         SpringApplication.run(SampleControler.class, args);
20     }*/
21     
22     @RequestMapping("/test")
23     public Map<String, String> testMap(){
24         Map<String,String> map = new HashMap<>();
25         map.put("name", "xdclass");
26         return map;
27     }
28 
29 }

XdClassApplication.javaapi

 1 package net.xdclass.demo;
 2 
 3 import org.springframework.boot.SpringApplication;
 4 import org.springframework.boot.SpringBootConfiguration;
 5 import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
 6 import org.springframework.boot.autoconfigure.SpringBootApplication;
 7 import org.springframework.context.annotation.ComponentScan;
 8 
 9 @SpringBootApplication    //一個註解頂下面三個註解
10 /*@SpringBootConfiguration
11 @EnableAutoConfiguration
12 @ComponentScan*/
13 
14 //啓動類
15 public class XdClassApplication {
16 
17     public static void main(String[] args) {
18         SpringApplication.run(XdClassApplication.class, args);
19     }
20 }

訪問:http://localhost:8080/test瀏覽器

二、開發接口必備工具之PostMan接口調試工具介紹和使用

簡介:模擬Http接口測試工具PostMan安裝和講解

 

一、接口調試工具安裝和基本使用

二、下載地址:https://www.getpostman.com/

 說明:

History能夠保存歷史請求

Collections:測試的請求沒有問題後,能夠保存到此處

 

點擊save

 同時可使用Download方式將內容以json形式導出

 

三、SpringBoot基礎HTTP接口GET請求實戰

簡介:講解springboot接口,http的get請求,各個註解使用

一、GET請求

一、單一參數@RequestMapping(path = "/{id}", method = RequestMethod.GET)

1) public String getUser(@PathVariable String id ) {}

 

2)@RequestMapping(path = "/{depid}/{userid}", method = RequestMethod.GET) 能夠同時指定多個提交方法

getUser(@PathVariable("depid") String departmentID,@PathVariable("userid") String userid)

 

3)一個頂倆

@GetMapping = @RequestMapping(method = RequestMethod.GET)

@PostMapping = @RequestMapping(method = RequestMethod.POST)

@PutMapping = @RequestMapping(method = RequestMethod.PUT)

@DeleteMapping = @RequestMapping(method = RequestMethod.DELETE)

 

4)@RequestParam(value = "name", required = true)

能夠設置默認值,好比分頁 

 

4)@RequestBody 請求體映射實體類

須要指定http頭爲 content-type爲application/json charset=utf-8

 

5)@RequestHeader 請求頭,好比鑑權

@RequestHeader("access_token") String accessToken

 

6)HttpServletRequest request自動注入獲取參數

 例:GetController.java

  1 package net.xdclass.demo.controller;
  2 import java.util.HashMap;
  3 import java.util.Map;
  4 import javax.servlet.http.HttpServletRequest;
  5 import net.xdclass.demo.domain.User;
  6 import org.springframework.web.bind.annotation.GetMapping;
  7 import org.springframework.web.bind.annotation.PathVariable;
  8 import org.springframework.web.bind.annotation.RequestBody;
  9 import org.springframework.web.bind.annotation.RequestHeader;
 10 import org.springframework.web.bind.annotation.RequestMapping;
 11 import org.springframework.web.bind.annotation.RequestMethod;
 12 import org.springframework.web.bind.annotation.RequestParam;
 13 import org.springframework.web.bind.annotation.RestController;
 14 
 15 //測試http協議的get請求
 16 @RestController
 17 public class GetController {
 18 
 19     private Map<String,Object> params = new HashMap<>();
 20     
 21     /**
 22      * 功能描述:測試restful協議,從路徑中獲取字段
 23      * (協議的命名一般用字母組合和下劃線方式,不用駝峯式命名)
 24      * @param cityId
 25      * @param userId
 26      * @return
 27      */
 28     @RequestMapping(path = "/{city_id}/{user_id}", method = RequestMethod.GET)
 29     public Object findUser(@PathVariable("city_id") String cityId,
 30             @PathVariable("user_id") String userId ){
 31         params.clear();
 32         
 33         params.put("cityId", cityId);
 34         params.put("userId", userId);
 35         
 36         return params;
 37         
 38     }
 39 
 40     /**
 41      * 功能描述:測試GetMapping
 42      * @param from
 43      * @param size
 44      * @return
 45      */
 46     @GetMapping(value="/v1/page_user1")
 47     public Object pageUser(int  from, int size ){
 48         params.clear();
 49         params.put("from", from);
 50         params.put("size", size);
 51         
 52         return params;
 53         
 54     }
 55 
 56     /**
 57      * 功能描述:默認值(defaultValue),是否必須的參數
 58      * @param from
 59      * @param size
 60      * @return
 61      */
 62     @GetMapping(value="/v1/page_user2")
 63     public Object pageUserV2(@RequestParam(defaultValue="0",name="page") int  from, int size ){
 64         
 65         params.clear();
 66         params.put("from", from);
 67         params.put("size", size);
 68         
 69         return params;
 70         
 71     }
 72 
 73     /**
 74      * 功能描述:bean對象傳參
 75      * 注意:一、注意須要指定http頭爲 content-type爲application/json
 76      *         二、使用body傳輸數據
 77      * @param user
 78      * @return
 79      */
 80     @RequestMapping("/v1/save_user")
 81     public Object saveUser(@RequestBody User user){
 82         params.clear();
 83         params.put("user", user);
 84         return params;    
 85     }
 86     
 87     /**
 88      * 功能描述:測試獲取http頭信息
 89      * @param accessToken
 90      * @param id
 91      * @return
 92      */
 93     @GetMapping("/v1/get_header")
 94     public Object getHeader(@RequestHeader("access_token") String accessToken, String id){
 95         params.clear();
 96         params.put("access_token", accessToken);
 97         params.put("id", id);
 98         return params;    
 99     }
100 
101     @GetMapping("/v1/test_request")
102     public Object testRequest(HttpServletRequest request){
103         params.clear();
104         String id = request.getParameter("id");
105         params.put("id", id);
106         return params;    
107     }
108     
109     
110 }

User.java

 1 package net.xdclass.demo.domain;
 2 
 3 public class User {
 4 
 5     private int age;
 6     
 7     private String pwd;
 8     
 9     private String phone;
10 
11     public int getAge() {
12         return age;
13     }
14 
15     public void setAge(int age) {
16         this.age = age;
17     }
18 
19     public String getPwd() {
20         return pwd;
21     }
22 
23     public void setPwd(String pwd) {
24         this.pwd = pwd;
25     }
26 
27     public String getPhone() {
28         return phone;
29     }
30 
31     public void setPhone(String phone) {
32         this.phone = phone;
33     }
34 
35     public User() {
36         super();
37     }
38 
39     public User(int age, String pwd, String phone) {
40         super();
41         this.age = age;
42         this.pwd = pwd;
43         this.phone = phone;
44     }
45     
46     
47 }

 

四、SpringBoot基礎HTTP接口POST,PUT,DELETE請求實戰

簡介:講解http請求post,put, delete提交方式

 代碼示例:

 1 package net.xdclass.demo.controller;
 2 import java.util.HashMap;
 3 import java.util.Map;
 4 import org.springframework.web.bind.annotation.DeleteMapping;
 5 import org.springframework.web.bind.annotation.PostMapping;
 6 import org.springframework.web.bind.annotation.PutMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 //測試http協議的post,del,put請求
10 @RestController
11 public class OtherHttpController {
12 
13     private Map<String,Object> params = new HashMap<>();
14 
15     /**
16      * 功能描述:測試PostMapping
17      * @param accessToken
18      * @param id
19      * @return
20      */
21     @PostMapping("/v1/login")
22     public Object login(String id, String pwd){
23         params.clear();
24         params.put("id", id);
25         params.put("pwd", pwd);
26         return params;    
27     }
28     
29     
30     @PutMapping("/v1/put")//經常使用於更新
31     public Object put(String id){
32         params.clear();
33         params.put("id", id);
34         return params;    
35     }
36     
37 
38     @DeleteMapping("/v1/del")//刪除操做
39     public Object del(String id){
40         params.clear();
41         params.put("id", id);
42         return params;    
43     }
44     
45 }

 

五、經常使用json框架介紹和Jackson返回結果處理

簡介:介紹經常使用json框架和註解的使用,自定義返回json結構和格式

 

一、經常使用框架 阿里 fastjson,谷歌gson等

JavaBean序列化爲Json,性能:Jackson > FastJson > Gson > Json-lib 同個結構

Jackson、FastJson、Gson類庫各有優勢,各有本身的專長

空間換時間,時間換空間

 

二、jackson處理相關自動

指定字段不返回:@JsonIgnore

User.java

測試:

前臺返回信息:

 

指定日期格式:@JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")

空字段不返回:@JsonInclude(Include.NON_NUll)

指定別名:@JsonProperty

 代碼示例:

User.java

 1 package net.xdclass.demo.domain;
 2 
 3 import java.util.Date;
 4 import com.fasterxml.jackson.annotation.JsonFormat;
 5 import com.fasterxml.jackson.annotation.JsonIgnore;
 6 import com.fasterxml.jackson.annotation.JsonInclude;
 7 import com.fasterxml.jackson.annotation.JsonInclude.Include;
 8 import com.fasterxml.jackson.annotation.JsonProperty;
 9 
10 public class User {
11 
12     private int age;
13     
14     @JsonIgnore//前臺不返回該字段信息,保護數據安全
15     private String pwd;
16     
17     @JsonProperty("account")
18     @JsonInclude(Include.NON_NULL)
19     private String phone;
20 
21     @JsonFormat(pattern="yyyy-MM-dd hh:mm:ss",locale="zh",timezone="GMT+8")
22     private Date createTime;
23     
24     public Date getCreateTime() {
25         return createTime;
26     }
27 
28     public void setCreateTime(Date createTime) {
29         this.createTime = createTime;
30     }
31 
32     public int getAge() {
33         return age;
34     }
35 
36     public void setAge(int age) {
37         this.age = age;
38     }
39 
40     public String getPwd() {
41         return pwd;
42     }
43 
44     public void setPwd(String pwd) {
45         this.pwd = pwd;
46     }
47 
48     public String getPhone() {
49         return phone;
50     }
51 
52     public void setPhone(String phone) {
53         this.phone = phone;
54     }
55 
56     public User() {
57         super();
58     }
59 
60     public User(int age, String pwd, String phone, Date createTime) {
61         super();
62         this.age = age;
63         this.pwd = pwd;
64         this.phone = phone;
65         this.createTime = createTime;
66     }
67 }

測試代碼:

1     @GetMapping("/testjson")
2     public Object testjson(){
3         
4         return new User(11, "abc123", "1001000", new Date());
5     }

前臺返回結果:

 

六、SpringBoot2.x目錄文件結構講解

簡介:講解SpringBoot目錄文件結構和官方推薦的目錄規範

 

一、目錄講解

src/main/java:存放代碼

src/main/resources

static: 存放靜態文件,好比 css、js、image, (訪問方式 http://localhost:8080/js/main.js)

templates:存放靜態頁面jsp,html,tpl

config:存放配置文件,application.properties

resources:

 

二、引入依賴 Thymeleaf

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

注意:若是不引入這個依賴包,html文件應該放在默認加載文件夾裏面,

好比resources、static、public這個幾個文件夾,才能夠訪問(這三個文件夾中的內容能夠直接訪問)

 

例如,要訪問templates下的index.html

index.html:

訪問:http://localhost:8080/api/v1/gopage

瀏覽器結果:

三、同個文件的加載順序,靜態資源文件

Spring Boot 默認會挨個從

META/resources > resources > static > public  裏面找是否存在相應的資源,若是有則直接返回。

 

四、默認配置

1)官網地址:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-spring-mvc-static-content

2)spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/ 

 自定義文件夾代碼示例:

在src/main/resources文件夾下建立application.properties

 1 spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/test/  

訪問test文件夾下的test3.js

在配置文件中,加入classpath:/test/,訪問:http://localhost:8080/test3.js

瀏覽器結果:

若不加入該內容,瀏覽器會提示錯誤信息,沒法訪問

五、靜態資源文件存儲在CDN

面試題:如何加快網站的訪問速度?

答:大型公司一般將靜態資源文件存儲在CDN,響應快。SpringBoot搭建的項目一般會先後端分離。

相關文章
相關標籤/搜索