此部分內容將包含 ResponseEntity、 RestTemplate、WebUtils 等
1. ResponseEntity
① Sprring Mvc 中作為方法的返回值使用法
@RequestMapping("/demo")
public ResponseEntity<?> getDemo(String username) {
User user = userService.getUserByUsername(username);
if (user != null)) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.badRequest().body(null);
}
}
② 設置 header 與 多個 headers
@RequestMapping("/demo")
public ResponseEntity<?> getDemo(String username) {
User user = userService.getUserByUsername(username);
if (user != null)) {
return ResponseEntity.ok(user);
} else {
return ResponseEntity.notFound().header("MyResponseHeader", "MyValue").build("Could't found by the username");
}
}
③ 文件下載
@ResponseBody
@RequestMapping(value = "/file_download", method = RequestMethod.GET)
public ResponseEntity courseFileDownload(String name, String path) {
try {
String url = internalStorage + "/" + COURSE_MATERIAL_FILE_BUCKET + "/" + path;
InputStream inputStream = new URL(url).openStream();
InputStreamResource resource = new InputStreamResource(inputStream);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM).header(HttpHeaders.CONTENT_DISPOSITION,
"attachment;filename=" + URLEncoder.encode(name, "UTF-8")).body(resource);
} catch (IOException e) {
return ResponseEntity.badRequest().body("文件不存在!");
}
}
④ 在 RestTemplate 中作為 getForEntity() 與 exchange()返回值被使用
ResponseEntity<String> entity = template.getForEntity("http://example.com", String.class);
String body = entity.getBody();
MediaType contentType = entity.getHeaders().getContentType();
HttpStatus statusCode = entity.getStatusCode();
⑤ 可以很方便地返回不同類型的結果
@RequestMapping(value = "/get_wx_acode", method = RequestMethod.GET)
public ResponseEntity getWxACode(WxACodeRequest wxACodeRequest) {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(new MappingJackson2HttpMessageConverter());
messageConverters.add(new ByteArrayHttpMessageConverter());
RestTemplate restTemplate = new RestTemplate(messageConverters);
String accessToken = fetchToken();
String aCodeUrl = String.format(
"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", accessToken);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<WxACodeRequest> entity = new HttpEntity<>(wxACodeRequest, headers);
try {
return restTemplate.postForEntity(aCodeUrl, entity, byte[].class);
} catch (RestClientException e) {
logger.error("get_wx_acode api error", e);
// or return ResponseEntity.badRequest().build(); // build for no body
return ResponseEntity.badRequest().body(ResponseResult.badRequest("400", "api error"));
}
}
2.判斷字符串是否為空
StringUtils .hasText(str) 與 StringUtils .hasLength(str) 前者包含后者,並且判斷不為 null,有長度,並且不全為空白字符。
3.操作 cookie 與 session
獲取 cookie
@CookieValue(value="myCookie", defaultValue="someValue",required=false)
設置 cookie (還可以直接在 response header 里添加)
Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setSecure(useSecureCookie); // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL cookie.setMaxAge(expiryTime); cookie.setPath(cookiePath); // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories response.addCookie(cookie);
顯示聲明存入 session 中的對象
public String handle(@SessionAttribute User user) {
設置 RedirectAttributes 添加 FlashAttribute
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session,
final RedirectAttributes redirectAttributes) {
if (!verify(username, password)) {
redirectAttributes.addFlashAttribute("message", "username/password invalid");
return "redirect:/login";
}
session.setAttribute(SESSION_LOGGED_IN, true);
redirectAttributes.addFlashAttribute("message", "Login Success");
return "redirect:/";
}
4.WebUtils 與 ServletRequestUtils
① 操作 參數
String param
= ServletRequestUtils.getStringParameter(
request, "param", "DEFAULT");
② 操作 session 或 cookie
WebUtils.setSessionAttribute(request, "parameter", param);
model.addAttribute("parameter", "You set: " + (String) WebUtils
.getSessionAttribute(request, "parameter"));
參考資料
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/ResponseEntity.html
https://www.baeldung.com/spring-webutils-servletrequestutils
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/util/WebUtils.html
https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StringUtils.html
