java ranger rest_使用REST
使用Spring MVC開發Web應用程序的主要工作就是編寫Controller邏輯。在Web應用中,除了需要使用MVC給用戶顯示頁面外,還有一類API接口,我們稱之為REST,通常輸入輸出都是JSON,便于第三方調用或者使用頁面JavaScript與之交互。
直接在Controller中處理JSON是可以的,因為Spring MVC的@GetMapping和@PostMapping都支持指定輸入和輸出的格式。如果我們想接收JSON,輸出JSON,那么可以這樣寫:
@PostMapping(value = "/rest",
consumes = "application/json;charset=UTF-8",
produces = "application/json;charset=UTF-8")
@ResponseBody
public String rest(@RequestBody User user) {
return "{\"restSupport\":true}";
}
對應的Maven工程需要加入Jackson這個依賴:com.fasterxml.jackson.core:jackson-databind:2.11.0
注意到@PostMapping使用consumes聲明能接收的類型,使用produces聲明輸出的類型,并且額外加了@ResponseBody表示返回的String無需額外處理,直接作為輸出內容寫入HttpServletResponse。輸入的JSON則根據注解@RequestBody直接被Spring反序列化為User這個JavaBean。
使用curl命令測試一下:
$ curl -v -H "Content-Type: application/json" -d '{"email":"bob@example.com"}' http://localhost:8080/rest
> POST /rest HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 27
>
< HTTP/1.1 200
< Content-Type: application/json;charset=utf-8
< Content-Length: 20
< Date: Sun, 10 May 2020 09:56:01 GMT
<
{"restSupport":true}
輸出正是我們寫入的字符串。
直接用Spring的Controller配合一大堆注解寫REST太麻煩了,因此,Spring還額外提供了一個@RestController注解,使用@RestController替代@Controller后,每個方法自動變成API接口方法。我們還是以實際代碼舉例,編寫ApiController如下:
@RestController
@RequestMapping("/api")
public class ApiController {
@Autowired
UserService userService;
@GetMapping("/users")
public List users() {
return userService.getUsers();
}
@GetMapping("/users/{id}")
public User user(@PathVariable("id") long id) {
return userService.getUserById(id);
}
@PostMapping("/signin")
public Map signin(@RequestBody SignInRequest signinRequest) {
try {
User user = userService.signin(signinRequest.email, signinRequest.password);
return Map.of("user", user);
} catch (Exception e) {
return Map.of("error", "SIGNIN_FAILED", "message", e.getMessage());
}
}
public static class SignInRequest {
public String email;
public String password;
}
}
編寫REST接口只需要定義@RestController,然后,每個方法都是一個API接口,輸入和輸出只要能被Jackson序列化或反序列化為JSON就沒有問題。我們用瀏覽器測試GET請求,可直接顯示JSON響應:
要測試POST請求,可以用curl命令:
$ curl -v -H "Content-Type: application/json" -d '{"email":"bob@example.com","password":"bob123"}' http://localhost:8080/api/signin
> POST /api/signin HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.64.1
> Accept: */*
> Content-Type: application/json
> Content-Length: 47
>
< HTTP/1.1 200
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Sun, 10 May 2020 08:14:13 GMT
<
{"user":{"id":1,"email":"bob@example.com","password":"bob123","name":"Bob",...
注意觀察上述JSON的輸出,User能被正確地序列化為JSON,但暴露了password屬性,這是我們不期望的。要避免輸出password屬性,可以把User復制到另一個UserBean對象,該對象只持有必要的屬性,但這樣做比較繁瑣。另一種簡單的方法是直接在User的password屬性定義處加上@JsonIgnore表示完全忽略該屬性:
public class User {
...
@JsonIgnore
public String getPassword() {
return password;
}
...
}
但是這樣一來,如果寫一個register(User user)方法,那么該方法的User對象也拿不到注冊時用戶傳入的密碼了。如果要允許輸入password,但不允許輸出password,即在JSON序列化和反序列化時,允許寫屬性,禁用讀屬性,可以更精細地控制如下:
public class User {
...
@JsonProperty(access = Access.WRITE_ONLY)
public String getPassword() {
return password;
}
...
}
同樣的,可以使用@JsonProperty(access = Access.READ_ONLY)允許輸出,不允許輸入。
練習
小結
使用@RestController可以方便地編寫REST服務,Spring默認使用JSON作為輸入和輸出。
要控制序列化和反序列化,可以使用Jackson提供的@JsonIgnore和@JsonProperty注解。
總結
以上是生活随笔為你收集整理的java ranger rest_使用REST的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2016招商银行信用卡快速积分最新方法
- 下一篇: mysql group by自定义_my