此部分内容将包含 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