SpringMvc 中的實用工具類介紹(包括 ResponseEntity、 RestTemplate、WebUtils 等)

此部份內容將包含 ResponseEntity、 RestTemplate、WebUtils 等html

 

1. ResponseEntityjava

① Sprring Mvc 中做爲方法的返回值使用法web

@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 與 多個 headersspring

@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");
    }
}

 ③ 文件下載api

@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()返回值被使用cookie

ResponseEntity<String> entity = template.getForEntity("http://example.com", String.class);
String body = entity.getBody();
MediaType contentType = entity.getHeaders().getContentType();
HttpStatus statusCode = entity.getStatusCode();

 ⑤ 能夠很方便地返回不一樣類型的結果session

@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.判斷字符串是否爲空app

StringUtils .hasText(str) 與 StringUtils .hasLength(str)  前者包含後者,而且判斷不爲 null,有長度,而且不全爲空白字符。post

 

3.操做 cookie 與 sessionfetch

獲取 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

相關文章
相關標籤/搜索