Restful風格知識點
@RestController注解
在類上添加@RestController可以默認類中的所有方法都帶有@ResponseBody注解,可以省去一個個添加的麻煩。
@RestController
@RequestMapping("/restful")
//@CrossOrigin(origins = {"http://localhost:8080","http://www.imooc.com"})
//@CrossOrigin(origins = "*",maxAge = 3600)
public class RestfulController {
@GetMapping("/request")
//@ResponseBody
public String doGetRequest(){
return "{\"message\":\"返回查詢結(jié)果\"}";
}
// POST /article/1
// POST /restful/request/100
@PostMapping("/request/{rid}")
//@ResponseBody
public String doPostRequest(@PathVariable("rid") Integer requestId, Person person){
System.out.println(person.getName() + ":" + person.getAge());
return "{\"message\":\"數(shù)據(jù)新建成功\",\"id\":" + requestId + "}";
}
@PutMapping("/request")
//@ResponseBody
public String doPutRequest(Person person){
System.out.println(person.getName() + ":" + person.getAge());
return "{\"message\":\"數(shù)據(jù)更新成功\"}";
}
@DeleteMapping("/request")
//@ResponseBody
public String doDeleteRequest(){
return "{\"message\":\"數(shù)據(jù)刪除成功\"}";
}
@GetMapping("/person")
public Person findByPersonId(Integer id){
Person p = new Person();
if(id==1){
p.setName("lily");
p.setAge(23);
}else if(id==2){
p.setName("smith");
p.setAge(22);
}
return p;
}
@GetMapping("/persons")
public List<Person> findPersons(){
List list = new ArrayList();
Person p1 = new Person();
p1.setName("lily");
p1.setAge(23);
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("smith");
p2.setAge(22);
p2.setBirthday(new Date());
list.add(p1);
list.add(p2);
return list;
}
}
路徑變量
@PathVariable注解可以讓控制方法接收前端傳來的請求中的路徑變量。例如下面這個例子,無論前端傳來1還是100這個id都能被控制方法中的requestId這個變量通過@PathVariable注解來接收從而在控制方法中使用。
// POST /restful/request/1
// POST /restful/request/100
@PostMapping("/request/{rid}")
//@ResponseBody
public String doPostRequest(@PathVariable("rid") Integer requestId, Person person){
System.out.println(person.getName() + ":" + person.getAge());
return "{\"message\":\"數(shù)據(jù)新建成功\",\"id\":" + requestId + "}";
}
簡單請求與非簡單請求
簡單請求是指標準結(jié)構(gòu)的HTTP請求對應(yīng)GET/POST請求
非簡單請求是復(fù)雜要求的HTTP請求指PUT/DELETE、擴展標準請求
兩者最大區(qū)別是非簡單請求發(fā)送前需要發(fā)送預(yù)檢請求
SpringMVC默認只支持get、post請求,要處理非簡單請求需要在web.xml中配置過濾器。
<filter>
<filter-name>formContentFilter</filter-name>
<filter-class>org.springframework.web.filter.FormContentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>formContentFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
JSON序列化
首先在項目中添加依賴。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.9</version>
</dependency>
然后在控制方法中返回實體對象即可,如果有多個實體需要返回,則可以使用List。
@GetMapping("/person")
public Person findByPersonId(Integer id){
Person p = new Person();
if(id==1){
p.setName("lily");
p.setAge(23);
}else if(id==2){
p.setName("smith");
p.setAge(22);
}
return p;
}
@GetMapping("/persons")
public List<Person> findPersons(){
List list = new ArrayList();
Person p1 = new Person();
p1.setName("lily");
p1.setAge(23);
p1.setBirthday(new Date());
Person p2 = new Person();
p2.setName("smith");
p2.setAge(22);
p2.setBirthday(new Date());
list.add(p1);
list.add(p2);
return list;
}
如果實體類中包含了日期變量,則需要使用特殊的注解進行格式轉(zhuǎn)變。
public class Person {
private String name;
private Integer age;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss" , timezone = "GMT+8")
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
瀏覽器的跨域訪問
同源策略:
同源策略阻止從一個域加載的腳本去獲取另一個域上的資源
只要協(xié)議、域名、端口有任何一個不同,都被當作是不同的域
瀏覽器Console看到Access-Control-Allow-Origin就代表跨域了
例子:
允許跨域的標簽:
<img>- 顯示遠程圖片
<script>- 加載遠程JS
<link> - 加載遠程CSS
請求頭中的Sec-Fetch-Mode:cors說明這是一個跨域訪問的請求。
響應(yīng)頭中的Vary: Origin,Access-Control-Request-Method, Access-Control-Request-Headers通知瀏覽器這是一個允許跨域訪問的url。
在控制類之前添加注解解決跨域訪問問題。
使用@CrossOrigin注解添加允許訪問的url。
maxAge參數(shù)設(shè)置緩存預(yù)檢請求結(jié)果的時間。
@CrossOrigin(origins = {"http://localhost:8080","http://www.imooc.com"},maxAge = 3600)
在配置文件中添加配置解決跨域訪問問題。
在applicationContext.xml中添加mvc:cors設(shè)置允許訪問的url。文章來源:http://www.zghlxwxcb.cn/news/detail-495294.html
<mvc:cors>
<mvc:mapping path="/restful/**"
allowed-origins="http://localhost:8080,http://www.imooc.com"
max-age="3600"/>
</mvc:cors>
path代表允許訪問哪個路徑下的資源。
注:注解和配置一起使用時,以注解配置為準。文章來源地址http://www.zghlxwxcb.cn/news/detail-495294.html
到了這里,關(guān)于Restful風格筆記的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!